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                         var ar = new Json.Array();
275                         // empty files do not have a tree.
276                         if (this.tree != null) {
277                                 ar.add_object_element(this.tree.toJsonObject());
278                         }
279                         ret.set_array_member("items", ar);
280                 
281                     return ret;
282                 }
283                 
284                 
285
286                 public string getTitle ()
287                 {
288                     if (this.title.length > 0) {
289                         return this.title;
290                     }
291                     var a = this.path.split("/");
292                     return a[a.length-1];
293                 }
294                 public string getTitleTip()
295                 {
296                     if (this.title.length > 0) {
297                         return "<b>" + this.title + "</b> " + this.path;
298                     }
299                     return this.path;
300                 }
301                 /*
302                     sortCn: function()
303                     {
304                         this.cn.sort(function(a,b) {
305                             return a.path > b.path;// ? 1 : -1;
306                         });
307                     },
308                 */
309                     // should be in palete provider really..
310
311
312                 public Palete.Palete palete()
313                 {
314                         return Palete.factory(this.xtype);
315
316                 }
317                 
318                 public string guessName(Node ar) // turns the object into full name.
319                 {
320                      // eg. xns: Roo, xtype: XXX -> Roo.xxx
321                     if (!ar.hasXnsType()) {
322                        return "";
323                     }
324                     
325                     return ar.get("* xns") + "." + ar.get("* xtype");
326                                       
327                                         
328                 }
329                 /**
330                  *  non-atomic write (replacement for put contents, as it creates temporary files.
331                  */
332                 public void writeFile(string path, string contents) throws GLib.IOError, GLib.Error
333                 {
334
335                                  
336                         var f = GLib.File.new_for_path(path);
337                         var data_out = new GLib.DataOutputStream(
338                                           f.replace(null, false, GLib.FileCreateFlags.NONE, null)
339                        );
340                         data_out.put_string(contents, null);
341                         data_out.close(null);
342                 }
343                 /*
344                 copyTo: function(path, cb)
345                 {
346                     var _this = this;
347                     this.loadItems(function() {
348                         
349                         _this.path = path;
350                         cb();
351                     });
352                     
353                 },
354                 */
355                 
356                 /**
357                  * 
358                  * munge JSON tree into Javascript code.
359                  *
360                  * NOTE - needs a deep copy of original tree, before starting..
361                  *     - so that it does not modify current..
362                  * 
363                  * FIXME: + or / prefixes to properties hide it from renderer.
364                  * FIXME: '*props' - not supported by this.. ?? - upto rendering code..
365                  * FIXME: needs to understand what properties might be translatable (eg. double quotes)
366                  * 
367                  * @arg {object} obj the object or array to munge..
368                  * @arg {boolean} isListener - is the array being sent a listener..
369                  * @arg {string} pad - the padding to indent with. 
370                  */
371                 
372                 public string mungeToString(string pad)
373                 {
374                         if (this.tree == null) {
375                                 return "";
376                         }
377                         var x = new NodeToJs(this.tree, this.doubleStringProps, pad);
378                         return x.munge();
379                         
380                     
381                 }
382                 public abstract void save();
383                 public abstract void saveHTML(string html);
384                 public abstract string toSource() ;
385                 public abstract string toSourcePreview() ;
386                 public abstract void removeFiles() ;
387                   
388         } 
389
390 }
391