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