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                         if (this.xtype == "Gtk") {
279                                 ret.set_string_member("build_module", this.build_module  == null ? "" : this.build_module);
280                         }
281                         
282                         if (this.transStrings.size > 0) {
283                                 var tr =  new Json.Object();
284                                 var iter = this.transStrings.map_iterator();
285                                 while (iter.next()) {
286                                         tr.set_string_member(iter.get_value(), iter.get_key());
287                                 }
288                                 ret.set_object_member("strings", tr);
289             }
290                         
291                         
292                         
293                         var ar = new Json.Array();
294                         // empty files do not have a tree.
295                         if (this.tree != null) {
296                                 ar.add_object_element(this.tree.toJsonObject());
297                         }
298                         ret.set_array_member("items", ar);
299                 
300                     return ret;
301                 }
302                 
303                 
304
305                 public string getTitle ()
306                 {
307                     if (this.title.length > 0) {
308                         return this.title;
309                     }
310                     var a = this.path.split("/");
311                     return a[a.length-1];
312                 }
313                 public string getTitleTip()
314                 {
315                     if (this.title.length > 0) {
316                         return "<b>" + this.title + "</b> " + this.path;
317                     }
318                     return this.path;
319                 }
320                 /*
321                     sortCn: function()
322                     {
323                         this.cn.sort(function(a,b) {
324                             return a.path > b.path;// ? 1 : -1;
325                         });
326                     },
327                 */
328                     // should be in palete provider really..
329
330
331                 public Palete.Palete palete()
332                 {
333                         return Palete.factory(this.xtype);
334
335                 }
336                 
337                 public string guessName(Node ar) // turns the object into full name.
338                 {
339                      // eg. xns: Roo, xtype: XXX -> Roo.xxx
340                     if (!ar.hasXnsType()) {
341                        return "";
342                     }
343                     
344                     return ar.get("* xns") + "." + ar.get("* xtype");
345                                       
346                                         
347                 }
348                 /**
349                  *  non-atomic write (replacement for put contents, as it creates temporary files.
350                  */
351                 public void writeFile(string path, string contents) throws GLib.IOError, GLib.Error
352                 {
353
354                                  
355                         var f = GLib.File.new_for_path(path);
356                         var data_out = new GLib.DataOutputStream(
357                                           f.replace(null, false, GLib.FileCreateFlags.NONE, null)
358                        );
359                         data_out.put_string(contents, null);
360                         data_out.close(null);
361                 }
362                 /*
363                 copyTo: function(path, cb)
364                 {
365                     var _this = this;
366                     this.loadItems(function() {
367                         
368                         _this.path = path;
369                         cb();
370                     });
371                     
372                 },
373                 */
374                 
375                 /**
376                  * 
377                  * munge JSON tree into Javascript code.
378                  *
379                  * NOTE - needs a deep copy of original tree, before starting..
380                  *     - so that it does not modify current..
381                  * 
382                  * FIXME: + or / prefixes to properties hide it from renderer.
383                  * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
384                  * FIXME: needs to understand what properties might be translatable (eg. double quotes)
385                  * 
386                  * @arg {object} obj the object or array to munge..
387                  * @arg {boolean} isListener - is the array being sent a listener..
388                  * @arg {string} pad - the padding to indent with. 
389                  */
390                 
391                 public string mungeToString(string pad)
392                 {
393                         if (this.tree == null) {
394                                 return "";
395                         }
396                         var x = new NodeToJs(this.tree, this.doubleStringProps, pad);
397                         return x.munge();
398                         
399                     
400                 }
401                 public abstract void save();
402                 public abstract void saveHTML(string html);
403                 public abstract string toSource() ;
404                 public abstract string toSourcePreview() ;
405                 public abstract void removeFiles() ;
406                  public abstract void  findTransStrings(Node? node );
407         } 
408
409 }
410