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