src/JsRender/NodeToVala.vala
[app.Builder.js] / src / JsRender / NodeToVala.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
13
14
15
16 public class JsRender.NodeToVala : Object {
17
18         Node node;
19
20         int depth;
21         string inpad;
22         string pad;
23         string ipad;
24         string cls;
25         string xcls;
26         
27         string ret;
28         
29         int cur_line;
30
31         Gee.ArrayList<string> ignoreList;
32         Gee.ArrayList<string> ignoreWrappedList; 
33         Gee.ArrayList<string> myvars;
34         Gee.ArrayList<Node> vitems; // top level items
35         NodeToVala top;
36         JsRender file;
37         
38         /* 
39          * ctor - just initializes things
40          * - wraps a render node 
41          */
42         public NodeToVala( Node node,  int depth, NodeToVala? parent) 
43         {
44
45                 
46                 this.node = node;
47                 this.depth = depth;
48                 this.inpad = string.nfill(depth > 0 ? 4 : 0, ' ');
49                 this.pad = this.inpad + "    ";
50                 this.ipad = this.inpad + "        ";
51                 this.cls = node.xvala_cls;
52                 this.xcls = node.xvala_xcls;
53                 this.ret = "";
54                 this.cur_line = parent == null ? 0 : parent.cur_line;
55                 
56                 
57                 this.top = parent == null ? this : parent.top;
58                 this.ignoreList = new Gee.ArrayList<string>();
59                 this.ignoreWrappedList  = new Gee.ArrayList<string>();
60                 this.myvars = new Gee.ArrayList<string>();
61                 this.vitems = new Gee.ArrayList<Node>();
62                 this.file = null;
63                 
64                 // initialize line data..
65                 node.line_start = this.cur_line;
66                 node.line_end  = this.cur_line;
67                 node.lines = new Gee.ArrayList();
68                 node.line_map = new Gee.HashMap<int,string>();
69                  
70                 
71         }
72
73         public int vcnt = 0;
74         string toValaNS(Node item)
75         {
76                 var ns = item.get("xns") ;
77                 if (ns == "GtkSource") {
78                         return "Gtk.Source";
79                 }
80                 return ns + ".";
81         }
82         public void  toValaName(Node item, int depth =0) 
83         {
84                 this.vcnt++;
85
86                 var ns =  this.toValaNS(item) ;
87                 var cls = ns + item.get("xtype");
88                 
89                 
90                 item.xvala_cls = cls;
91                 
92                 
93                 string id = item.get("id").length > 0 ?
94                         item.get("id") :  "%s%d".printf(item.get("xtype"), this.vcnt);
95
96                 
97                 
98                 
99                 if (id[0] == '*' || id[0] == '+') {
100                         item.xvala_xcls = "Xcls_" + id.substring(1);
101                 } else {
102                         item.xvala_xcls = "Xcls_" + id;
103                 }
104                         
105                 
106                 item.xvala_id =  id;
107                 if (depth > 0) {                        
108                         this.vitems.add(item);
109                 } else if (!item.props.has_key("id")) {
110                         // use the file name..
111                         item.xvala_xcls =  this.file.name;
112                         // is id used?
113                         item.xvala_id = this.file.name;
114
115                 }
116                 // loop children..
117                                                                                                                            
118                 if (item.items.size < 1) {
119                         return;
120                 }
121                 for(var i =0;i<item.items.size;i++) {
122                         this.toValaName(item.items.get(i), depth+1);
123                 }
124                                           
125         }
126         /**
127          *  Main entry point to convert a file into a string..
128          */
129         public static string mungeFile(JsRender file) 
130         {
131                 if (file.tree == null) {
132                         return "";
133                 }
134
135                 var n = new NodeToVala(file.tree, 0, null);
136                 n.file = file;
137                 n.vcnt = 0;
138                 
139                 n.toValaName(file.tree);
140                 
141                 
142                 GLib.debug("top cls %s / xlcs %s\n ",file.tree.xvala_cls,file.tree.xvala_cls); 
143                 n.cls = file.tree.xvala_cls;
144                 n.xcls = file.tree.xvala_xcls;
145                 return n.munge();
146                 
147
148         }
149         
150         public string munge ( )
151         {
152                 //return this.mungeToString(this.node);
153
154                 this.ignore("pack");
155                 this.ignore("init");
156                 this.ignore("xns");
157                 this.ignore("xtype");
158                 this.ignore("id");
159                 
160                 this.globalVars();
161                 this.classHeader();
162                 this.addSingleton();
163                 this.addTopProperties();
164                 this.addMyVars();
165                 this.addPlusProperties();
166                 this.addValaCtor();
167                 this.addUnderThis();
168                 this.addWrappedCtor();
169
170                 this.addInitMyVars();
171                 this.addWrappedProperties();
172                 this.addChildren();
173                 this.addInit();
174                 this.addListeners();
175                 this.addEndCtor();
176                 this.addUserMethods();
177                 this.iterChildren();
178                 
179                 return this.ret;
180                  
181                          
182         } 
183         public string mungeChild(  Node cnode)
184         {
185                 var x = new  NodeToVala(cnode,  this.depth+1, this);
186                 return x.munge();
187         }
188         public void addLine(string str= "")
189         {
190                 this.cur_line++;
191                 this.ret += str + "\n";
192         }
193         public void addMultiLine(string str= "")
194         {
195                 this.cur_line++;
196                 this.cur_line += str.split("\n").length;
197                 this.ret += str + "\n";
198         }
199          
200         
201         public void globalVars()
202         {
203                 if (this.depth > 0) {
204                         return;
205                 }
206                 // Global Vars..??? when did this get removed..?
207                 //this.ret += this.inpad + "public static " + this.xcls + "  " + this.node.xvala_id+ ";\n\n";
208
209                 this.addLine(this.inpad + "static " + this.xcls + "  _" + this.node.xvala_id+ ";");
210                 this.addLine();
211                    
212         }
213
214         void classHeader()
215         {
216                            
217                 // class header..
218                 // class xxx {   WrappedGtk  el; }
219                 this.node.line_start = this.cur_line;
220                 this.addLine(inpad + "public class " + this.xcls + " : Object \n" + this.inpad + "{");
221                 
222                  
223                 this.addLine(this.pad + "public " + this.cls + " el;");
224  
225                 this.addLine(this.pad + "private " + this.top.xcls + "  _this;");
226                 this.addLine();
227                         
228                         
229                         
230                         // singleton
231         }
232         void addSingleton() 
233         {
234                 if (depth > 0) {
235                         return;
236                 }
237                 this.addLine(pad + "public static " + xcls + " singleton()");
238                 this.addLine(this.pad + "{");
239                 this.addLine(this.ipad +    "if (_" + this.node.xvala_id  + " == null) {");
240                 this.addLine(this.ipad +    "    _" + this.node.xvala_id + "= new "+ this.xcls + "();");  // what about args?
241                 this.addLine(this.ipad +    "}");
242                 this.addLine(this.ipad +    "return _" + this.node.xvala_id +";");
243                 this.addLine(this.pad + "}");
244         }
245                         
246         /**
247          * when ID is used... on an element, it registeres a property on the top level...
248          * so that _this.ID always works..
249          * 
250          */
251         void addTopProperties()
252         {
253                 if (this.depth > 0) {
254                         return;
255                 }
256                 // properties - global..??
257
258                 var iter = this.vitems.list_iterator();
259                 while(iter.next()) {
260                         var n = iter.get();
261
262                          
263                         if (!n.props.has_key("id") || n.xvala_id.length < 0) {
264                                 continue;
265                                 
266                         }
267                         if (n.xvala_id[0] == '*') {
268                                 continue;
269                         }
270                         if (n.xvala_id[0] == '+') {
271                                 continue;
272                         }
273                         this.addLine(this.pad + "public " + n.xvala_xcls + " " + n.xvala_id + ";");
274                         
275                 }
276                                 
277         }
278         /**
279          * create properties that are not 'part of the wrapped element.
280          * 
281          * 
282          */
283         
284         void addMyVars()
285         {
286                 this.addLine();
287                 this.addLine(this.ipad + "// my vars (def)");
288                         
289
290  
291                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
292                    
293                 if (cls == null) {
294                         return;
295                 }
296           
297                 
298                         // Key = TYPE:name
299                 var iter = this.node.props.map_iterator();
300                 while (iter.next()) {
301                         var k = iter.get_key();
302                         if (this.shouldIgnore(k)) {
303                                 continue;
304                         }
305                         var vv = k.strip().split(" ");
306                         // user defined method
307                         if (vv[0] == "|") {
308                                 continue;
309                         }
310                         if (vv[0] == "*") {
311                                 continue;
312                         }
313                                 
314                         if (vv[0] == "@") {
315                                 this.node.setLine(this.cur_line, "p", k);
316                                 this.addLine(this.pad + "public signal" + k.substring(1)  + " "  + iter.get_value() + ";");
317                                 
318                                 this.ignore(k);
319                                 continue;
320                         }
321                         var min = (vv[0] == "$" || vv[0] == "#") ? 3 : 2; 
322                         if (vv.length < min) {
323                                 // skip 'old js style properties without a type'
324                                 continue;
325                         }
326                         
327                         var kname = vv[vv.length-1];
328
329                         if (this.shouldIgnore(kname)) {
330                                 continue;
331                         }
332                         
333                         // is it a class property...
334                         if (cls.props.has_key(kname) && vv[0] != "#") {
335                                 continue;
336                         }
337                         
338                         this.myvars.add(k);
339                         this.node.setLine(this.cur_line, "p", k);
340                         
341                         this.addLine(this.pad + "public " + 
342                                 (k[0] == '$' || k[0] == '#' ? k.substring(2) : k ) + ";");
343                                 
344                         this.ignore(k);
345                         
346                                 
347                 }
348         }
349         
350         // if id of child is '+' then it's a property of this..
351         void addPlusProperties()
352         {
353                 if (this.node.items.size < 1) {
354                         return;
355                 }
356                 var iter = this.node.items.list_iterator();
357                 while (iter.next()) {
358                         var ci = iter.get();
359                                 
360                         if (ci.xvala_id[0] != '+') {
361                                 continue; // skip generation of children?
362                                 
363                         }
364                          
365                         this.addLine(this.pad + "public " + ci.xvala_xcls + " " + ci.xvala_id.substring(1) + ";");
366                                            
367                         
368                 }
369         }
370         /**
371          * add the constructor definition..
372          */
373         void addValaCtor()
374         {
375                         
376                 
377                 // .vala props.. 
378                 
379                 string[] cargs = {};
380                 var cargs_str = "";
381                 // ctor..
382                 this.addLine();
383                 this.addLine(this.pad + "// ctor");
384                 
385                 if (this.node.has("* args")) {
386                         // not sure what this is supposed to be ding..
387                 
388                         cargs_str = ", " + this.node.get("* args");
389                         //var ar = this.node.get("* args");.split(",");
390                         //for (var ari =0; ari < ar.length; ari++) {
391                                 //      cargs +=  (ar[ari].trim().split(" ").pop();
392                                   // }
393                         }
394         
395                 if (this.depth < 1) {
396                  
397                         // top level - does not pass the top level element..
398                         this.addLine(this.pad + "public " + this.xcls + "(" +  cargs_str +")");
399                         this.addLine(this.pad + "{");
400                 } else {
401                                 
402                         // for sub classes = we passs the top level as _owner
403                         this.addLine(this.pad + "public " + this.xcls + "(" +  this.top.xcls + " _owner " + cargs_str + ")");
404                         this.addLine(this.pad + "{");
405                 }
406                 
407
408         }
409         /**
410          *  make sure _this is defined..
411          */
412         void addUnderThis() 
413         {
414                 // public static?
415                 if (depth < 1) {
416                         this.addLine( this.ipad + "_this = this;");
417                         return;
418                 }
419                 // for non top level = _this point to owner, and _this.ID is set
420                 
421                 this.addLine( this.ipad + "_this = _owner;");
422
423                 if (this.node.props.has_key("id")
424                         &&
425                         this.node.xvala_id != "" 
426                         && 
427                         this.node.xvala_id[0] != '*' 
428                         && 
429                         this.node.xvala_id[0] != '+' 
430                         ) {
431                                 this.addLine( this.ipad + "_this." + node.xvala_id  + " = this;");
432                    
433                 }
434                          
435         }
436         /**
437          * Initialize this.el to point to the wrapped element.
438          * 
439          * 
440          */
441
442         void addWrappedCtor()
443         {
444                 // wrapped ctor..
445                 // this may need to look up properties to fill in the arguments..
446                 // introspection does not workk..... - as things like gtkmessagedialog
447                 /*
448                 if (cls == 'Gtk.Table') {
449
450                 var methods = this.palete.getPropertiesFor(cls, 'methods');
451
452                 print(JSON.stringify(this.palete.proplist[cls], null,4));
453                 Seed.quit();
454                 }
455                 */
456                 if (this.node.has("* ctor")) {
457                         this.node.setLine(this.cur_line, "p", "* ctor");
458                         this.addLine(this.ipad + "this.el = " + this.node.get("* ctor")+ ";");
459                         return;
460                 }
461                  
462                 var  default_ctor = Palete.Gir.factoryFqn(this.node.fqn() + ".new");
463
464                  
465                 if (default_ctor != null && default_ctor.paramset != null && default_ctor.paramset.params.size > 0) {
466                         string[] args  = {};
467                         var iter =default_ctor.paramset.params.list_iterator();
468                         while (iter.next()) {
469                                 var n = iter.get().name;
470                                 if (!this.node.has(n)) {
471
472                                         if (iter.get().type.contains("int")) {
473                                                 args += "0";
474                                                 continue;
475                                         }
476                                         if (iter.get().type.contains("float")) {
477                                                 args += "0f";
478                                                 continue;
479                                         }
480                                         if (iter.get().type.contains("bool")) {
481                                                 args += "true"; // always default to true?
482                                                 continue;
483                                         }
484                                         // any other types???
485                                         
486                                         args += "null";
487                                         continue;
488                                 }
489                                 this.ignoreWrapped(n);
490                                 this.ignore(n);
491                                 
492                                 var v = this.node.get(n);
493
494                                 if (iter.get().type == "string") {
495                                         v = "\"" +  v.escape("") + "\"";
496                                 }
497                                 if (v == "TRUE" || v == "FALSE") {
498                                         v = v.down();
499                                 }
500
501                                 
502                                 args += v;
503
504                         }
505                         this.node.setLine(this.cur_line, "p", "* xtype");
506                         
507                         this.addLine(this.ipad + "this.el = new " + cls + "( "+ string.joinv(", ",args) + " );") ;
508                         return;
509                         
510                 }
511                 this.node.setLine(this.cur_line, "p", "* xtype");;
512                 
513                 this.addLine(this.ipad + "this.el = new " + this.cls + "();");
514
515                         
516         }
517
518         void addInitMyVars()
519         {
520                         //var meths = this.palete.getPropertiesFor(item['|xns'] + '.' + item.xtype, 'methods');
521                         //print(JSON.stringify(meths,null,4));Seed.quit();
522                         
523                         
524                         
525                         // initialize.. my vars..
526                 this.addLine();
527                 this.addLine( this.ipad + "// my vars (dec)");
528                 
529                 var iter = this.myvars.list_iterator();
530                 while(iter.next()) {
531                         
532                         var k = iter.get();
533                         
534                         var ar  = k.strip().split(" ");
535                         var kname = ar[ar.length-1];
536                         
537                         var v = this.node.props.get(k);
538                         // ignore signals.. 
539                         if (v.length < 1) {
540                                 continue; 
541                         }
542                         if (v == "FALSE" || v == "TRUE") {
543                                 v = v.down();
544                         }
545                         //FIXME -- check for raw string.. "string XXXX"
546                         
547                         // if it's a string...
548                         
549                         
550                         this.addLine(this.ipad + "this." + kname + " = " +   v +";");
551                 }
552         }
553
554         
555
556
557         
558         void addWrappedProperties()
559         {
560                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
561                 if (cls == null) {
562                         return;
563                 }
564                         // what are the properties of this class???
565                 this.addLine();
566                 this.addLine(this.ipad + "// set gobject values");
567                 
568
569                 var iter = cls.props.map_iterator();
570                 while (iter.next()) {
571                         var p = iter.get_key();
572                         print("Check Write %s\n", p);
573                         if (!this.node.has(p)) {
574                                 continue;
575                         }
576                         if (this.shouldIgnoreWrapped(p)) {
577                                 continue;
578                         }
579                         
580                                 this.ignore(p);
581                         var v = this.node.get(p);
582
583                         var nodekey = this.node.get_key(p);
584
585                         // user defined properties.
586                         if (nodekey[0] == '#') {
587                                 continue;
588                         }
589                                 
590
591                         
592                         var is_raw = nodekey[0] == '$';
593                         
594                         // what's the type.. - if it's a string.. then we quote it..
595                         if (iter.get_value().type == "string" && !is_raw) {
596                                  v = "\"" +  v.escape("") + "\"";
597                         }
598                         if (v == "TRUE" || v == "FALSE") {
599                                 v = v.down();
600                         }
601                         if (iter.get_value().type == "float" && v[v.length-1] != 'f') {
602                                 v += "f";
603                         }
604                         
605                         
606                         this.addLine("%sthis.el.%s = %s;".printf(ipad,p,v)); // // %s,  iter.get_value().type);
607                                         
608                            // got a property..
609                            
610
611                 }
612                 
613         }
614         /**
615          *  pack the children into the parent.
616          * 
617          * if the child's id starts with '*' then it is not packed...
618          * - this allows you to define children and add them manually..
619          */
620
621         void addChildren()
622         {
623                                 //code
624                 if (this.node.items.size < 1) {
625                         return;
626                 }
627                          
628                 var iter = this.node.items.list_iterator();
629                 var i = -1;
630                 while (iter.next()) {
631                         i++;
632                                 
633                         var ci = iter.get();
634
635                         if (ci.xvala_id[0] == '*') {
636                                 continue; // skip generation of children?
637                         }
638                                         
639                         var xargs = "";
640                         if (ci.has("* args")) {
641                                 
642                                 var ar = ci.get("* args").split(",");
643                                 for (var ari = 0 ; ari < ar.length; ari++ ) {
644                                         var arg = ar[ari].split(" ");
645                                         xargs += "," + arg[arg.length -1];
646                                 }
647                         }
648                         // create the element..
649                         this.addLine(this.ipad + "var child_" + "%d".printf(i) + " = new " + ci.xvala_xcls +
650                                         "( _this " + xargs + ");" );
651                         
652                         // this is only needed if it does not have an ID???
653                         this.addLine(this.ipad + "child_" + "%d".printf(i) +".ref();"); // we need to reference increase unnamed children...
654                         
655                         if (ci.has("* prop")) {
656                                 this.addLine(ipad + "this.el." + ci.get("* prop") + " = child_" + "%d".printf(i) + ".el;");
657                                 continue;
658                         } 
659                                 
660
661         // not sure why we have 'true' in pack?!?
662                         if (!ci.has("pack") || ci.get("pack").down() == "false" || ci.get("pack").down() == "true") {
663                                 continue;
664                         }
665                         
666                         string[]  packing =  { "add" };
667                         if (ci.has("pack")) {
668                                 packing = ci.get("pack").split(",");
669                         }
670                         
671                         var pack = packing[0];
672                         this.addLine(this.ipad + "this.el." + pack.strip() + " (  child_" + "%d".printf(i) + ".el " +
673                                    (packing.length > 1 ? 
674                                                 (", " + string.joinv(",", packing).substring(pack.length+1))
675                                         :
676                                                         ""
677                                                 ) + " );");
678         
679                                           
680                         if (ci.xvala_id[0] != '+') {
681                                 continue; // skip generation of children?
682                                                 
683                         }
684                         // this.{id - without the '+'} = the element...
685                         this.addLine(this.ipad + "this." + ci.xvala_id.substring(1) + " =  child_" + "%d".printf(i) +  ";");
686                                   
687                 }
688         }
689
690         void addInit()
691         {
692
693                 
694                 if (!this.node.has("init")) {
695                                 return;
696                 }
697                 this.addLine();
698                 this.addLine(ipad + "// init method");
699                 this.addLine();
700                 this.node.setLine(this.cur_line, "p", "init");
701                 
702                 this.addMultiLine(ipad + this.padMultiline(ipad, this.node.get("init")) );
703
704          }
705          void addListeners()
706          {
707                 if (this.node.listeners.size < 1) {
708                         return;
709                 }
710                                 
711                 this.addLine();
712                 this.addLine(ipad + "//listeners");
713                         
714                          
715
716                 var iter = this.node.listeners.map_iterator();
717                 while (iter.next()) {
718                         var k = iter.get_key();
719                         var v = iter.get_value();
720                         
721                         this.node.setLine(this.cur_line, "l", k);
722                         this.addMultiLine(this.ipad + "this.el." + k + ".connect( " + 
723                                         this.padMultiline(this.ipad,v) +");"); 
724                                 
725                 }
726         }    
727         void addEndCtor()
728         {
729                          
730                         // end ctor..
731                         this.addLine(this.pad + "}");
732         }
733
734
735         /*
736  * Standardize this crap...
737  * 
738  * standard properties (use to set)
739  *          If they are long values show the dialog..
740  *
741  * someprop : ....
742  * bool is_xxx  :: can show a pulldown.. (true/false)
743  * string html  
744  * $ string html  = string with value interpolated eg. baseURL + ".." 
745  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
746  * $ untypedvalue = javascript untyped value...  
747  * _ string html ... = translatable..
748
749  * 
750  * object properties (not part of the GOjbect being wrapped?
751  * # Gee.ArrayList<Xcls_fileitem> fileitems
752  * 
753  * signals
754  * @ void open 
755  * 
756  * methods -- always text editor..
757  * | void clearFiles
758  * | someJSmethod
759  * 
760  * specials
761  * * prop -- string
762  * * args  -- string
763  * * ctor -- string
764  * * init -- big string?
765  * 
766  * event handlers (listeners)
767  *   just shown 
768  * 
769  * -----------------
770  * special ID values
771  *  +XXXX -- indicates it's a instance property / not glob...
772  *  *XXXX -- skip writing glob property (used as classes that can be created...)
773  * 
774  * 
775  */
776          
777         void addUserMethods()
778         {
779                 this.addLine();
780                 this.addLine(this.pad + "// user defined functions");
781                         
782                         // user defined functions...
783                 var iter = this.node.props.map_iterator();
784                 while(iter.next()) {
785                         var k = iter.get_key();
786                         if (this.shouldIgnore(k)) {
787                                 continue;
788                         }
789                         // HOW TO DETERIME if its a method?            
790                         if (k[0] != '|') {
791                                         //strbuilder("\n" + pad + "// skip " + k + " - not pipe \n"); 
792                                         continue;
793                         }
794                         
795                         // function in the format of {type} (args) { .... }
796                         var kk = k.substring(2);
797                         var vv = iter.get_value();
798                         this.node.setLine(this.cur_line, "p", k);
799                         this.addMultiLine(this.pad + "public " + kk + " " + this.padMultiline(this.pad, vv));;
800                         
801                                 
802                 }
803         }
804
805         void iterChildren()
806         {
807                 this.node.line_end = this.cur_line;
808                         
809                 if (this.depth > 0) {
810                         this.addLine(this.inpad + "}");
811                 }
812                 
813                 var iter = this.node.items.list_iterator();
814                 var i = -1;
815                 while (iter.next()) {
816                         this.addMultiLine(this.mungeChild(iter.get()));
817                 }
818                          
819                 if (this.depth < 1) {
820                         this.addLine(this.inpad + "}");
821                 }
822                         
823         }
824
825         string padMultiline(string pad, string str)
826         {
827                 var ar = str.strip().split("\n");
828                 return string.joinv("\n" + pad , ar);
829         }
830         
831         void ignore(string i) {
832                 this.ignoreList.add(i);
833                 
834         }
835         void ignoreWrapped(string i) {
836                 this.ignoreWrappedList.add(i);
837                 
838         }
839         bool shouldIgnore(string i)
840         {
841                 return ignoreList.contains(i);
842         }
843         bool shouldIgnoreWrapped(string i)
844         {
845                 return ignoreWrappedList.contains(i);
846         }
847         
848 }
849         
850          
851         
852         
853
854