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