src/Builder4/About.vala.c
[app.Builder.js] / src / JsRender / Roo.vala
1 /*
2  * Renderer for Javascript output (roo library based)
3  * 
4  * - translation support
5  * -  doubleStringProps contains elements that are 'translable'
6  *    ** in the old method this our compression tool could extract them
7  *  - the  new idea is to make a list at the top of the javascript file
8  *    and output a map...
9  *    
10  * 
11  * 
12  * 
13  * 
14  */
15 namespace JsRender {
16
17     static int rid = 0; 
18    
19     class Roo : JsRender 
20     {
21         string region;
22         bool disabled;
23
24
25         
26         public Roo(Project.Project project, string path) {
27             base( project, path);
28             this.xtype = "Roo";
29              this.language = "js";
30             
31            this.content_type = "";
32            
33             //this.items = false;
34             //if (cfg.json) {
35             //    var jstr =  JSON.parse(cfg.json);
36             //    this.items = [ jstr ];
37             //    //console.log(cfg.items.length);
38             //    delete cfg.json; // not needed!
39             // }
40             this.modOrder = "001"; /// sequence id that this uses.
41             this.region = "center";
42             this.disabled = false;
43             
44             // super?!?!
45             this.id = "file-roo-%d".printf(rid++);
46             //console.dump(this);
47             // various loader methods..
48
49             string[]  dsp = { 
50                                 "title",
51                 "legend",
52                 "loadingText",
53                 "emptyText",
54                 "qtip",
55                 "value",
56                 "text",
57                 "emptyMsg",
58                 "displayMsg",
59                 "html",
60                 "headline",
61                 "header",
62                 "placeholder",
63                 "fieldLabel",
64                 
65                 };
66             for (var i=0;i<dsp.length;i++) {
67                 this.doubleStringProps.add(dsp[i]);
68             }
69
70             
71         }
72     
73  
74                 
75                 public   override void   removeFiles() {
76                         var html = GLib.Path.get_dirname(this.path) +"/templates/" + name + ".html";
77                         if (FileUtils.test(html, FileTest.EXISTS)) {
78                                 GLib.FileUtils.remove(html);
79                         }
80                         var js = GLib.Path.get_dirname(this.path) +"/" + name + ".html";
81                         if (FileUtils.test(js, FileTest.EXISTS)) {
82                                 GLib.FileUtils.remove(js);
83                         }
84                 }
85                 
86         public  override void  loadItems() throws GLib.Error // : function(cb, sync) == original was async.
87         {
88             
89                                  
90                         print("load Items!");
91                         if (this.tree != null) {
92                                 return;
93                         }
94                         print("load " + this.path);
95
96                         var pa = new Json.Parser();
97                         pa.load_from_file(this.path);
98                         var node = pa.get_root();
99
100                         if (node.get_node_type () != Json.NodeType.OBJECT) {
101                                 throw new Error.INVALID_FORMAT ("Unexpected element type %s", node.type_name ());
102                         }
103                         var obj = node.get_object ();
104                 
105                 
106                         this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
107                         this.name = this.jsonHasOrEmpty(obj, "name");
108                         this.parent = this.jsonHasOrEmpty(obj, "parent");
109                         this.permname = this.jsonHasOrEmpty(obj, "permname");
110                         this.title = this.jsonHasOrEmpty(obj, "title");
111                         this.modOrder = this.jsonHasOrEmpty(obj, "modOrder");
112
113                         var bjs_version_str = this.jsonHasOrEmpty(obj, "bjs-version");
114                         bjs_version_str = bjs_version_str == "" ? "1" : bjs_version_str;
115
116                         
117                         // load items[0] ??? into tree...
118                         if (obj.has_member("items") 
119                                 && 
120                                 obj.get_member("items").get_node_type() == Json.NodeType.ARRAY
121                                 &&
122                                 obj.get_array_member("items").get_length() > 0
123                         ) {
124                                 this.tree = new Node(); 
125                                 var ar = obj.get_array_member("items");
126                                 var tree_base = ar.get_object_element(0);
127                                 this.tree.loadFromJson(tree_base, int.parse(bjs_version_str));
128                         }
129                         this.loaded = true;
130                         this.toSource(); // force it to number the lines...
131
132             
133         }
134         
135         
136         public  override  void save()
137         {
138             
139                 print("--- JsRender.Roo.save");
140                 print("save() - reset transStrings\n");
141                 this.transStrings = new Gee.HashMap<string,string>();
142                 this.findTransStrings(this.tree);
143                 
144                 this.saveBJS();
145
146                 // no tree..
147                 if (this.tree == null) {
148                         return;
149                 }
150                 // now write the js file..
151                 string js;
152                 try {
153                         Regex regex = new Regex("\\.(bjs|js)$");
154
155                         js = regex.replace(this.path,this.path.length , 0 , ".js");
156                 } catch (RegexError e) {
157                         this.name = "???";
158                         print("count not make filename from path");
159                         return;
160                 }
161
162
163                 //var d = new Date();
164                 var js_src = this.toSource();            
165                 //print("TO SOURCE in " + ((new Date()) - d) + "ms");
166                 try {
167                         this.writeFile(js, js_src);            
168                 } catch (FileError e ) {
169                         print("Save failed\n");
170                 }
171                 // for bootstrap - we can write the HTML to the templates directory..
172                  
173             //var top = this.guessName(this.items[0]);
174             //print ("TOP = " + top)
175              
176             
177             
178             
179         }
180
181          
182
183          
184         public override void saveHTML ( string html )
185         {
186                  
187                 var top = this.tree.fqn();
188                 print ("TOP = " + top + "\n" );
189                 if (top.index_of("Roo.bootstrap.") < 0 &&
190                     top.index_of("Roo.mailer.") < 0
191                         ) {
192                         return;
193                 }
194                 
195                 
196                 //now write the js file..
197                 string fn;
198                 try {
199                         Regex regex = new Regex("\\.(bjs|js)$");
200
201                         fn = regex.replace(this.path,this.path.length , 0 , ".html");
202                 } catch (RegexError e) {
203                         this.name = "???";
204                         print("count not make filename from path");
205                         return;
206                 }
207                 var bn = GLib.Path.get_basename(fn);
208                 var dn = GLib.Path.get_dirname(fn);
209
210                 var targetdir = dn + (
211                         top.index_of("Roo.mailer.") < 0 ? "/templates" : "" );
212                               
213                 
214                 if (!FileUtils.test(targetdir, FileTest.IS_DIR)) {
215                         print("Skip save - templates folder does not exist : %s\n", targetdir);
216                         return;
217                 }
218                 print("SAVE HTML -- %s\n%s\n",targetdir + "/" +  bn, html);
219                 try {
220                         this.writeFile(targetdir + "/" +  bn , html);            
221                 } catch (FileError e ) {
222                         print("SaveHtml failed\n");
223                 }
224             
225             
226             
227         }
228
229                 public Gee.ArrayList<string> findxincludes(Node node,   Gee.ArrayList<string> ret)
230                 {
231                         
232                         if (node.props.has_key("* xinclude")) {
233                                 ret.add(node.props.get("* xinclude"));
234                         }
235                         for (var i =0; i < node.items.size; i++) {
236                                 this.findxincludes(node.items.get(i), ret);
237                         }
238                         return ret;
239                                 
240                 }
241                  
242
243                  
244                 public override void  findTransStrings(Node? node )
245                 {
246                         // iterate properties...
247                         // use doubleStringProps
248                         
249                         // flagging a translatable string..
250                         // the code would use string _astring to indicate a translatable string
251                         // the to use it it would do String.format(this._message, somedata);
252                         
253                         // loop through and find string starting with '_' 
254                         if (node == null) {
255                                 return;
256                         }               
257                         
258                         var iter = node.props.map_iterator();
259                         while (iter.next()) {
260                                 // key formats : XXXX
261                                 // XXX - plain
262                                 // string XXX - with type
263                                 // $ XXX - with flag (no type)
264                                 // $ string XXX - with flag
265                                 string kname;
266                                 string ktype;
267                                 string kflag;
268                                 node.normalize_key(iter.get_key(), out kname, out kflag, out ktype);
269                                 if (kflag == "$") {
270                                         continue;
271                                 }
272                                 var str = iter.get_value();
273                                 if (this.doubleStringProps.index_of(kname) > -1) {
274                                         print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
275                                         this.transStrings.set(str,  
276                                                 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
277                                         );
278                                         continue;
279                                 }
280                                 
281                                 if (ktype.down() == "string" && kname[0] == '_') {
282                                         print("flag=%s type=%s name=%s : %s\n", kflag,ktype,kname,str);
283                                         this.transStrings.set(str,  
284                                                 GLib.Checksum.compute_for_string (ChecksumType.MD5, str)
285                                         );
286                                         continue;
287                                 }
288                                 
289                         }
290                          
291
292                         
293                         // iterate children..
294                         for (var i =0; i < node.items.size; i++) {
295                                 this.findTransStrings(node.items.get(i) );
296                         }
297                 
298                                 
299                 }  
300                 
301                 public string  transStringsToJs()
302                 {
303                         
304                         print("Roo.transStringsToJs()\n");
305                         if (this.transStrings.size < 1) {
306                                 print("Roo.transStringsToJs() size < 1?\n");
307                                 return "";
308                         }
309                          
310                         string[] kvs = {};
311                         var iter = this.transStrings.map_iterator();
312                         while (iter.next()) {
313                                 kvs +=  ("  '" + iter.get_value() + "' :" + 
314                                         this.tree.quoteString(iter.get_key())
315                                         );
316                         }
317                         return " _strings : {\n" + string.joinv(",\n", kvs) + "\n" + 
318                                 " },";
319                                 
320                 
321               
322                         
323                 }
324                   
325         /**
326          * javascript used in Webkit preview 
327          */
328         
329         public override string  toSourcePreview()
330         {
331                         print("toSourcePreview() - reset transStrings\n");
332                         this.transStrings = new Gee.HashMap<string,string>();
333                         
334                 
335                         print("to source preview\n");
336                         if (this.tree == null) {
337                                 return "";
338                         }
339                         this.findTransStrings(this.tree);
340                         var top = this.tree.fqn();
341                         var xinc = new Gee.ArrayList<string>(); 
342
343                         this.findxincludes(this.tree, xinc);
344                         print("got %d xincludes\n", xinc.size);
345                         var prefix_data = "";
346                         if (xinc.size > 0 ) {
347                                 for(var i = 0; i < xinc.size; i++) {
348                                         print("check xinclude:  %s\n", xinc.get(i));
349                                         var sf = this.project.getByName(xinc.get(i));
350                                         if (sf == null) {
351                                                 print("Failed to find file by name?\n");
352                                                 continue;
353                                         }
354
355                                         sf.loadItems();
356                                         sf.findTransStrings(sf.tree);
357                                         var xinc_str = sf.toSource();
358                                         
359                                         //string xinc_str;
360                                         //FileUtils.get_contents(js, out xinc_str);
361                                         prefix_data += "\n" + xinc_str + "\n";
362                                         
363                                 }
364
365                         }
366
367                         
368                         
369                         //print(JSON.stringify(this.items, null,4));
370                                    
371                         if (top == null) {
372                                 print ("guessname returned false");
373                                 return "";
374                         }
375
376
377                         if (top.contains("Dialog")) {
378                                 return prefix_data + this.toSourceDialog(true);
379                         }
380
381                         if (top.contains("Modal")) {
382                                 return prefix_data + this.toSourceModal(true);
383                         }
384
385                         return prefix_data + this.toSourceLayout(true);
386                                 
387                                 
388             
389         }
390         public override void setSource(string str) {}
391         /**
392          * This needs to use some options on the project
393          * to determine how the file is output..
394          * 
395          * At present we are hard coding it..
396          * 
397          * 
398          */
399         public override string toSource()
400         {
401             // dump the file tree back out to a string.
402             
403             // we have 2 types = dialogs and components
404             // 
405             
406             
407                         if (this.tree == null) {
408                                 return "";
409                         }
410             var top = this.tree.fqn();
411             if (top == null) {
412                 return "";
413             }
414             
415             
416             
417             // get the translatable strings.. = we reload them again so calling methods get the right data...
418             this.transStrings = new Gee.HashMap<string,string>();
419                         this.findTransStrings(this.tree);
420             
421             
422             if (top.contains("Dialog")) {
423                 return this.toSourceDialog(false);
424             }
425             
426             if (top.contains("Modal")) {
427                 return this.toSourceModal(false);
428             }
429             return this.toSourceLayout(false);
430             
431             /*
432             eventually support 'classes??'
433              return this.toSourceStdClass();
434             */
435               
436         }
437         
438         /**
439                  * 
440                  * munge JSON tree into Javascript code.
441                  *
442                  * NOTE - needs a deep copy of original tree, before starting..
443                  *     - so that it does not modify current..
444                  * 
445                  * FIXME: + or / prefixes to properties hide it from renderer.
446                  * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
447                  * FIXME: needs to understand what properties might be translatable (eg. double quotes)
448                  * 
449                  * @arg {object} obj the object or array to munge..
450                  * @arg {boolean} isListener - is the array being sent a listener..
451                  * @arg {string} pad - the padding to indent with. 
452                  */
453                 
454                 public string mungeToStringWrap(string pad, string prefix, string suffix)
455                 {
456                         if (this.tree == null) {
457                                 return "";
458                         }
459                         var x = new NodeToJs(this.tree, this.doubleStringProps, pad, null);
460                         x.cur_line = prefix.split("\n").length;
461                         
462                         var ret = x.munge();
463                         //var nret = x.ret;
464                         
465                         // output both files.. so we can diff them...
466                         //this.writeFile("/tmp/old.js", ret);
467                         //this.writeFile("/tmp/new.js", nret);                  
468                         return prefix +  ret + suffix;
469                         
470                     
471                 }
472         
473         
474        
475         public string outputHeader()
476         {
477                 string[] s = {
478                         "//<script type=\"text/javascript\">",
479                         "",
480                         "// Auto generated file - created by app.Builder.js- do not edit directly (at present!)",
481                         ""
482                    
483                 };  
484                 var ret=  string.joinv("\n",s);
485                 var bits = this.name.split(".");
486                 if (bits.length > 1) {
487                         ret += "\nRoo.namespace(\'" + 
488                                 this.name.substring(0, this.name.length - (bits[bits.length-1].length + 1)) +
489                                 "');\n";
490                                 
491                 }
492                 /// genericlly used..
493                   
494                 return ret;
495             
496        
497         }
498         // a standard dialog module.
499         // fixme - this could be alot neater..
500         public string toSourceDialog(bool isPreview) 
501         {
502             
503             //var items = JSON.parse(JSON.stringify(this.items[0]));
504             
505             
506            
507  
508             string[] adda = { " = {",
509                 "",
510                 this.transStringsToJs() ,
511                 "",
512                 " dialog : false,",
513                 " callback:  false,",
514                 "",   
515                 " show : function(data, cb)",
516                 " {",
517                 "  if (!this.dialog) {",
518                 "   this.create();",
519                 "  }",
520                 "",
521                 "  this.callback = cb;",
522                 "  this.data = data;",
523                 "  this.dialog.show(this.data._el);",
524                 "  if (this.form) {",
525                 "   this.form.reset();",
526                 "   this.form.setValues(data);",
527                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
528                 "  }",
529                 "",   
530                 " },",
531                 "",
532                 " create : function()",
533                 " {",
534                 "   var _this = this;",
535                 "   this.dialog = Roo.factory(" 
536             };
537             string[] addb = {  
538                    ");",
539                 " }",
540                 "};",
541                 ""
542             };
543              
544             return this.mungeToStringWrap("    ",   
545                         this.outputHeader() + "\n" + this.name + string.joinv("\n", adda), //header
546                         string.joinv("\n", addb) // footer
547                 );
548              
549              
550              
551              
552         }
553         /**
554          Bootstrap modal dialog 
555          
556         */
557         
558         
559         public string toSourceModal(bool isPreview) 
560         {
561             
562             
563             //var items = JSON.parse(JSON.stringify(this.items[0]));
564              
565             
566             string[] adda = { " = {",
567                 "",
568                 this.transStringsToJs() ,
569                 "",
570                 " dialog : false,",
571                 " callback:  false,",
572                 "",   
573                 " show : function(data, cb)",
574                 " {",
575                 "  if (!this.dialog) {",
576                 "   this.create();",
577                 "  }",
578                 "",
579                 "  this.callback = cb;",
580                 "  this.data = data;",
581                 "  this.dialog.show(this.data._el);",
582                 "  if (this.form) {",
583                 "   this.form.reset();",
584                 "   this.form.setValues(data);",
585                 "   this.form.fireEvent('actioncomplete', this.form,  { type: 'setdata', data: data });",
586                 "  }",
587                 "",   
588                 " },",
589                 "",
590                 " create : function()",
591                 " {",
592                 "  var _this = this;",
593                 "  this.dialog = Roo.factory("
594             };
595             string[] addb =  {
596                 "  );",
597                 " }",
598                 "};",
599                 ""
600             };
601                         return this.mungeToStringWrap("    ",   
602                         this.outputHeader() + "\n" +  this.name + string.joinv("\n", adda), // header
603                         string.joinv("\n", addb) // footer
604                 );
605              
606              
607              
608         }
609          
610         
611         
612         
613         
614         public string   pathToPart()
615         {
616             var dir = Path.get_basename(Path.get_dirname(this.path));
617             var ar = dir.split(".");
618             var modname = ar[ar.length-1];
619             
620             // now we have the 'module name'..
621             var fbits = Path.get_basename(this.path).split(".");
622             
623              
624             var npart = fbits[fbits.length - 2]; // this should be 'AdminProjectManager' for example...
625             if (modname.length < npart.length && npart.substring(0, modname.length) == modname) {
626                 npart = npart.substring(modname.length);
627             }
628             return "[" + this.tree.quoteString(modname) + ", " + this.tree.quoteString(npart) + " ]";
629             //return ret;
630             
631             
632             
633             
634         }
635         
636         // a layout compoent 
637         public string toSourceLayout(bool isPreview) 
638         {
639           
640             
641                 if (isPreview) {
642                         //       topItem.region = 'center';
643                         //    topItem.background = false;
644                 }
645             
646                 var  modkey = this.modOrder + "-" +   this.name;
647                 try {
648                         var reg = new Regex("[^A-Za-z.]+");
649             
650                          modkey = this.modOrder + "-" + reg.replace(this.name, this.name.length, 0 , "-");
651             } catch (RegexError e) {
652                         //noop..
653             }
654                 string  parent =   (this.parent.length > 0 ?  "'" + this.parent + "'" :  "false");
655
656                 
657                 
658                 if (isPreview) {
659                         // set to false to ensure this is the top level..
660                         parent = "false";
661                                 var topnode = this.tree.fqn();
662                                 print("topnode = %s\n", topnode);
663                         if (GLib.Regex.match_simple("^Roo\\.bootstrap\\.",topnode) &&
664                             topnode != "Roo.bootstrap.Body"
665                         ) {
666                                 parent = "\"#bootstrap-body\"";
667                         }
668                           
669                 }
670             
671             
672             
673             var pref = this.outputHeader() + "\n" +
674                         
675                         this.name  +  " = new Roo.XComponent({\n" +
676                         "\n" + 
677                         this.transStringsToJs()  +    "\n" +
678                 "\n" +
679                         "  part     :  "+ this.pathToPart() + ",\n" +
680                                 /// critical used by builder to associate modules/parts/persm
681                         "  order    : '" +modkey+"',\n" +
682                         "  region   : '" + this.region   +"',\n" +
683                         "  parent   : "+ parent + ",\n" +
684                         "  name     : " + this.tree.quoteString(this.title.length > 0 ? this.title : "unnamed module") + ",\n" +
685                         "  disabled : " + (this.disabled ? "true" : "false") +", \n" +
686                         "  permname : '" + (this.permname.length > 0 ? this.permname : "") +"', \n" +
687                             
688                        // "    tree : function() { return this._tree(); },\n" +   //BC
689                         "  _tree : function()\n" +
690                         "  {\n" +
691                         "   var _this = this;\n" + // bc
692                         "   var MODULE = this;\n" + /// this looks like a better name.
693                         "   return ";
694                         
695                     return this.mungeToStringWrap("   ", pref,  ";" +
696                         "  }\n" +
697                         "});\n"
698                 );
699                       
700               
701         }
702             
703         public new string? guessName (Node? ar) // turns the object into full name.
704         {
705              // eg. xns: Roo, xtype: XXX -> Roo.xxx
706             if (ar == null) {
707                 return null;
708             }
709             
710             string[] ret = {} ;
711             ret += (ar.get("|xns").length < 1 ? "Roo": ar.get("|xns"));
712              
713             
714             if ( ar.get("xtype").length < 1) {
715                 return null;
716             }
717                     
718             var xtype = ar.get("xtype");
719
720             if (xtype[0] == '*') { // prefixes????
721                 xtype  = xtype.substring(1);
722             }
723             if (! Regex.match_simple("^Roo", xtype)) {
724                 
725                 // already starts with roo...
726                 ret = {};
727             }
728             ret += xtype;
729             var str =  string.joinv(".", ret);
730             
731             return str;
732            // 
733             //Palete.Palete.factory("Roo").guessName(str);
734             
735                             
736                                  
737         }
738         
739         string getHelpUrl(string cls)
740         {
741             return "http://www.roojs.com/roojs1/docs/symbols/" + cls + ".html";
742         }
743                  
744      
745     }
746 }