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