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