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