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                 
74         }
75
76         public int vcnt = 0;
77         string toValaNS(Node item)
78         {
79                 var ns = item.get("xns") ;
80                 if (ns == "GtkSource") {
81                         return "Gtk.Source";
82                 }
83                 return ns + ".";
84         }
85         public void  toValaName(Node item, int depth =0) 
86         {
87                 this.vcnt++;
88
89                 var ns =  this.toValaNS(item) ;
90                 var cls = ns + item.get("xtype");
91                 
92                 
93                 item.xvala_cls = cls;
94                 
95                 
96                 string id = item.get("id").length > 0 ?
97                         item.get("id") :  "%s%d".printf(item.get("xtype"), this.vcnt);
98
99                 
100                 
101                 
102                 if (id[0] == '*' || id[0] == '+') {
103                         item.xvala_xcls = "Xcls_" + id.substring(1);
104                 } else {
105                         item.xvala_xcls = "Xcls_" + id;
106                 }
107                         
108                 
109                 item.xvala_id =  id;
110                 if (depth > 0) {                        
111                         this.vitems.add(item);
112                 } else if (!item.props.has_key("id")) {
113                         // use the file name..
114                         item.xvala_xcls =  this.file.name;
115                         // is id used?
116                         item.xvala_id = this.file.name;
117
118                 }
119                 // loop children..
120                                                                                                                            
121                 if (item.items.size < 1) {
122                         return;
123                 }
124                 for(var i =0;i<item.items.size;i++) {
125                         this.toValaName(item.items.get(i), depth+1);
126                 }
127                                           
128         }
129         /**
130          *  Main entry point to convert a file into a string..
131          */
132         public static string mungeFile(JsRender file) 
133         {
134                 if (file.tree == null) {
135                         return "";
136                 }
137
138                 var n = new NodeToVala(file.tree, 0, null);
139                 n.file = file;
140                 n.vcnt = 0;
141                 
142                 n.toValaName(file.tree);
143                 
144                 
145                 GLib.debug("top cls %s / xlcs %s\n ",file.tree.xvala_cls,file.tree.xvala_cls); 
146                 n.cls = file.tree.xvala_cls;
147                 n.xcls = file.tree.xvala_xcls;
148                 return n.munge();
149                 
150
151         }
152         
153         public string munge ( )
154         {
155                 //return this.mungeToString(this.node);
156
157                 this.ignore("pack");
158                 this.ignore("init");
159                 this.ignore("xns");
160                 this.ignore("xtype");
161                 this.ignore("id");
162                 
163                 this.globalVars();
164                 this.classHeader();
165                 this.addSingleton();
166                 this.addTopProperties();
167                 this.addMyVars();
168                 this.addPlusProperties();
169                 this.addValaCtor();
170                 this.addUnderThis();
171                 this.addWrappedCtor();
172
173                 this.addInitMyVars();
174                 this.addWrappedProperties();
175                 this.addChildren();
176                 this.addInit();
177                 this.addListeners();
178                 this.addEndCtor();
179                 this.addUserMethods();
180                 this.iterChildren();
181                 
182                 return this.ret;
183                  
184                          
185         } 
186         public string mungeChild(  Node cnode)
187         {
188                 var x = new  NodeToVala(cnode,  this.depth+1, this);
189                 return x.munge();
190         }
191         public void addLine(string str= "")
192         {
193                 this.cur_line++;
194                 this.ret += str + "\n";
195         }
196         public void addMultiLine(string str= "")
197         {
198                 this.cur_line++;
199                 this.cur_line += str.split("\n").length;
200                 this.ret += str + "\n";
201         }
202          
203         
204         public void globalVars()
205         {
206                 if (this.depth > 0) {
207                         return;
208                 }
209                 // Global Vars..??? when did this get removed..?
210                 //this.ret += this.inpad + "public static " + this.xcls + "  " + this.node.xvala_id+ ";\n\n";
211
212                 this.addLine(this.inpad + "static " + this.xcls + "  _" + this.node.xvala_id+ ";");
213                 this.addLine();
214                    
215         }
216
217         void classHeader()
218         {
219                            
220                 // class header..
221                 // class xxx {   WrappedGtk  el; }
222                 this.node.line_start = this.cur_line;
223                 this.addLine(inpad + "public class " + this.xcls + " : Object \n" + 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.proplines.set(k, this.cur_line);
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
343                         this.node.proplines.set(k, this.cur_line);
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.proplines.set("* ctor", this.cur_line);
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.proplines.set("* xtype", this.cur_line);
509                         this.addLine(this.ipad + "this.el = new " + cls + "( "+ string.joinv(", ",args) + " );") ;
510                         return;
511                         
512                 }
513                 this.node.proplines.set("* xtype", this.cur_line);
514                 
515                 this.addLine(this.ipad + "this.el = new " + this.cls + "();");
516
517                         
518         }
519
520         void addInitMyVars()
521         {
522                         //var meths = this.palete.getPropertiesFor(item['|xns'] + '.' + item.xtype, 'methods');
523                         //print(JSON.stringify(meths,null,4));Seed.quit();
524                         
525                         
526                         
527                         // initialize.. my vars..
528                 this.addLine();
529                 this.addLine( this.ipad + "// my vars (dec)");
530                 
531                 var iter = this.myvars.list_iterator();
532                 while(iter.next()) {
533                         
534                         var k = iter.get();
535                         
536                         var ar  = k.strip().split(" ");
537                         var kname = ar[ar.length-1];
538                         
539                         var v = this.node.props.get(k);
540                         // ignore signals.. 
541                         if (v.length < 1) {
542                                 continue; 
543                         }
544                         if (v == "FALSE" || v == "TRUE") {
545                                 v = v.down();
546                         }
547                         //FIXME -- check for raw string.. "string XXXX"
548                         
549                         // if it's a string...
550                         
551                         
552                         this.addLine(this.ipad + "this." + kname + " = " +   v +";");
553                 }
554         }
555
556         
557
558
559         
560         void addWrappedProperties()
561         {
562                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
563                 if (cls == null) {
564                         return;
565                 }
566                         // what are the properties of this class???
567                 this.addLine();
568                 this.addLine(this.ipad + "// set gobject values");
569                 
570
571                 var iter = cls.props.map_iterator();
572                 while (iter.next()) {
573                         var p = iter.get_key();
574                         print("Check Write %s\n", p);
575                         if (!this.node.has(p)) {
576                                 continue;
577                         }
578                         if (this.shouldIgnoreWrapped(p)) {
579                                 continue;
580                         }
581                         
582                                 this.ignore(p);
583                         var v = this.node.get(p);
584
585                         var nodekey = this.node.get_key(p);
586
587                         // user defined properties.
588                         if (nodekey[0] == '#') {
589                                 continue;
590                         }
591                                 
592
593                         
594                         var is_raw = nodekey[0] == '$';
595                         
596                         // what's the type.. - if it's a string.. then we quote it..
597                         if (iter.get_value().type == "string" && !is_raw) {
598                                  v = "\"" +  v.escape("") + "\"";
599                         }
600                         if (v == "TRUE" || v == "FALSE") {
601                                 v = v.down();
602                         }
603                         if (iter.get_value().type == "float" && v[v.length-1] != 'f') {
604                                 v += "f";
605                         }
606                         
607                         
608                         this.addLine("%sthis.el.%s = %s;".printf(ipad,p,v)); // // %s,  iter.get_value().type);
609                                         
610                            // got a property..
611                            
612
613                 }
614                 
615         }
616         /**
617          *  pack the children into the parent.
618          * 
619          * if the child's id starts with '*' then it is not packed...
620          * - this allows you to define children and add them manually..
621          */
622
623         void addChildren()
624         {
625                                 //code
626                 if (this.node.items.size < 1) {
627                         return;
628                 }
629                          
630                 var iter = this.node.items.list_iterator();
631                 var i = -1;
632                 while (iter.next()) {
633                         i++;
634                                 
635                         var ci = iter.get();
636
637                         if (ci.xvala_id[0] == '*') {
638                                 continue; // skip generation of children?
639                         }
640                                         
641                         var xargs = "";
642                         if (ci.has("* args")) {
643                                 
644                                 var ar = ci.get("* args").split(",");
645                                 for (var ari = 0 ; ari < ar.length; ari++ ) {
646                                         var arg = ar[ari].split(" ");
647                                         xargs += "," + arg[arg.length -1];
648                                 }
649                         }
650                         // create the element..
651                         this.addLine(this.ipad + "var child_" + "%d".printf(i) + " = new " + ci.xvala_xcls +
652                                         "( _this " + xargs + ");" );
653                         
654                         // this is only needed if it does not have an ID???
655                         this.addLine(this.ipad + "child_" + "%d".printf(i) +".ref();"); // we need to reference increase unnamed children...
656                         
657                         if (ci.has("* prop")) {
658                                 this.addLine(ipad + "this.el." + ci.get("* prop") + " = child_" + "%d".printf(i) + ".el;");
659                                 continue;
660                         } 
661                                 
662
663         // not sure why we have 'true' in pack?!?
664                         if (!ci.has("pack") || ci.get("pack").down() == "false" || ci.get("pack").down() == "true") {
665                                 continue;
666                         }
667                         
668                         string[]  packing =  { "add" };
669                         if (ci.has("pack")) {
670                                 packing = ci.get("pack").split(",");
671                         }
672                         
673                         var pack = packing[0];
674                         this.addLine(this.ipad + "this.el." + pack.strip() + " (  child_" + "%d".printf(i) + ".el " +
675                                    (packing.length > 1 ? 
676                                                 (", " + string.joinv(",", packing).substring(pack.length+1))
677                                         :
678                                                         ""
679                                                 ) + " );");
680         
681                                           
682                         if (ci.xvala_id[0] != '+') {
683                                 continue; // skip generation of children?
684                                                 
685                         }
686                         // this.{id - without the '+'} = the element...
687                         this.addLine(this.ipad + "this." + ci.xvala_id.substring(1) + " =  child_" + "%d".printf(i) +  ";");
688                                   
689                 }
690         }
691
692         void addInit()
693         {
694
695                 
696                 if (!this.node.has("init")) {
697                                 return;
698                 }
699                 this.addLine();
700                 this.addLine(ipad + "// init method");
701                 this.addLine();
702                 this.node.proplines.set("init", this.cur_line);
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                                 this.node.listenlines.set(k, this.cur_line);
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.proplines.set(k, this.cur_line);
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