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