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