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