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