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<int>();
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 += "/*%d*/ ".printf(this.cur_line-1) + str + "\n";
192         }
193         public void addMultiLine(string str= "")
194         {
195                 var l = this.cur_line;
196                 this.cur_line += str.split("\n").length;
197                 this.ret +=  "/*%d*/ ".printf(l) + 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");
221                 this.addLine(this.inpad + "{");
222                 
223                  
224                 this.addLine(this.pad + "public " + this.cls + " el;");
225  
226                 this.addLine(this.pad + "private " + this.top.xcls + "  _this;");
227                 this.addLine();
228                         
229                         
230                         
231                         // singleton
232         }
233         void addSingleton() 
234         {
235                 if (depth > 0) {
236                         return;
237                 }
238                 this.addLine(pad + "public static " + xcls + " singleton()");
239                 this.addLine(this.pad + "{");
240                 this.addLine(this.ipad +    "if (_" + this.node.xvala_id  + " == null) {");
241                 this.addLine(this.ipad +    "    _" + this.node.xvala_id + "= new "+ this.xcls + "();");  // what about args?
242                 this.addLine(this.ipad +    "}");
243                 this.addLine(this.ipad +    "return _" + this.node.xvala_id +";");
244                 this.addLine(this.pad + "}");
245         }
246                         
247         /**
248          * when ID is used... on an element, it registeres a property on the top level...
249          * so that _this.ID always works..
250          * 
251          */
252         void addTopProperties()
253         {
254                 if (this.depth > 0) {
255                         return;
256                 }
257                 // properties - global..??
258
259                 var iter = this.vitems.list_iterator();
260                 while(iter.next()) {
261                         var n = iter.get();
262
263                          
264                         if (!n.props.has_key("id") || n.xvala_id.length < 0) {
265                                 continue;
266                                 
267                         }
268                         if (n.xvala_id[0] == '*') {
269                                 continue;
270                         }
271                         if (n.xvala_id[0] == '+') {
272                                 continue;
273                         }
274                         this.addLine(this.pad + "public " + n.xvala_xcls + " " + n.xvala_id + ";");
275                         
276                 }
277                                 
278         }
279         /**
280          * create properties that are not 'part of the wrapped element.
281          * 
282          * 
283          */
284         
285         void addMyVars()
286         {
287                 this.addLine();
288                 this.addLine(this.ipad + "// my vars (def)");
289                         
290
291  
292                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
293                    
294                 if (cls == null) {
295                         return;
296                 }
297           
298                 
299                         // Key = TYPE:name
300                 var iter = this.node.props.map_iterator();
301                 while (iter.next()) {
302                         var k = iter.get_key();
303                         if (this.shouldIgnore(k)) {
304                                 continue;
305                         }
306                         var vv = k.strip().split(" ");
307                         // user defined method
308                         if (vv[0] == "|") {
309                                 continue;
310                         }
311                         if (vv[0] == "*") {
312                                 continue;
313                         }
314                                 
315                         if (vv[0] == "@") {
316                                 this.node.setLine(this.cur_line, "p", k);
317                                 this.addLine(this.pad + "public signal" + k.substring(1)  + " "  + iter.get_value() + ";");
318                                 
319                                 this.ignore(k);
320                                 continue;
321                         }
322                         var min = (vv[0] == "$" || vv[0] == "#") ? 3 : 2; 
323                         if (vv.length < min) {
324                                 // skip 'old js style properties without a type'
325                                 continue;
326                         }
327                         
328                         var kname = vv[vv.length-1];
329
330                         if (this.shouldIgnore(kname)) {
331                                 continue;
332                         }
333                         
334                         // is it a class property...
335                         if (cls.props.has_key(kname) && vv[0] != "#") {
336                                 continue;
337                         }
338                         
339                         this.myvars.add(k);
340                         this.node.setLine(this.cur_line, "p", k);
341                         
342                         this.addLine(this.pad + "public " + 
343                                 (k[0] == '$' || k[0] == '#' ? k.substring(2) : k ) + ";");
344                                 
345                         this.ignore(k);
346                         
347                                 
348                 }
349         }
350         
351         // if id of child is '+' then it's a property of this..
352         void addPlusProperties()
353         {
354                 if (this.node.items.size < 1) {
355                         return;
356                 }
357                 var iter = this.node.items.list_iterator();
358                 while (iter.next()) {
359                         var ci = iter.get();
360                                 
361                         if (ci.xvala_id[0] != '+') {
362                                 continue; // skip generation of children?
363                                 
364                         }
365                          
366                         this.addLine(this.pad + "public " + ci.xvala_xcls + " " + ci.xvala_id.substring(1) + ";");
367                                            
368                         
369                 }
370         }
371         /**
372          * add the constructor definition..
373          */
374         void addValaCtor()
375         {
376                         
377                 
378                 // .vala props.. 
379                 
380                 string[] cargs = {};
381                 var cargs_str = "";
382                 // ctor..
383                 this.addLine();
384                 this.addLine(this.pad + "// ctor");
385                 
386                 if (this.node.has("* args")) {
387                         // not sure what this is supposed to be ding..
388                 
389                         cargs_str = ", " + this.node.get("* args");
390                         //var ar = this.node.get("* args");.split(",");
391                         //for (var ari =0; ari < ar.length; ari++) {
392                                 //      cargs +=  (ar[ari].trim().split(" ").pop();
393                                   // }
394                         }
395         
396                 if (this.depth < 1) {
397                  
398                         // top level - does not pass the top level element..
399                         this.addLine(this.pad + "public " + this.xcls + "(" +  cargs_str +")");
400                         this.addLine(this.pad + "{");
401                 } else {
402                                 
403                         // for sub classes = we passs the top level as _owner
404                         this.addLine(this.pad + "public " + this.xcls + "(" +  this.top.xcls + " _owner " + cargs_str + ")");
405                         this.addLine(this.pad + "{");
406                 }
407                 
408
409         }
410         /**
411          *  make sure _this is defined..
412          */
413         void addUnderThis() 
414         {
415                 // public static?
416                 if (depth < 1) {
417                         this.addLine( this.ipad + "_this = this;");
418                         return;
419                 }
420                 // for non top level = _this point to owner, and _this.ID is set
421                 
422                 this.addLine( this.ipad + "_this = _owner;");
423
424                 if (this.node.props.has_key("id")
425                         &&
426                         this.node.xvala_id != "" 
427                         && 
428                         this.node.xvala_id[0] != '*' 
429                         && 
430                         this.node.xvala_id[0] != '+' 
431                         ) {
432                                 this.addLine( this.ipad + "_this." + node.xvala_id  + " = this;");
433                    
434                 }
435                          
436         }
437         /**
438          * Initialize this.el to point to the wrapped element.
439          * 
440          * 
441          */
442
443         void addWrappedCtor()
444         {
445                 // wrapped ctor..
446                 // this may need to look up properties to fill in the arguments..
447                 // introspection does not workk..... - as things like gtkmessagedialog
448                 /*
449                 if (cls == 'Gtk.Table') {
450
451                 var methods = this.palete.getPropertiesFor(cls, 'methods');
452
453                 print(JSON.stringify(this.palete.proplist[cls], null,4));
454                 Seed.quit();
455                 }
456                 */
457                 if (this.node.has("* ctor")) {
458                         this.node.setLine(this.cur_line, "p", "* ctor");
459                         this.addLine(this.ipad + "this.el = " + this.node.get("* ctor")+ ";");
460                         return;
461                 }
462                  
463                 var  default_ctor = Palete.Gir.factoryFqn(this.node.fqn() + ".new");
464
465                  
466                 if (default_ctor != null && default_ctor.paramset != null && default_ctor.paramset.params.size > 0) {
467                         string[] args  = {};
468                         var iter =default_ctor.paramset.params.list_iterator();
469                         while (iter.next()) {
470                                 var n = iter.get().name;
471                                 if (!this.node.has(n)) {
472
473                                         if (iter.get().type.contains("int")) {
474                                                 args += "0";
475                                                 continue;
476                                         }
477                                         if (iter.get().type.contains("float")) {
478                                                 args += "0f";
479                                                 continue;
480                                         }
481                                         if (iter.get().type.contains("bool")) {
482                                                 args += "true"; // always default to true?
483                                                 continue;
484                                         }
485                                         // any other types???
486                                         
487                                         args += "null";
488                                         continue;
489                                 }
490                                 this.ignoreWrapped(n);
491                                 this.ignore(n);
492                                 
493                                 var v = this.node.get(n);
494
495                                 if (iter.get().type == "string") {
496                                         v = "\"" +  v.escape("") + "\"";
497                                 }
498                                 if (v == "TRUE" || v == "FALSE") {
499                                         v = v.down();
500                                 }
501
502                                 
503                                 args += v;
504
505                         }
506                         this.node.setLine(this.cur_line, "p", "* xtype");
507                         
508                         this.addLine(this.ipad + "this.el = new " + cls + "( "+ string.joinv(", ",args) + " );") ;
509                         return;
510                         
511                 }
512                 this.node.setLine(this.cur_line, "p", "* xtype");;
513                 
514                 this.addLine(this.ipad + "this.el = new " + this.cls + "();");
515
516                         
517         }
518
519         void addInitMyVars()
520         {
521                         //var meths = this.palete.getPropertiesFor(item['|xns'] + '.' + item.xtype, 'methods');
522                         //print(JSON.stringify(meths,null,4));Seed.quit();
523                         
524                         
525                         
526                         // initialize.. my vars..
527                 this.addLine();
528                 this.addLine( this.ipad + "// my vars (dec)");
529                 
530                 var iter = this.myvars.list_iterator();
531                 while(iter.next()) {
532                         
533                         var k = iter.get();
534                         
535                         var ar  = k.strip().split(" ");
536                         var kname = ar[ar.length-1];
537                         
538                         var v = this.node.props.get(k);
539                         // ignore signals.. 
540                         if (v.length < 1) {
541                                 continue; 
542                         }
543                         if (v == "FALSE" || v == "TRUE") {
544                                 v = v.down();
545                         }
546                         //FIXME -- check for raw string.. "string XXXX"
547                         
548                         // if it's a string...
549                         
550                         
551                         this.addLine(this.ipad + "this." + kname + " = " +   v +";");
552                 }
553         }
554
555         
556
557
558         
559         void addWrappedProperties()
560         {
561                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
562                 if (cls == null) {
563                         return;
564                 }
565                         // what are the properties of this class???
566                 this.addLine();
567                 this.addLine(this.ipad + "// set gobject values");
568                 
569
570                 var iter = cls.props.map_iterator();
571                 while (iter.next()) {
572                         var p = iter.get_key();
573                         print("Check Write %s\n", p);
574                         if (!this.node.has(p)) {
575                                 continue;
576                         }
577                         if (this.shouldIgnoreWrapped(p)) {
578                                 continue;
579                         }
580                         
581                                 this.ignore(p);
582                         var v = this.node.get(p);
583
584                         var nodekey = this.node.get_key(p);
585
586                         // user defined properties.
587                         if (nodekey[0] == '#') {
588                                 continue;
589                         }
590                                 
591
592                         
593                         var is_raw = nodekey[0] == '$';
594                         
595                         // what's the type.. - if it's a string.. then we quote it..
596                         if (iter.get_value().type == "string" && !is_raw) {
597                                  v = "\"" +  v.escape("") + "\"";
598                         }
599                         if (v == "TRUE" || v == "FALSE") {
600                                 v = v.down();
601                         }
602                         if (iter.get_value().type == "float" && v[v.length-1] != 'f') {
603                                 v += "f";
604                         }
605                         
606                         
607                         this.addLine("%sthis.el.%s = %s;".printf(ipad,p,v)); // // %s,  iter.get_value().type);
608                                         
609                            // got a property..
610                            
611
612                 }
613                 
614         }
615         /**
616          *  pack the children into the parent.
617          * 
618          * if the child's id starts with '*' then it is not packed...
619          * - this allows you to define children and add them manually..
620          */
621
622         void addChildren()
623         {
624                                 //code
625                 if (this.node.items.size < 1) {
626                         return;
627                 }
628                          
629                 var iter = this.node.items.list_iterator();
630                 var i = -1;
631                 while (iter.next()) {
632                         i++;
633                                 
634                         var ci = iter.get();
635
636                         if (ci.xvala_id[0] == '*') {
637                                 continue; // skip generation of children?
638                         }
639                                         
640                         var xargs = "";
641                         if (ci.has("* args")) {
642                                 
643                                 var ar = ci.get("* args").split(",");
644                                 for (var ari = 0 ; ari < ar.length; ari++ ) {
645                                         var arg = ar[ari].split(" ");
646                                         xargs += "," + arg[arg.length -1];
647                                 }
648                         }
649                         // create the element..
650                         this.addLine(this.ipad + "var child_" + "%d".printf(i) + " = new " + ci.xvala_xcls +
651                                         "( _this " + xargs + ");" );
652                         
653                         // this is only needed if it does not have an ID???
654                         this.addLine(this.ipad + "child_" + "%d".printf(i) +".ref();"); // we need to reference increase unnamed children...
655                         
656                         if (ci.has("* prop")) {
657                                 this.addLine(ipad + "this.el." + ci.get("* prop") + " = child_" + "%d".printf(i) + ".el;");
658                                 continue;
659                         } 
660                                 
661
662         // not sure why we have 'true' in pack?!?
663                         if (!ci.has("pack") || ci.get("pack").down() == "false" || ci.get("pack").down() == "true") {
664                                 continue;
665                         }
666                         
667                         string[]  packing =  { "add" };
668                         if (ci.has("pack")) {
669                                 packing = ci.get("pack").split(",");
670                         }
671                         
672                         var pack = packing[0];
673                         this.addLine(this.ipad + "this.el." + pack.strip() + " (  child_" + "%d".printf(i) + ".el " +
674                                    (packing.length > 1 ? 
675                                                 (", " + string.joinv(",", packing).substring(pack.length+1))
676                                         :
677                                                         ""
678                                                 ) + " );");
679         
680                                           
681                         if (ci.xvala_id[0] != '+') {
682                                 continue; // skip generation of children?
683                                                 
684                         }
685                         // this.{id - without the '+'} = the element...
686                         this.addLine(this.ipad + "this." + ci.xvala_id.substring(1) + " =  child_" + "%d".printf(i) +  ";");
687                                   
688                 }
689         }
690
691         void addInit()
692         {
693
694                 
695                 if (!this.node.has("init")) {
696                                 return;
697                 }
698                 this.addLine();
699                 this.addLine(ipad + "// init method");
700                 this.addLine();
701                 this.node.setLine(this.cur_line, "p", "init");
702                 
703                 this.addMultiLine(ipad + this.padMultiline(ipad, this.node.get("init")) );
704
705          }
706          void addListeners()
707          {
708                 if (this.node.listeners.size < 1) {
709                         return;
710                 }
711                                 
712                 this.addLine();
713                 this.addLine(ipad + "//listeners");
714                         
715                          
716
717                 var iter = this.node.listeners.map_iterator();
718                 while (iter.next()) {
719                         var k = iter.get_key();
720                         var v = iter.get_value();
721                         
722                         this.node.setLine(this.cur_line, "l", k);
723                         this.addMultiLine(this.ipad + "this.el." + k + ".connect( " + 
724                                         this.padMultiline(this.ipad,v) +");"); 
725                                 
726                 }
727         }    
728         void addEndCtor()
729         {
730                          
731                         // end ctor..
732                         this.addLine(this.pad + "}");
733         }
734
735
736         /*
737  * Standardize this crap...
738  * 
739  * standard properties (use to set)
740  *          If they are long values show the dialog..
741  *
742  * someprop : ....
743  * bool is_xxx  :: can show a pulldown.. (true/false)
744  * string html  
745  * $ string html  = string with value interpolated eg. baseURL + ".." 
746  *  Clutter.ActorAlign x_align  (typed)  -- shows pulldowns if type is ENUM? 
747  * $ untypedvalue = javascript untyped value...  
748  * _ string html ... = translatable..
749
750  * 
751  * object properties (not part of the GOjbect being wrapped?
752  * # Gee.ArrayList<Xcls_fileitem> fileitems
753  * 
754  * signals
755  * @ void open 
756  * 
757  * methods -- always text editor..
758  * | void clearFiles
759  * | someJSmethod
760  * 
761  * specials
762  * * prop -- string
763  * * args  -- string
764  * * ctor -- string
765  * * init -- big string?
766  * 
767  * event handlers (listeners)
768  *   just shown 
769  * 
770  * -----------------
771  * special ID values
772  *  +XXXX -- indicates it's a instance property / not glob...
773  *  *XXXX -- skip writing glob property (used as classes that can be created...)
774  * 
775  * 
776  */
777          
778         void addUserMethods()
779         {
780                 this.addLine();
781                 this.addLine(this.pad + "// user defined functions");
782                         
783                         // user defined functions...
784                 var iter = this.node.props.map_iterator();
785                 while(iter.next()) {
786                         var k = iter.get_key();
787                         if (this.shouldIgnore(k)) {
788                                 continue;
789                         }
790                         // HOW TO DETERIME if its a method?            
791                         if (k[0] != '|') {
792                                         //strbuilder("\n" + pad + "// skip " + k + " - not pipe \n"); 
793                                         continue;
794                         }
795                         
796                         // function in the format of {type} (args) { .... }
797                         var kk = k.substring(2);
798                         var vv = iter.get_value();
799                         this.node.setLine(this.cur_line, "p", k);
800                         this.addMultiLine(this.pad + "public " + kk + " " + this.padMultiline(this.pad, vv));;
801                         
802                                 
803                 }
804         }
805
806         void iterChildren()
807         {
808                 this.node.line_end = this.cur_line;
809                 this.node.sortLines();
810                 
811                         
812                 if (this.depth > 0) {
813                         this.addLine(this.inpad + "}");
814                 }
815                 
816                 var iter = this.node.items.list_iterator();
817                 var i = -1;
818                 while (iter.next()) {
819                         this.addMultiLine(this.mungeChild(iter.get()));
820                 }
821                          
822                 if (this.depth < 1) {
823                         this.addLine(this.inpad + "}");
824                 }
825                         
826         }
827
828         string padMultiline(string pad, string str)
829         {
830                 var ar = str.strip().split("\n");
831                 return string.joinv("\n" + pad , ar);
832         }
833         
834         void ignore(string i) {
835                 this.ignoreList.add(i);
836                 
837         }
838         void ignoreWrapped(string i) {
839                 this.ignoreWrappedList.add(i);
840                 
841         }
842         bool shouldIgnore(string i)
843         {
844                 return ignoreList.contains(i);
845         }
846         bool shouldIgnoreWrapped(string i)
847         {
848                 return ignoreWrappedList.contains(i);
849         }
850         
851 }
852         
853          
854         
855         
856
857