src/JsRender/NodeToJs.vala
[app.Builder.js] / src / JsRender / NodeToJs.vala
1 /**
2  * 
3  * Code to convert node tree to Javascript...
4  * 
5  * usage : x = (new JsRender.NodeToJs(node)).munge();
6  * 
7 */
8
9
10
11
12 public class JsRender.NodeToJs : Object {
13
14         static uint indent = 1;
15         static string indent_str = " ";
16         
17         Node node;
18         Gee.ArrayList<string>  doubleStringProps;  // need to think if this is a good idea like this
19         string pad;
20         
21           
22         Gee.HashMap<string,string> out_props;
23         Gee.HashMap<string,string> out_listeners;       
24         Gee.HashMap<string,Node> out_nodeprops;
25         Gee.ArrayList<Node> out_children;
26         Gee.HashMap<string,Gee.ArrayList<Node>> out_props_array;
27         Gee.HashMap<string,Gee.ArrayList<string>> out_props_array_plain;        
28         
29         NodeToJs top;
30         public string ret;
31         
32         public int cur_line;
33
34         
35         public NodeToJs( Node node, Gee.ArrayList<string> doubleStringProps, string pad, NodeToJs? parent) 
36         {
37                 this.node = node;
38                 this.doubleStringProps = doubleStringProps;
39                 this.pad = pad;
40                 
41                 //this.els = new Gee.ArrayList<string>(); 
42                 //this.ar_props = new Gee.HashMap<string,string>();
43                 
44                 
45                 this.out_props = new Gee.HashMap<string,string>();
46                 this.out_listeners = new Gee.HashMap<string,string>();  
47                 this.out_nodeprops = new Gee.HashMap<string,Node>() ;
48                 this.out_children = new Gee.ArrayList<Node> ();
49                 this.out_props_array = new Gee.HashMap<string,Gee.ArrayList<Node>>() ;
50                 this.out_props_array_plain = new Gee.HashMap<string,Gee.ArrayList<string>>() ;
51         
52                 
53                 
54                 this.cur_line = parent == null ? 0 : parent.cur_line  ; //-1 as we usuall concat onto the existin gline?
55                 this.ret = "";
56                 this.top = parent == null ? this : parent.top;
57                 // reset the maps...
58                 if (parent == null) {
59                         node.node_lines = new Gee.ArrayList<int>();
60                         node.node_lines_map = new Gee.HashMap<int,Node>();
61                  }
62         }
63         
64         
65         
66         
67         
68         
69         public string munge ( )
70         {
71                 //return this.mungeToString(this.node);
72
73                 this.node.line_start = this.cur_line;
74                 
75                 this.checkChildren();
76                 this.readProps();
77                 //this.readArrayProps();
78                 this.readListeners();
79
80                 if (!this.node.props.has_key("* xinclude")) {
81                         this.iterChildren();
82                 }
83                 
84                 
85                 
86                 // no properties to output...
87                 //if (this.els.size < 1) {
88                 //      return "";
89                 //}
90
91                 this.mungeOut();
92                 return this.ret;
93                  
94         } 
95                 /**
96         
97         This currently works by creating a key/value array of this.els, which is just an array of properties..
98         this is so that join() works...
99         
100         how this could work:
101         a) output header
102         b) output plan properties.
103         c) output listeners..
104         c) output *prop
105         g) output prop_arrays..
106         d) output children
107         e) 
108         
109         
110         
111         */
112         
113         public Gee.ArrayList<string> orderedPropKeys() {
114         
115                 var ret = new Gee.ArrayList<string> ();
116                 var niter = this.out_props.map_iterator();
117                 while(niter.next()) {
118                         ret.add(niter.get_key());
119                 }
120                 
121                 ret.sort((  a,  b) => {
122                         return ((string)a).collate((string)b);
123                         //if (a == b) return 0;
124                         //return a < b ? -1 : 1;
125                 });
126                 return ret;
127         }
128         public Gee.ArrayList<string> orderedListenerKeys() {
129         
130                 var ret = new Gee.ArrayList<string> ();
131                 var niter = this.out_listeners.map_iterator();
132                 while(niter.next()) {
133                         ret.add(niter.get_key());
134                 }
135                 
136                 ret.sort((  a,  b) => {
137                         return ((string)a).collate((string)b);
138                         //if (a == b) return 0;
139                         //return a < b ? -1 : 1;
140                 });
141                 return ret;
142         }
143         
144
145         public string mungeOut()
146         {
147                 this.node.line_start = this.cur_line;
148                 this.top.node.setNodeLine(this.cur_line, this.node);
149                 var spad = this.pad.substring(0, this.pad.length-indent);
150                 
151                 if (this.node.props.has_key("* xinclude")) {
152                         this.addLine("Roo.apply(" + this.node.props.get("* xinclude") + "._tree(), {");
153          
154                 } else {
155                         this.addLine("{");
156                 }
157                 var suffix = "";
158                 // output the items...
159                 // work out remaining items...
160                 var  total_nodes = this.out_props.size + 
161                                 this.out_props_array_plain.size + 
162                                 (this.out_listeners.size > 0 ? 1 : 0) +
163                                 this.out_nodeprops.size +
164                                 this.out_props_array.size +
165                                 (this.out_children.size > 0 ? 1 : 0);
166                 
167                 
168                 
169                 // plain properties.
170                 var iter = this.orderedPropKeys().list_iterator();
171                 while(iter.next()) {
172                         total_nodes--;
173                         suffix = total_nodes > 0 ? "," : "";
174                         var k = iter.get();
175                         var v = this.out_props.get(k);
176                         
177                         this.addMultiLine(this.pad + k + " : " + v + suffix);
178                 }
179          
180                 // listeners..
181                 
182                 if (this.out_listeners.size > 0 ) { 
183                         total_nodes--;
184                         this.addLine(this.pad + "listeners : {");
185                         iter = this.orderedListenerKeys().list_iterator();
186                          
187                         var sz = this.out_listeners.size;
188                         while(iter.next()) {
189                                 sz--;
190                                 suffix = sz > 0 ? "," : "";
191                                 var k = iter.get();
192                                 var v = this.out_listeners.get(k);
193                                 this.addMultiLine(this.pad + indent_str + k + " : " + v + suffix);
194                         }
195                         suffix = total_nodes > 0 ? "," : "";
196                         this.addLine(this.pad + "}" + suffix);                  
197                         
198                 }
199                 
200                 //------- at this point it is the end of the code relating directly to the object..
201                 
202                 this.node.line_end = this.cur_line;
203                 
204                 
205                 
206                 // * prop
207
208                 var niter = this.out_nodeprops.map_iterator();
209
210                 while(niter.next()) {
211                         total_nodes--;
212                         suffix = total_nodes > 0 ? "," : "";
213                         var l = this.pad + niter.get_key() + " : " + 
214                                         this.mungeChildNew(this.pad + indent_str, niter.get_value()) + suffix;
215                         this.addMultiLine(l);
216                 }                        
217                 // prop arrays...
218                 
219                 var piter = this.out_props_array.map_iterator();
220
221                 while(piter.next()) {
222                         total_nodes--;
223
224                         this.addLine(this.pad + piter.get_key() + " : [");
225                         var pliter = piter.get_value().list_iterator();
226                         while (pliter.next()) {
227                                 suffix = pliter.has_next()  ? "," : "";
228                                 this.addMultiLine(this.pad + indent_str + 
229                                         this.mungeChildNew(this.pad + indent_str  + indent_str, pliter.get()) + suffix);
230                         }
231
232                         suffix = total_nodes > 0 ? "," : "";
233  
234                         this.addLine(this.pad + "]" + suffix);                  
235                 }       
236                 
237                 // children..
238                 if (this.out_children.size > 0) {
239                         this.addLine(this.pad + "items  : [" );
240                         var cniter = this.out_children.list_iterator();
241                         while (cniter.next()) {
242                                 suffix = cniter.has_next()  ? "," : "";
243                                 this.addMultiLine(this.pad + indent_str +
244                                         this.mungeChildNew(this.pad + indent_str  + indent_str, cniter.get()) + suffix
245                                 );
246                                 
247                         }
248                         
249                         this.addLine(this.pad +   "]");
250                 }
251                 
252                 if (this.node.props.has_key("* xinclude")) {
253                         this.ret += spad + "})";
254          
255                 } else {
256                         this.ret += spad + "}";
257                 }
258                 
259                 this.node.sortLines();
260                 return this.ret;
261         
262         }
263         
264  
265         
266         
267         
268         public void addLine(string str= "")
269         {
270                 this.cur_line ++;
271                 //this.ret += str+ "\n";
272                 this.ret +=  "/*%d(%d-%d)*/ ".printf(this.cur_line -1, this.node.line_start,this.node.line_end) + str + "\n";
273                 
274                 
275         }
276         
277         public void addMultiLine(string str= "")
278         {
279                 var l = cur_line;
280                 this.cur_line += str.split("\n").length;
281                 this.ret +=   "/*%d(%d-%d)*/ ".printf(l, this.node.line_start,this.node.line_end)+ str + "\n";
282                 //this.ret +=   str + "\n";
283         }
284  
285         public string mungeChildNew(string pad ,  Node cnode )
286         {
287                 var x = new  NodeToJs(cnode, this.doubleStringProps, pad, this);
288          
289                 x.munge();
290                 return x.ret;
291         }
292         
293
294         
295         public void checkChildren () 
296         {
297                 
298                  
299                 // look throught he chilren == looking for * prop.. -- fixme might not work..
300                 
301                 
302                 if (!this.node.hasChildren()) {
303                         return;
304                 }
305                 // look for '*props'
306            
307                 for (var ii =0; ii< this.node.items.size; ii++) {
308                         var pl = this.node.items.get(ii);
309                         if (!pl.props.has_key("* prop")) {
310                                 //newitems.add(pl);
311                                 continue;
312                         }
313                         
314                         //print(JSON.stringify(pl,null,4));
315                         // we have a prop...
316                         //var prop = pl['*prop'] + '';
317                         //delete pl['*prop'];
318                         var prop = pl.get("* prop");
319                         print("got prop "+ prop + "\n");
320                         
321                         // name ends in [];
322                         if (! Regex.match_simple("\\[\\]$", prop)) {
323                                 // it's a standard prop..
324                                 
325                                 // munge property..??
326                                 
327                                 this.out_nodeprops.set(prop, pl);
328                                  
329                                 continue;
330                         }
331
332
333
334                         
335                         var sprop  = prop.replace("[]", "");
336                         print("sprop is : " + sprop + "\n");
337                         
338                         // it's an array type..
339                         //var old = "";
340                         if (!this.out_props_array.has_key(sprop)) {
341                                 this.out_props_array.set(sprop, new Gee.ArrayList<Node>());
342                         }
343                         
344                          
345                         this.out_props_array.get(sprop).add( pl);
346                         //this.ar_props.set(sprop, nstr);
347                          
348                         
349                 }
350                  
351         }
352         /*
353  * Standardize this crap...
354  * 
355  * standard properties (use to set)
356  *          If they are long values show the dialog..
357  *
358  * someprop : ....
359  * bool is_xxx  :: can show a pulldown.. (true/false)
360  * string html  
361  * $ string html  = string with value interpolated eg. baseURL + ".." 
362  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
363  * $ untypedvalue = javascript untyped value...  
364  * _ string html ... = translatable..
365
366  * 
367  * object properties (not part of the GOjbect being wrapped?
368  * # Gee.ArrayList<Xcls_fileitem> fileitems
369  * 
370  * signals
371  * @ void open 
372  * 
373  * methods -- always text editor..
374  * | void clearFiles
375  * | someJSmethod
376  * 
377  * specials
378  * * prop -- string
379  * * args  -- string
380  * * ctor -- string
381  * * init -- big string?
382  * 
383  * event handlers (listeners)
384  *   just shown 
385  * 
386  * -----------------
387  * special ID values
388  *  +XXXX -- indicates it's a instance property / not glob...
389  *  *XXXX -- skip writing glob property (used as classes that can be created...)
390  * 
391  * 
392  */
393         public void readProps()
394         {
395                 string left;
396                 Regex func_regex ;
397
398                 if (this.node.props.has_key("$ xns")) {
399                         this.out_props.set("'|xns'", "'" +  this.node.props.get("$ xns") + "'" );
400                         
401                         //this.els.add("'|xns' : '" + this.node.props.get("$ xns") + "'");
402
403                 }
404
405                 
406                 try {
407                         func_regex = new Regex("^\\s+|\\s+$");
408                 } catch (RegexError e) {
409                         print("failed to build regex");
410                         return;
411                 }
412                 // sort the key's so they always get rendered in the same order..
413                 
414                 var keys = new Gee.ArrayList<string>();
415                 var piter = this.node.props.map_iterator();
416                 while (piter.next() ) {
417                         string k;
418                         string ktype;
419                         string kflag;
420                         this.node.normalize_key(piter.get_key(), out k, out kflag, out ktype);
421                         
422                         keys.add(k);
423                 }
424                 
425                 keys.sort((  a,  b) => {
426                         return ((string)a).collate((string)b);
427                         //if (a == b) return 0;
428                         //return a < b ? -1 : 1;
429                 });
430                 
431                 
432                 
433                 for (var i = 0; i< keys.size; i++) {
434                         var key = this.node.get_key(keys.get(i));
435                         print("ADD KEY %s\n", key);
436                         string k;
437                         string ktype;
438                         string kflag;
439                         
440                         this.node.normalize_key(key, out k, out kflag, out ktype);
441                         
442                         
443                         var v = this.node.get(key);
444                          
445                         
446                         //if (this.skip.contains(k) ) {
447                         //      continue;
448                         //}
449                         if (  Regex.match_simple("\\[\\]$", k)) {
450                                 // array .. not supported... here?
451                                 
452
453                         }
454                         
455                         string leftv = k;
456                         // skip builder stuff. prefixed with  '.' .. just like unix fs..
457                         if (kflag == ".") { // |. or . -- do not output..
458                                 continue;
459                         }
460                          if (kflag == "*") {
461                                 // ignore '* prop'; ??? 
462                                 continue;
463                          }
464                                 
465                         
466                         if (Lang.isKeyword(leftv) || Lang.isBuiltin(leftv)) {
467                                 left = "'" + leftv + "'";
468                         } else if (Regex.match_simple("[^A-Za-z_]+",leftv)) { // not plain a-z... - quoted.
469                                 var val = this.node.quoteString(leftv);
470                                 
471                                 left = "'" + val.substring(1, val.length-2).replace("'", "\\'") + "'";
472                         } else {
473                                 left = leftv;
474                         }
475                          
476                          
477                         // next.. is it a function.. or a raw string..
478                         if (
479                                 kflag == "|" 
480                                 || 
481                                 kflag == "$" 
482                                 || 
483                                 ktype == "function"
484                                
485                                 // ??? any others that are raw output..
486                                 ) {
487                                 // does not hapepnd with arrays.. 
488                                 if (v.length < 1) {  //if (typeof(el) == 'string' && !obj[i].length) { //skip empty.
489                                         continue;
490                                 }
491                                 /*
492                                 print(v);
493                                 string str = "";
494                                 try {
495                                         str = func_regex.replace(v,v.length, 0, "");
496                                 } catch(Error e) {
497                                         print("regex failed");
498                                         return "";
499                                 }
500                                 */
501                                 var str = v.strip();
502                                   
503                                 var lines = str.split("\n");
504                                 var nstr = "" + str;
505                                 if (lines.length > 0) {
506                                         nstr =  string.joinv("\n" + this.pad, lines);
507                                         //nstr =  string.joinv("\n", lines);
508                                 }
509                                 this.out_props.set(left, nstr);
510                                 //print("==> " +  str + "\n");
511                                 //this.els.add(left + " : "+  nstr);
512                                 continue;
513                         }
514                         // standard..
515                         
516                         
517                         if (
518                                 Lang.isNumber(v) 
519                                 || 
520                                 Lang.isBoolean(v)
521                                 ||
522                                 ktype.down() == "boolean"
523                                 || 
524                                 ktype.down() == "bool"
525                                 || 
526                                 ktype.down() == "number"
527                                 || 
528                                 ktype.down() == "int"
529                             ) { // boolean or number...?
530                             this.out_props.set(left, v.down());
531                                 //this.els.add(left + " : " + v.down() );
532                                 continue;
533                         }
534                         
535                         // is it a translated string?
536                         
537                         
538                         
539                         
540                         // strings..
541                         //if (this.doubleStringProps.size < 1) {
542                         //      this.els.add(left + this.node.quoteString(v));
543                         //      continue;
544                         //}
545                    
546                         if ((this.doubleStringProps.index_of(k) > -1) || 
547                                 (ktype.down() == "string" && k[0] == '_')
548                         
549                         ) {
550                                 // then use the translated version...
551                                 
552                                 var com = " /* " + 
553                                         (v.split("\n").length > 1 ?
554                                                 ("\n" + this.pad +  string.joinv(this.pad +  "\n", v.split("\n")).replace("*/", "* - /") + "\n" + this.pad + "*/ ") :
555                                                 (v.replace("*/", "* - /") + " */")
556                                         );
557                                 
558                                 //this.els.add(left + " : _this._strings['" + 
559                                 //      GLib.Checksum.compute_for_string (ChecksumType.MD5, v) +
560                                 //      "']"
561                                 //);
562                                 this.out_props.set(left, "_this._strings['" + 
563                                         GLib.Checksum.compute_for_string (ChecksumType.MD5, v) +
564                                         "']" + com);
565                                 continue;
566                         }
567                  
568                         // otherwise it needs to be encapsulated.. as single quotes..
569                         
570                         var vv = this.node.quoteString(v);
571                         // single quote.. v.substring(1, v.length-1).replace("'", "\\'") + "'";
572                         //this.els.add(left + " : " +  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
573                         this.out_props.set(left,  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
574
575                    
576                    
577                    
578                 }
579         }
580          
581         public void readListeners()
582         {
583                 
584                 if (this.node.listeners.size < 1) {
585                         return;
586                 }
587                 // munge the listeners.
588                 //print("ADDING listeners?");
589         
590  
591         
592         
593                 var keys = new Gee.ArrayList<string>();
594                 var piter = this.node.listeners.map_iterator();
595                 while (piter.next() ) {
596                          
597                         keys.add(piter.get_key());
598                 }
599                 keys.sort((  a,  b) => {
600                         return ((string)a).collate((string)b);
601                         //if (a == b) return 0;
602                         //return a < b ? -1 : 1;
603                 });
604         
605                  
606                 for (var i = 0; i< keys.size; i++) {
607                         var key = keys.get(i);
608                         var val = this.node.listeners.get(key);
609                 
610         
611                          // 
612                         var str = val.strip();
613                         var lines = str.split("\n");
614                         if (lines.length > 0) {
615                                 //str = string.joinv("\n" + this.pad + "           ", lines);
616                                 str = string.joinv("\n" + this.pad + indent_str + indent_str , lines);
617                         }
618                          
619                         this.out_listeners.set(key.replace("|", "") ,str);
620                 
621                         
622                 }
623                  
624                  
625
626         }
627
628         public void iterChildren()
629         {
630                 
631                 
632                 // finally munge the children...
633                 if (this.node.items.size < 1) {
634                         return;
635                 }
636                 var itms = "items : [\n";
637                 //var n = 0;
638                 for(var i = 0; i < this.node.items.size;i++) {
639                         var ele = this.node.items.get(i);
640                         if (ele.props.has_key("* prop")) {
641                                 continue;
642                         }
643                          
644                         this.out_children.add(ele);
645                         
646                 }
647                 itms +=  "\n"+  this.pad + "]"  + "\n";
648                 //this.els.add(itms);
649         }
650
651                 // finally output listeners...
652                 
653         public void xIncludeToString()
654         {
655                 
656
657         }
658
659 }
660         
661          
662         
663