src/JsRender/JsRender.vala
[app.Builder.js] / src / JsRender / JsRender.vala
1 //<Script type="text/javascript">
2
3 namespace JsRender {
4
5
6         public errordomain Error {
7                 INVALID_FORMAT,
8                 RENAME_FILE_EXISTS
9         }
10                 
11         public abstract class JsRender  : Object {
12                 /**
13                  * @cfg {Array} doubleStringProps list of properties that can be double quoted.
14                  */
15                 public Gee.ArrayList<string> doubleStringProps;
16                 
17                 public string id;
18                 public string name;   // is the JS name of the file.
19                 public string fullname;
20                 public string path;  // is the full path to the file.
21                 public string parent;  // JS parent.
22                 public string region;  // RooJS - insert region.
23         
24                 public string title;  // a title.. ?? nickname.. ??? -
25                 public string build_module; // module to build if we compile (or are running tests...)
26                 
27
28                 public string permname;
29                 public string language;
30                 public string modOrder;
31                 public string xtype;
32                 public uint64 webkit_page_id; // set by webkit view - used to extract extension/etc..
33                     
34                 public Project.Project project;
35                 //Project : false, // link to container project!
36                 
37                 public Node tree; // the tree of nodes.
38                 
39                 public GLib.List<JsRender> cn; // child files.. (used by project ... should move code here..)
40
41                 public bool hasParent; 
42                 
43                 public Gee.HashMap<string,string> transStrings; // map of md5 -> string.
44                 
45
46                 public signal void changed (Node? node, string source); 
47
48                 /**
49                  * UI componenets
50                  * 
51                  */
52                 //public Xcls_Editor editor;
53                 
54                 
55                 
56                 public JsRender(Project.Project project, string path) {
57                     
58                         this.cn = new GLib.List<JsRender>();
59                         this.path = path;
60                         this.project = project;
61                         this.hasParent = false;
62                         this.parent = "";
63                         this.tree = null;
64                         this.title = "";
65                         this.region = "";
66                         this.permname = "";
67                         this.modOrder = "";
68                         this.language = "";
69                         this.build_module = "";
70                         print("JsRender.cto() - reset transStrings\n");
71                         this.transStrings = new Gee.HashMap<string,string> ();
72                         
73                         // should use basename reallly...
74                         
75                         var ar = this.path.split("/");
76                         // name is in theory filename without .bjs (or .js eventually...)
77                         try {
78                                 Regex regex = new Regex ("\\.(bjs|js)$");
79
80                                 this.name = ar.length > 0 ? regex.replace(ar[ar.length-1],ar[ar.length-1].length, 0 , "") : "";
81                         } catch (Error e) {
82                                 this.name = "???";
83                         }
84                         this.fullname = (this.parent.length > 0 ? (this.parent + ".") : "" ) + this.name;
85
86                         this.doubleStringProps = new Gee.ArrayList<string>();
87
88                 }
89                 
90                 public void renameTo(string name) 
91                 {
92                         
93                         var bjs = GLib.Path.get_dirname(this.path) +"/" +  name + ".bjs";
94                         if (FileUtils.test(bjs, FileTest.EXISTS)) {
95                                 throw new Error.RENAME_FILE_EXISTS("File exists %s\n",name);
96                         }
97                         GLib.FileUtils.remove(this.path);
98                         this.removeFiles();
99                         // remove other files?
100                         
101                         this.name = name;
102                         this.path = bjs;
103                         
104                 }
105                 
106
107                 
108                 // not sure why xt is needed... -> project contains xtype..
109                 
110                 public static JsRender factory(string xt, Project.Project project, string path)
111                 {
112          
113                         switch (xt) {
114                                 case "Gtk":
115                                         return new Gtk(project, path);
116                                 case "Roo":
117                                         return new Roo(project, path);
118                         }
119                         throw new Error.INVALID_FORMAT("JsRender Factory called with xtype=%s", xt);
120                         return null;    
121                 }
122
123                 public string toJsonString()
124                 {
125                         var generator = new Json.Generator ();
126                         generator.indent = 4;
127                         generator.pretty = true;
128                         var node = new Json.Node(Json.NodeType.OBJECT);
129                         node.set_object(this.toJsonObject());
130                         generator.set_root(node);
131                         return generator.to_data(null);
132                 }
133         
134                 public string nickType()
135                 {
136                         var ar = this.name.split(".");
137                         string[] ret = {};
138                         for (var i =0; i < ar.length -1; i++) {
139                                 ret += ar[i];
140                         }
141                         return string.joinv(".", ret);
142                         
143                 }
144                 public string nickName()
145                 {
146                         var ar = this.name.split(".");
147                         return ar[ar.length-1];
148                         
149                 }
150
151                 
152                 public string getIconFileName(bool return_default)
153                 {
154                          
155                         var m5 = GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5,this.path); 
156
157                         var dir = GLib.Environment.get_home_dir() + "/.Builder/icons";
158                         if (!FileUtils.test(dir, FileTest.IS_DIR)) {
159                                  File.new_for_path(dir).make_directory();
160                         }
161                         var fname = dir + "/" + m5 + ".png";
162                         
163                         if (!return_default) {
164                                 print("getIconFileName return %s\n", fname);
165                                 return fname;
166                         }
167                         
168                         if (FileUtils.test(fname, FileTest.EXISTS)) {
169                                 print("getIconFileName return %s\n", fname);
170                                 return fname;
171                         }
172                         // we need to create this somehow...
173                         print("getIconFileName return %s\n", GLib.Environment.get_home_dir() + "/.Builder/test.jpg");
174                         return  GLib.Environment.get_home_dir() + "/.Builder/test.jpg";
175
176                 }
177                 
178
179                 public void saveBJS()
180                 {
181                      
182                     var generator = new Json.Generator ();
183                     generator.indent = 1;
184                     generator.pretty = true;
185                     var node = new Json.Node(Json.NodeType.OBJECT);
186                     node.set_object(this.toJsonObject());
187                     generator.set_root(node);
188                     
189                     print("WRITE :%s\n " , this.path);// + "\n" + JSON.stringify(write));
190                     try {
191                                 this.writeFile(this.path, generator.to_data(null));
192                         //generator.to_file(this.path);
193                     } catch(Error e) {
194                         print("Save failed");
195                     }
196                 }
197                  
198                  
199
200                 public abstract void loadItems() throws GLib.Error;
201                 
202                 /**
203                  *
204                  * load from a javascript file.. rather than bjs..
205                  * 
206                  *
207                  */
208                  /*
209                 _loadItems : function(cb)
210                 {
211                     // already loaded..
212                     if (this.items !== false) {
213                         return false;
214                     }
215                       
216                     
217                     
218                     var tr = new  TokenReader(  { 
219                         keepDocs :true, 
220                         keepWhite : true,  
221                         keepComments : true, 
222                         sepIdents : false,
223                         collapseWhite : false,
224                         filename : args[0],
225                         ignoreBadGrammer: true
226                     });
227                     
228                     var str = File.read(this.path);
229                     var toks = tr.tokenize(new TextStream(str));  
230                     var rf = new JsParser(toks);
231                     rf.parse();
232                     var cfg = rf.cfg;
233                     
234                     this.modOrder = cfg.modOrder || '001';
235                     this.name = cfg.name.replace(/\.bjs/, ''); // BC!
236                     this.parent =  cfg.parent;
237                     this.permname =  cfg.permname || '';
238                     this.title =  cfg.title || cfg.name;;
239                     this.items = cfg.items || []; 
240                     //???
241                     //this.fixItems(_this, false);
242                     cb();
243                     return true;    
244                         
245                 },
246                 */
247                     /**
248                      * accepts:
249                      * { success : , failure : , scope : }
250                      * 
251                      * 
252                      * 
253                      */
254                 /*     
255                 void getTree ( o ) {
256                     print("File.getTree tree called on base object?!?!");
257                 }
258         */
259                 public string jsonHasOrEmpty(Json.Object obj, string key) {
260                         return obj.has_member(key) ? 
261                                                 obj.get_string_member(key) : "";
262                 }
263
264                 
265                 public Json.Object toJsonObject ()
266                 {
267                     
268                     
269                         var ret = new Json.Object();
270                         //ret.set_string_member("id", this.id); // not relivant..
271                         ret.set_string_member("name", this.name);
272                         ret.set_string_member("parent", this.parent == null ? "" : this.parent);
273                         ret.set_string_member("title", this.title == null ? "" : this.title);
274                         ret.set_string_member("path", this.path);
275                         //ret.set_string_member("items", this.items);
276                         ret.set_string_member("permname", this.permname  == null ? "" : this.permname);
277                         ret.set_string_member("modOrder", this.modOrder  == null ? "" : this.modOrder);
278                         
279                         if (this.transStrings.size > 0) {
280                                 var tr =  new Json.Object();
281                                 var iter = this.transStrings.map_iterator();
282                                 while (iter.next()) {
283                                         tr.set_string_member(iter.get_value(), iter.get_key());
284                                 }
285                                 ret.set_object_member("strings", tr);
286             }
287                         
288                         
289                         
290                         var ar = new Json.Array();
291                         // empty files do not have a tree.
292                         if (this.tree != null) {
293                                 ar.add_object_element(this.tree.toJsonObject());
294                         }
295                         ret.set_array_member("items", ar);
296                 
297                     return ret;
298                 }
299                 
300                 
301
302                 public string getTitle ()
303                 {
304                     if (this.title.length > 0) {
305                         return this.title;
306                     }
307                     var a = this.path.split("/");
308                     return a[a.length-1];
309                 }
310                 public string getTitleTip()
311                 {
312                     if (this.title.length > 0) {
313                         return "<b>" + this.title + "</b> " + this.path;
314                     }
315                     return this.path;
316                 }
317                 /*
318                     sortCn: function()
319                     {
320                         this.cn.sort(function(a,b) {
321                             return a.path > b.path;// ? 1 : -1;
322                         });
323                     },
324                 */
325                     // should be in palete provider really..
326
327
328                 public Palete.Palete palete()
329                 {
330                         return Palete.factory(this.xtype);
331
332                 }
333                 
334                 public string guessName(Node ar) // turns the object into full name.
335                 {
336                      // eg. xns: Roo, xtype: XXX -> Roo.xxx
337                     if (!ar.hasXnsType()) {
338                        return "";
339                     }
340                     
341                     return ar.get("* xns") + "." + ar.get("* xtype");
342                                       
343                                         
344                 }
345                 /**
346                  *  non-atomic write (replacement for put contents, as it creates temporary files.
347                  */
348                 public void writeFile(string path, string contents) throws GLib.IOError, GLib.Error
349                 {
350
351                                  
352                         var f = GLib.File.new_for_path(path);
353                         var data_out = new GLib.DataOutputStream(
354                                           f.replace(null, false, GLib.FileCreateFlags.NONE, null)
355                        );
356                         data_out.put_string(contents, null);
357                         data_out.close(null);
358                 }
359                 /*
360                 copyTo: function(path, cb)
361                 {
362                     var _this = this;
363                     this.loadItems(function() {
364                         
365                         _this.path = path;
366                         cb();
367                     });
368                     
369                 },
370                 */
371                 
372                 /**
373                  * 
374                  * munge JSON tree into Javascript code.
375                  *
376                  * NOTE - needs a deep copy of original tree, before starting..
377                  *     - so that it does not modify current..
378                  * 
379                  * FIXME: + or / prefixes to properties hide it from renderer.
380                  * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
381                  * FIXME: needs to understand what properties might be translatable (eg. double quotes)
382                  * 
383                  * @arg {object} obj the object or array to munge..
384                  * @arg {boolean} isListener - is the array being sent a listener..
385                  * @arg {string} pad - the padding to indent with. 
386                  */
387                 
388                 public string mungeToString(string pad)
389                 {
390                         if (this.tree == null) {
391                                 return "";
392                         }
393                         var x = new NodeToJs(this.tree, this.doubleStringProps, pad);
394                         return x.munge();
395                         
396                     
397                 }
398                 public abstract void save();
399                 public abstract void saveHTML(string html);
400                 public abstract string toSource() ;
401                 public abstract string toSourcePreview() ;
402                 public abstract void removeFiles() ;
403                  public abstract void  findTransStrings(Node? node );
404         } 
405
406 }
407