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