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 = this.cur_line;
66                 node.proplines = new Gee.HashMap<string,int>();
67                 node.listenlines = 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         addMultiLine
200         
201         public void globalVars()
202         {
203                 if (this.depth > 0) {
204                         return;
205                 }
206                 // Global Vars..
207                 //this.ret += this.inpad + "public static " + this.xcls + "  " + this.node.xvala_id+ ";\n\n";
208
209                 this.addLine("%sstatic %s _%s;".printf(this.inpad, this.xcls, this.node.xvala_id));
210                 this.addLine();
211                 //this.ret += this.inpad + "static " + this.xcls + "  _" + this.node.xvala_id+ ";\n\n";
212                                 
213                                 
214         }
215
216         void classHeader()
217         {
218                            
219                 // class header..
220                 // class xxx {   WrappedGtk  el; }
221                 this.node.line = this.cur_line;
222                 this.addLine(inpad + "public class " + this.xcls + " : Object \n" + this.inpad + "{");
223                 
224                  
225                 this.addLine(this.pad + "public " + this.cls + " el;");
226  
227                 this.addLine(this.pad + "private " + this.top.xcls + "  _this;)";
228                 this.addLine();
229                         
230                         
231                         
232                         // singleton
233         }
234         void addSingleton() 
235         {
236                 if (depth > 0) {
237                         return;
238                 }
239                 this.addLine(pad + "public static " + xcls + " singleton()");
240                 this.addLine(this.pad + "{")
241                 this.addLine(this.ipad +    "if (_" + this.node.xvala_id  + " == null) {");
242                 this.addLine(this.ipad +    "    _" + this.node.xvala_id + "= new "+ this.xcls + "();");  // what about args?
243                 this.addLine(this.ipad +    "}");
244                 this.addLine(this.ipad +    "return _" + this.node.xvala_id +";");
245                 this.addLine(this.pad + "}");
246         }
247                         
248         /**
249          * when ID is used... on an element, it registeres a property on the top level...
250          * so that _this.ID always works..
251          * 
252          */
253         void addTopProperties()
254         {
255                 if (this.depth > 0) {
256                         return;
257                 }
258                 // properties - global..??
259
260                 var iter = this.vitems.list_iterator();
261                 while(iter.next()) {
262                         var n = iter.get();
263
264                          
265                         if (!n.props.has_key("id") || n.xvala_id.length < 0) {
266                                 continue;
267                                 
268                         }
269                         if (n.xvala_id[0] == '*') {
270                                 continue;
271                         }
272                         if (n.xvala_id[0] == '+') {
273                                 continue;
274                         }
275                         this.addLine(this.pad + "public " + n.xvala_xcls + " " + n.xvala_id + ";");
276                         
277                 }
278                                 
279         }
280         /**
281          * create properties that are not 'part of the wrapped element.
282          * 
283          * 
284          */
285         
286         void addMyVars()
287         {
288                 this.addLine();
289                 this.addLine(this.ipad + "// my vars (def)");
290                         
291
292  
293                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
294                    
295                 if (cls == null) {
296                         return;
297                 }
298           
299                 
300                         // Key = TYPE:name
301                 var iter = this.node.props.map_iterator();
302                 while (iter.next()) {
303                         var k = iter.get_key();
304                         if (this.shouldIgnore(k)) {
305                                 continue;
306                         }
307                         var vv = k.strip().split(" ");
308                         // user defined method
309                         if (vv[0] == "|") {
310                                 continue;
311                         }
312                         if (vv[0] == "*") {
313                                 continue;
314                         }
315                                 
316                         if (vv[0] == "@") {
317                                 this.node.proplines.set(k, this.cur_line);
318                                 this.addLine(this.pad + "public signal" + k.substring(1)  + " "  + iter.get_value() + ";");
319                                 
320                                 this.ignore(k);
321                                 continue;
322                         }
323                         var min = (vv[0] == "$" || vv[0] == "#") ? 3 : 2; 
324                         if (vv.length < min) {
325                                 // skip 'old js style properties without a type'
326                                 continue;
327                         }
328                         
329                         var kname = vv[vv.length-1];
330
331                         if (this.shouldIgnore(kname)) {
332                                 continue;
333                         }
334                         
335                         // is it a class property...
336                         if (cls.props.has_key(kname) && vv[0] != "#") {
337                                 continue;
338                         }
339                         
340                         this.myvars.add(k);
341
342                         this.node.proplines.set(k, this.cur_line);
343                         this.addLine(this.pad + "public " + 
344                                 (k[0] == '$' || k[0] == '#' ? k.substring(2) : k ) + ";");
345                                 
346                         this.ignore(k);
347                         
348                                 
349                 }
350         }
351         
352         // if id of child is '+' then it's a property of this..
353         void addPlusProperties()
354         {
355                 if (this.node.items.size < 1) {
356                         return;
357                 }
358                 var iter = this.node.items.list_iterator();
359                 while (iter.next()) {
360                 var ci = iter.get();
361                                 
362                         if (ci.xvala_id[0] != '+') {
363                                 continue; // skip generation of children?
364                                 
365                         }
366                         this.node.proplines.set(k, this.cur_line);
367                         this.addLine(this.pad + "public " + ci.xvala_xcls + " " + ci.xvala_id.substring(1) + ";");
368                                            
369                         
370                 }
371         }
372         /**
373          * add the constructor definition..
374          */
375         void addValaCtor()
376         {
377                         
378                 
379                 // .vala props.. 
380                 
381                 string[] cargs = {};
382                 var cargs_str = "";
383                 // ctor..
384                 this.addLine();
385                 this.addLine(this.pad + "// ctor");
386                 
387                 if (this.node.has("* args")) {
388                         // not sure what this is supposed to be ding..
389                 
390                         cargs_str = ", " + this.node.get("* args");
391                         //var ar = this.node.get("* args");.split(",");
392                         //for (var ari =0; ari < ar.length; ari++) {
393                                 //      cargs +=  (ar[ari].trim().split(" ").pop();
394                                   // }
395                         }
396         
397                 if (this.depth < 1) {
398                  
399                         // top level - does not pass the top level element..
400                         this.addLine(this.pad + "public " + this.xcls + "(" +  cargs_str +")")
401                         this.addLine(this.pad + "{");
402                 } else {
403                                 
404                         // for sub classes = we passs the top level as _owner
405                         this.addLine(this.pad + "public " + this.xcls + "(" +  this.top.xcls + " _owner " + cargs_str + ")");
406                         this.addLine(this.pad + "{");
407                 }
408                 
409
410         }
411         /**
412          *  make sure _this is defined..
413          */
414         void addUnderThis() 
415         {
416                         // public static?
417                 if (depth < 1) {
418                         this.addLine( this.ipad + "_this = this;");
419                         return;
420                 }
421                 // for non top level = _this point to owner, and _this.ID is set
422                 
423                 this.addLine( this.ipad + "_this = _owner;");
424
425                 if (this.node.props.has_key("id")
426                         &&
427                         this.node.xvala_id != "" 
428                         && 
429                         this.node.xvala_id[0] != '*' 
430                         && 
431                         this.node.xvala_id[0] != '+' 
432                         ) {
433                                 this.addLine( this.ipad + "_this." + node.xvala_id  + " = this;");
434                    
435                 }
436                          
437         }
438         /**
439          * Initialize this.el to point to the wrapped element.
440          * 
441          * 
442          */
443
444         void addWrappedCtor()
445         {
446                 // wrapped ctor..
447                 // this may need to look up properties to fill in the arguments..
448                 // introspection does not workk..... - as things like gtkmessagedialog
449                 /*
450                 if (cls == 'Gtk.Table') {
451
452                 var methods = this.palete.getPropertiesFor(cls, 'methods');
453
454                 print(JSON.stringify(this.palete.proplist[cls], null,4));
455                 Seed.quit();
456                 }
457                 */
458                 if (this.node.has("* ctor")) {
459                         this.node.proplines.set("* ctor", this.curline);
460                         this.addLine(this.ipad + "this.el = " + this.node.get("* ctor")+ ";");
461                         return;
462                 }
463                  
464                 var  default_ctor = Palete.Gir.factoryFqn(this.node.fqn() + ".new");
465
466                  
467                 if (default_ctor != null && default_ctor.paramset != null && default_ctor.paramset.params.size > 0) {
468                         string[] args  = {};
469                         var iter =default_ctor.paramset.params.list_iterator();
470                         while (iter.next()) {
471                                 var n = iter.get().name;
472                                 if (!this.node.has(n)) {
473
474                                         if (iter.get().type.contains("int")) {
475                                                 args += "0";
476                                                 continue;
477                                         }
478                                         if (iter.get().type.contains("float")) {
479                                                 args += "0f";
480                                                 continue;
481                                         }
482                                         if (iter.get().type.contains("bool")) {
483                                                 args += "true"; // always default to true?
484                                                 continue;
485                                         }
486                                         // any other types???
487                                         
488                                         args += "null";
489                                         continue;
490                                 }
491                                 this.ignoreWrapped(n);
492                                 this.ignore(n);
493                                 
494                                 var v = this.node.get(n);
495
496                                 if (iter.get().type == "string") {
497                                         v = "\"" +  v.escape("") + "\"";
498                                 }
499                                 if (v == "TRUE" || v == "FALSE") {
500                                         v = v.down();
501                                 }
502
503                                 
504                                 args += v;
505
506                         }
507                         this.node.proplines.set("* xtype", this.curline);
508                         this.addLine(this.ipad + "this.el = new " + cls + "( "+ string.joinv(", ",args) + " );") ;
509                         return;
510                         
511                 }
512                 this.node.proplines.set("* xtype", this.curline);
513                 
514                 this.addLine(this.ipad + "this.el = new " + this.cls + "();");
515
516                         
517         }
518
519         void addInitMyVars()
520         {
521                         //var meths = this.palete.getPropertiesFor(item['|xns'] + '.' + item.xtype, 'methods');
522                         //print(JSON.stringify(meths,null,4));Seed.quit();
523                         
524                         
525                         
526                         // initialize.. my vars..
527                 this.addLine();
528                 this.addLine( this.ipad + "// my vars (dec)");
529                 
530                 var iter = this.myvars.list_iterator();
531                 while(iter.next()) {
532                         
533                         var k = iter.get();
534                         
535                         var ar  = k.strip().split(" ");
536                         var kname = ar[ar.length-1];
537                         
538                         var v = this.node.props.get(k);
539                         // ignore signals.. 
540                         if (v.length < 1) {
541                                 continue; 
542                         }
543                         if (v == "FALSE" || v == "TRUE") {
544                                 v = v.down();
545                         }
546                         //FIXME -- check for raw string.. "string XXXX"
547                         
548                         // if it's a string...
549                         
550                         
551                         this.addLine(this.ipad + "this." + kname + " = " +   v +";");
552                 }
553         }
554
555         
556
557
558         
559         void addWrappedProperties()
560         {
561                 var cls = Palete.Gir.factoryFqn(this.node.fqn());
562                 if (cls == null) {
563                         return;
564                 }
565                         // what are the properties of this class???
566                 this.ret += "\n" + this.ipad + "// set gobject values\n";
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.ret += "%sthis.el.%s = %s;\n".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.ret+= this.pad + "}\n";
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                         
777                 this.ret+= "\n" + pad + "// user defined functions \n";  
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                                 // function in the format of {type} (args) { .... }
792                                 var kk = k.substring(2);
793                                 var vv = iter.get_value();
794                                 this.ret += this.pad + "public " + kk + " " + this.padMultiline(this.pad, vv) + "\n";
795                         
796                                 
797                         }
798         }
799
800         void iterChildren()
801         {
802                         
803                         if (this.depth > 0) {
804                         this.ret+= this.inpad + "}\n";
805                         }
806                 
807                 var iter = this.node.items.list_iterator();
808                 var i = -1;
809                 while (iter.next()) {
810                                 this.ret += this.mungeChild(iter.get());
811                 }
812                          
813                         if (this.depth < 1) {
814                                 this.ret+= this.inpad + "}\n";
815                         }
816                         
817                 }
818
819         string padMultiline(string pad, string str)
820         {
821                 var ar = str.strip().split("\n");
822                 return string.joinv("\n" + pad , ar);
823         }
824         
825         void ignore(string i) {
826                 this.ignoreList.add(i);
827                 
828         }
829         void ignoreWrapped(string i) {
830                 this.ignoreWrappedList.add(i);
831                 
832         }
833         bool shouldIgnore(string i)
834         {
835                 return ignoreList.contains(i);
836         }
837         bool shouldIgnoreWrapped(string i)
838         {
839                 return ignoreWrappedList.contains(i);
840         }
841         
842 }
843         
844          
845         
846         
847
848