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  
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                         var l = this.pad + niter.get_key() + " : " + 
196                                         this.mungeChildNew(this.pad + indent_str, niter.get_value(),  -1) + suffix;
197                         this.addMultiLine(l);
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.addMultiLine(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                 this.ret +=  "/*%d*/ ".printf(this.cur_line) + str + "\n";
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(this.cur_line) + 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, int offset = 0)
335         {
336                 var x = new  NodeToJs(cnode, this.doubleStringProps, pad, this);
337                 x.cur_line -= offset;
338                 x.munge();
339                 return x.ret;
340         }
341         
342
343         
344         public void checkChildren () 
345         {
346                 
347                  
348                 // look throught he chilren == looking for * prop.. -- fixme might not work..
349                 
350                 
351                 if (!this.node.hasChildren()) {
352                         return;
353                 }
354                 // look for '*props'
355            
356                 for (var ii =0; ii< this.node.items.size; ii++) {
357                         var pl = this.node.items.get(ii);
358                         if (!pl.props.has_key("* prop")) {
359                                 //newitems.add(pl);
360                                 continue;
361                         }
362                         
363                         //print(JSON.stringify(pl,null,4));
364                         // we have a prop...
365                         //var prop = pl['*prop'] + '';
366                         //delete pl['*prop'];
367                         var prop = pl.get("* prop");
368                         print("got prop "+ prop + "\n");
369                         
370                         // name ends in [];
371                         if (! Regex.match_simple("\\[\\]$", prop)) {
372                                 // it's a standard prop..
373                                 
374                                 // munge property..??
375                                 
376                                 this.out_nodeprops.set(prop, pl);
377                                 
378                                 this.els.add( prop  + " : " + this.mungeChild (  this.pad + indent_str,  pl));
379                                 
380                                 
381                                 //keys.push(prop);
382                                 continue;
383                         }
384
385
386
387                         
388                         var sprop  = prop.replace("[]", "");
389                         print("sprop is : " + sprop + "\n");
390                         
391                         // it's an array type..
392                         var old = "";
393                         if (!this.ar_props.has_key(sprop)) {
394                                 
395                                 this.ar_props.set(sprop, "");
396                                 this.out_props_array.set(sprop, new Gee.ArrayList<Node>());
397                         } else {
398                                 old = this.ar_props.get(sprop);
399                         }
400                         var nstr  = old += old.length > 0 ? ",\n" : "";
401                         nstr += this.mungeChild( this.pad + indent_str + indent_str + indent_str ,   pl);
402                         this.out_props_array.get(sprop).add( pl);
403                         this.ar_props.set(sprop, nstr);
404                          
405                         
406                 }
407                  
408         }
409         /*
410  * Standardize this crap...
411  * 
412  * standard properties (use to set)
413  *          If they are long values show the dialog..
414  *
415  * someprop : ....
416  * bool is_xxx  :: can show a pulldown.. (true/false)
417  * string html  
418  * $ string html  = string with value interpolated eg. baseURL + ".." 
419  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
420  * $ untypedvalue = javascript untyped value...  
421  * _ string html ... = translatable..
422
423  * 
424  * object properties (not part of the GOjbect being wrapped?
425  * # Gee.ArrayList<Xcls_fileitem> fileitems
426  * 
427  * signals
428  * @ void open 
429  * 
430  * methods -- always text editor..
431  * | void clearFiles
432  * | someJSmethod
433  * 
434  * specials
435  * * prop -- string
436  * * args  -- string
437  * * ctor -- string
438  * * init -- big string?
439  * 
440  * event handlers (listeners)
441  *   just shown 
442  * 
443  * -----------------
444  * special ID values
445  *  +XXXX -- indicates it's a instance property / not glob...
446  *  *XXXX -- skip writing glob property (used as classes that can be created...)
447  * 
448  * 
449  */
450         public void readProps()
451         {
452                 string left;
453                 Regex func_regex ;
454
455                 if (this.node.props.has_key("$ xns")) {
456                         this.out_props.set("'|xns'", "'" +  this.node.props.get("$ xns") + "'" );
457                         
458                         this.els.add("'|xns' : '" + this.node.props.get("$ xns") + "'");
459
460                 }
461
462                 
463                 try {
464                         func_regex = new Regex("^\\s+|\\s+$");
465                 } catch (Error e) {
466                         print("failed to build regex");
467                         return;
468                 }
469                 // sort the key's so they always get rendered in the same order..
470                 
471                 var keys = new Gee.ArrayList<string>();
472                 var piter = this.node.props.map_iterator();
473                 while (piter.next() ) {
474                         string k;
475                         string ktype;
476                         string kflag;
477                         this.node.normalize_key(piter.get_key(), out k, out kflag, out ktype);
478                         
479                         keys.add(k);
480                 }
481                 
482                 keys.sort((  a,  b) => {
483                         return ((string)a).collate((string)b);
484                         //if (a == b) return 0;
485                         //return a < b ? -1 : 1;
486                 });
487                 
488                 
489                 
490                 for (var i = 0; i< keys.size; i++) {
491                         var key = this.node.get_key(keys.get(i));
492                         print("ADD KEY %s\n", key);
493                         string k;
494                         string ktype;
495                         string kflag;
496                         
497                         this.node.normalize_key(key, out k, out kflag, out ktype);
498                         
499                         
500                         var v = this.node.get(key);
501                          
502                         
503                         //if (this.skip.contains(k) ) {
504                         //      continue;
505                         //}
506                         if (  Regex.match_simple("\\[\\]$", k)) {
507                                 // array .. not supported... here?
508                                 
509
510                         }
511                         
512                         string leftv = k;
513                         // skip builder stuff. prefixed with  '.' .. just like unix fs..
514                         if (kflag == ".") { // |. or . -- do not output..
515                                 continue;
516                         }
517                          if (kflag == "*") {
518                                 // ignore '* prop'; ??? 
519                                 continue;
520                          }
521                                 
522                         
523                         if (Lang.isKeyword(leftv) || Lang.isBuiltin(leftv)) {
524                                 left = "'" + leftv + "'";
525                         } else if (Regex.match_simple("[^A-Za-z_]+",leftv)) { // not plain a-z... - quoted.
526                                 var val = this.node.quoteString(leftv);
527                                 
528                                 left = "'" + val.substring(1, val.length-2).replace("'", "\\'") + "'";
529                         } else {
530                                 left = leftv;
531                         }
532                          
533                          
534                         // next.. is it a function.. or a raw string..
535                         if (
536                                 kflag == "|" 
537                                 || 
538                                 kflag == "$" 
539                                 || 
540                                 ktype == "function"
541                                
542                                 // ??? any others that are raw output..
543                                 ) {
544                                 // does not hapepnd with arrays.. 
545                                 if (v.length < 1) {  //if (typeof(el) == 'string' && !obj[i].length) { //skip empty.
546                                         continue;
547                                 }
548                                 /*
549                                 print(v);
550                                 string str = "";
551                                 try {
552                                         str = func_regex.replace(v,v.length, 0, "");
553                                 } catch(Error e) {
554                                         print("regex failed");
555                                         return "";
556                                 }
557                                 */
558                                 var str = v.strip();
559                                   
560                                 var lines = str.split("\n");
561                                 var nstr = "" + str;
562                                 if (lines.length > 0) {
563                                         nstr =  string.joinv("\n" + this.pad, lines);
564                                         //nstr =  string.joinv("\n", lines);
565                                 }
566                                 this.out_props.set(left, nstr);
567                                 //print("==> " +  str + "\n");
568                                 this.els.add(left + " : "+  nstr);
569                                 continue;
570                         }
571                         // standard..
572                         
573                         
574                         if (
575                                 Lang.isNumber(v) 
576                                 || 
577                                 Lang.isBoolean(v)
578                                 ||
579                                 ktype.down() == "boolean"
580                                 || 
581                                 ktype.down() == "bool"
582                                 || 
583                                 ktype.down() == "number"
584                                 || 
585                                 ktype.down() == "int"
586                             ) { // boolean or number...?
587                             this.out_props.set(left, v.down());
588                                 this.els.add(left + " : " + v.down() );
589                                 continue;
590                         }
591                         
592                         // is it a translated string?
593                         
594                         
595                         
596                         
597                         // strings..
598                         //if (this.doubleStringProps.size < 1) {
599                         //      this.els.add(left + this.node.quoteString(v));
600                         //      continue;
601                         //}
602                    
603                         if ((this.doubleStringProps.index_of(k) > -1) || 
604                                 (ktype.down() == "string" && k[0] == '_')
605                         
606                         ) {
607                                 // then use the translated version...
608                                 
609                                 var com = " /* " + 
610                                         (v.split("\n").length > 1 ?
611                                                 ("\n" + string.joinv(this.pad +  "\n", v.split("\n")).replace("*/", "* - /") + "\n" + this.pad + "*/ ") :
612                                                 (v.replace("*/", "* - /") + " */")
613                                         );
614                                 
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                                         "']" + com);
622                                 continue;
623                         }
624                  
625                         // otherwise it needs to be encapsulated.. as single quotes..
626                         
627                         var vv = this.node.quoteString(v);
628                         // single quote.. v.substring(1, v.length-1).replace("'", "\\'") + "'";
629                         this.els.add(left + " : " +  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
630                         this.out_props.set(left,  "'" + vv.substring(1, vv.length-2).replace("'", "\\'") + "'");
631
632                    
633                    
634                    
635                 }
636         }
637         public void readArrayProps()
638         {
639         
640                 // this is not needed in the new version
641                 // as array props are handled more directly..
642                 
643                 // handle the childitems  that are arrays.. eg. button[] = {  }...
644                 
645                 // note this does not handle a mix of nodes and properties with the same 
646                 
647                 string left;
648                 
649                 var iter = this.ar_props.map_iterator();
650                 while (iter.next()) {
651                         var k = iter.get_key();
652                         var right = iter.get_value();
653                         
654                         string leftv = k[0] == '|' ? k.substring(1) : k;
655                         if (Lang.isKeyword(leftv) || Lang.isBuiltin(leftv)) {
656                                 left = "'" + leftv + "'";
657                         } else if (Regex.match_simple("[^A-Za-z_]+",leftv)) { // not plain a-z... - quoted.
658                                 var val = this.node.quoteString(leftv);
659                                 
660                                 left = "'" + val.substring(1, val.length-2).replace("'", "\\'") + "'";
661                         } else {
662                                 left = leftv;
663                         }
664
665                         
666                         if (right.length > 0){
667                                 //if (this.out_props_array_plain.has_key(left)) {
668                                 //      this.out_props_array_plain.set(left, new Gee.ArrayList<string>());
669                                 //}
670                                 //this.out_props_array_plain.get(left).add(right);
671                         
672                                 this.els.add(left + " : [\n" +  this.pad + indent_str + indent_str +  
673                                              right + "\n" + this.pad + "]");
674                         }
675                 
676                         
677                 }
678
679         }
680         public void readListeners()
681         {
682                 
683                 if (this.node.listeners.size < 1) {
684                         return;
685                 }
686                 // munge the listeners.
687                 //print("ADDING listeners?");
688         
689  
690         
691         
692                 var keys = new Gee.ArrayList<string>();
693                 var piter = this.node.listeners.map_iterator();
694                 while (piter.next() ) {
695                          
696                         keys.add(piter.get_key());
697                 }
698                 keys.sort((  a,  b) => {
699                         return ((string)a).collate((string)b);
700                         //if (a == b) return 0;
701                         //return a < b ? -1 : 1;
702                 });
703         
704                 var itms = "listeners : {\n";
705                 
706                 for (var i = 0; i< keys.size; i++) {
707                         var key = keys.get(i);
708                         var val = this.node.listeners.get(key);
709                 
710         
711                         itms += i >0 ? ",\n" : "";      
712                         // 
713                         var str = val.strip();
714                         var lines = str.split("\n");
715                         if (lines.length > 0) {
716                                 //str = string.joinv("\n" + this.pad + "           ", lines);
717                                 str = string.joinv("\n" + this.pad + indent_str + indent_str , lines);
718                         }
719                         
720                         itms +=  this.pad + indent_str  + key.replace("|", "")  + " : " + str;
721                         this.out_listeners.set(key.replace("|", "") ,str);
722                 
723                         
724                 }
725                 itms += "\n" + this.pad + "}";
726                 //print ( "ADD " + itms); 
727                 this.els.add(itms);
728
729         }
730
731         public void iterChildren()
732         {
733                 
734                 
735                 // finally munge the children...
736                 if (this.node.items.size < 1) {
737                         return;
738                 }
739                 var itms = "items : [\n";
740                 var n = 0;
741                 for(var i = 0; i < this.node.items.size;i++) {
742                         var ele = this.node.items.get(i);
743                         if (ele.props.has_key("* prop")) {
744                                 continue;
745                         }
746                         if (n > 0) {
747                                  itms += ",\n";
748                         }
749                         n++;
750                         itms += this.pad + indent_str  +
751                                 this.mungeChild( this.pad + indent_str + indent_str ,  ele);
752                         this.out_children.add(ele);
753                         
754                 }
755                 itms +=  "\n"+  this.pad + "]"  + "\n";
756                 this.els.add(itms);
757         }
758
759                 // finally output listeners...
760                 
761         public void xIncludeToString()
762         {
763                 
764
765         }
766
767 }
768         
769          
770         
771