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