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