src/Project/Project.vala
[app.Builder.js] / src / Project / Project.vala
1 //<Script type="text/javascript">
2
3 /**
4  * Project Object
5  * 
6  * Projects can only contain one directory... - it can import other projects..(later)
7  * 
8  * we need to sort out that - paths is currently a key/value array..
9  * 
10  * 
11  * 
12  */
13 namespace Project {
14          public errordomain Error {
15                 INVALID_TYPE,
16                 NEED_IMPLEMENTING,
17                 MISSING_FILE,
18                 INVALID_VALUE,
19                 INVALID_FORMAT
20         }
21
22         // static array of all projects.
23         public Gee.HashMap<string,Project>  projects;
24         
25         
26         public bool  projects_loaded = false;
27
28         
29         public class Project : Object {
30                 
31                 public signal void on_changed (); 
32         
33                 public string id;
34                 public string fn = ""; // just a md5...
35                 public string name = "";
36                 public string runhtml = "";
37                 public string base_template = "";
38                 public string rootURL = "";
39                 public Gee.HashMap<string,string> paths;
40                 public Gee.HashMap<string,JsRender.JsRender> files ;
41                 //tree : false,
42                 public  string xtype;
43                 
44                 public Json.Object json_project_data;
45                 public Palete.RooDatabase roo_database;
46                  
47                 bool is_scanned; 
48            
49                 
50                 public Project (string path) {
51                         
52                         this.name = GLib.Path.get_basename(path); // default..
53                         this.json_project_data = new Json.Object();
54                         
55                         this.is_scanned = false;
56                         this.paths = new Gee.HashMap<string,string>();
57                         this.files = new Gee.HashMap<string,JsRender.JsRender>();
58                         //XObject.extend(this, cfg);
59                         //this.files = { }; 
60                         if (path.length > 0) {
61                                 this.paths.set(path, "dir");
62                         }
63                         // dummy roo database...
64                         this.initRooDatabase();
65                         
66                         
67                         
68                 }
69                 public void  initRooDatabase()
70                 {
71                          
72                         this.roo_database = new Palete.RooDatabase.from_project(this);
73                 }
74                 
75                 
76                 
77                 public static void loadAll(bool force = false)
78                 {
79                         if (projects_loaded && !force) {
80                                 return;
81                         }
82
83                         var dirname = GLib.Environment.get_home_dir() + "/.Builder";
84                         var dir = File.new_for_path(dirname);
85                                 if (!dir.query_exists()) {
86                                 dir.make_directory();
87                                 return;
88                         }
89                         projects = new  Gee.HashMap<string,Project>();
90                           
91                    
92                         try {
93                                 var file_enum = dir.enumerate_children(
94                                                                 GLib.FileAttribute.STANDARD_DISPLAY_NAME, 
95                                         GLib.FileQueryInfoFlags.NONE, 
96                                         null
97                                 );
98                                 
99                                  
100                                 FileInfo next_file; 
101                                 while ((next_file = file_enum.next_file(null)) != null) {
102                                                 var fn = next_file.get_display_name();
103                                         if (!Regex.match_simple("\\.json$", fn)) {
104                                                 continue;
105                                         }
106                                         factoryFromFile(dirname + "/" + fn);
107                                 }       
108                         } catch(Error e) {
109                                 GLib.warning("oops - something went wrong scanning the projects\n");
110                         }
111                         
112
113                 }
114
115                 public static Gee.ArrayList<Project> allProjectsByName()
116                 {
117                         var ret = new Gee.ArrayList<Project>();
118                         var iter = projects.map_iterator();
119                                 while (iter.next()) {
120                                         ret.add(iter.get_value());
121                                 }
122                         // fixme -- sort...
123                         return ret;
124                 
125                 }
126                 
127                 public static Project getProject(string name)
128                 {
129                         
130                         var iter = projects.map_iterator();
131                         while (iter.next()) {
132                                 if (iter.get_value().name == name) {
133                                         return iter.get_value();
134                                 }
135                                 
136                         }
137                         
138                         return null;
139                 
140                 }
141                 
142                 
143                 // load project data from project file.
144                 public static void   factoryFromFile(string jsonfile)
145                 {
146                          
147                         GLib.debug("parse %s\n", jsonfile);
148
149                         var pa = new Json.Parser();
150                         pa.load_from_file(jsonfile);
151                         var node = pa.get_root();
152
153                         
154                         if (node == null || node.get_node_type () != Json.NodeType.OBJECT) {
155                                 GLib.debug("SKIP " + jsonfile + " - invalid format?\n");
156                                 return;
157                         }
158                         
159                         var obj = node.get_object ();
160                         var xtype =  obj.get_string_member("xtype");
161
162
163                         var paths = obj.get_object_member("paths");
164                         var i = 0;
165                         var fpath = "";
166                         paths.foreach_member((sobj, key, val) => {
167                                 if (i ==0 ) {
168                                         fpath = key;
169                                 }
170                                         
171                         });
172
173                         
174                         var proj = factory(xtype, fpath);
175
176                         proj.json_project_data  = obj; // store the original object...
177                         
178                         proj.fn =  Path.get_basename(jsonfile).split(".")[0];
179
180                         // might not exist?
181
182                         if (obj.has_member("runhtml")) {
183                                         proj.runhtml  = obj.get_string_member("runhtml"); 
184                         }
185                         // might not exist?
186                         if (obj.has_member("base_template")) {
187                                         proj.base_template  = obj.get_string_member("base_template"); 
188                         }
189                         // might not exist?
190                         if (obj.has_member("rootURL")) {
191                                         proj.rootURL  = obj.get_string_member("rootURL"); 
192                         }
193                         
194                         proj.name = obj.get_string_member("name");
195
196                          
197                         paths.foreach_member((sobj, key, val) => {
198                                 proj.paths.set(key, "dir");
199                         });
200                         proj.initRooDatabase();
201                         
202                         GLib.debug("Add Project %s", proj.id);
203                         
204                         projects.set(proj.id,proj);
205                         
206                         
207                         
208                         
209                 }
210                 
211                 
212                 public static Project factory(string xtype, string path)
213                 {
214
215                         // check to see if it's already loaded..
216
217                          
218                         var iter = projects.map_iterator();
219                         while (iter.next()) {
220                                 if (iter.get_value().hasPath( path)) {
221                                         return iter.get_value();
222                                  }
223                         }
224
225
226                         switch(xtype) {
227                                 case "Gtk":
228                                         return new Gtk(path);
229                                 case "Roo":
230                                         return new Roo(path);
231                         }
232                         throw new Error.INVALID_TYPE("invalid project type");
233                                 
234                 }
235                 
236                 
237                 
238                  public static void  remove(Project project)
239                 {
240                         // delete the file..
241                         var dirname = GLib.Environment.get_home_dir() + "/.Builder";
242                                  
243                         FileUtils.unlink(dirname + "/" + project.fn + ".json");
244                         projects.unset(project.id,null);
245                         
246
247                 }
248                  
249
250                 public void save()
251                 {
252                                 // fixme..
253                         
254                         if (this.fn.length < 1) {
255                                 // make the filename..
256                                 //var t = new DateTime.now_local ();
257                                 //TimeVal tv;
258                                 //t.to_timeval(out tv);
259                                 //var str = "%l:%l".printf(tv.tv_sec,tv.tv_usec);
260                                 var str = this.firstPath();
261                                 
262                                         this.fn = GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str, str.length);
263                         }
264
265                         var dirname = GLib.Environment.get_home_dir() + "/.Builder";
266                         var  s =  this.toJSON(false);
267                         FileUtils.set_contents(dirname + "/" + this.fn + ".json", s, s.length);  
268                         
269                         
270                 }
271
272                 
273                 
274                 public string toJSON(bool show_all)
275                 {
276                         
277                         
278                         this.json_project_data.set_string_member("name", this.name);
279                         this.json_project_data.set_string_member("fn", this.fn);
280                         this.json_project_data.set_string_member("xtype", this.xtype);
281                         this.json_project_data.set_string_member("runhtml", this.runhtml);
282                         this.json_project_data.set_string_member("rootURL", this.rootURL);
283                         this.json_project_data.set_string_member("base_template", this.base_template);
284                         this.json_project_data.set_string_member("rootURL", this.rootURL);
285  
286                         var paths = new Json.Object(); 
287
288
289                         var iter = this.paths.map_iterator();
290                         while (iter.next()) {
291                                 paths.set_string_member(iter.get_key(), "path");
292                         }
293                         this.json_project_data.set_object_member("paths", paths);
294
295                         
296                         if (show_all) {
297                                 var files = new Json.Array();
298                                 
299                                 
300                                 var fiter = this.files.map_iterator();
301                                 while (fiter.next()) {
302                                         files.add_string_element (fiter.get_key());
303                                 }
304                                 this.json_project_data.set_array_member("files", files);
305                                 
306                         }
307
308                 
309                         var  generator = new Json.Generator ();
310                         var  root = new Json.Node(Json.NodeType.OBJECT);
311                         root.init_object(this.json_project_data);
312                         generator.set_root (root);
313                         if (show_all) {
314                                 generator.pretty = true;
315                                 generator.indent = 4;
316                         }
317
318                         return  generator.to_data (null);
319                           
320                           
321                 }
322                 public string firstPath()
323                 {
324                         var iter = this.paths.map_iterator();
325                         while (iter.next()) {
326                                 return iter.get_key();
327                         }
328                   
329                         return "";
330                 }
331
332                 public bool hasPath(string path)
333                 {
334                         var iter = this.paths.map_iterator();
335                         while (iter.next()) {
336                                 if (iter.get_key() == path) {
337                                 return true;
338                         }
339                         }
340                   
341                         return false;
342                 }
343
344                 
345                 // returns the first path
346                 public string getName()
347                 {
348                         var iter = this.paths.map_iterator();
349                         while (iter.next()) {
350                                 return GLib.Path.get_basename(iter.get_key());
351                         }
352                   
353                         return "";
354                 }
355
356                 public Gee.ArrayList<JsRender.JsRender> sortedFiles()
357                 {
358                         var files = new Gee.ArrayList<JsRender.JsRender>();
359
360                         var fiter = this.files.map_iterator();
361                         while(fiter.next()) {
362                                 files.add(fiter.get_value());
363                         }
364                                 files.sort((fa,fb) => {
365                                 return ((JsRender.JsRender)fa).name.collate(((JsRender.JsRender)fb).name);
366
367                         });
368                         return files;
369
370                 }
371                 
372          
373                 public JsRender.JsRender? getByName(string name)
374                 {
375                         
376                         var fiter = files.map_iterator();
377                         while(fiter.next()) {
378                          
379                                 var f = fiter.get_value();
380                                 
381                                 
382                                 GLib.debug ("Project.getByName: %s ?= %s\n" ,f.name , name);
383                                 if (f.name == name) {
384                                         return f;
385                                 }
386                         };
387                         return null;
388                 }
389                 
390                 public JsRender.JsRender? getById(string id)
391                 {
392                         
393                         var fiter = files.map_iterator();
394                         while(fiter.next()) {
395                          
396                                 var f = fiter.get_value();
397                                 
398                                 
399                                 //console.log(f.id + '?=' + id);
400                                 if (f.id == id) {
401                                         return f;
402                                 }
403                                 };
404                         return null;
405                 }
406
407                 public JsRender.JsRender newFile (string name)
408                 {
409                         var ret =  JsRender.JsRender.factory(this.xtype, 
410                                                                                          this, 
411                                                                                          this.firstPath() + "/" + name + ".bjs");
412                         this.addFile(ret);
413                         return ret;
414                 }
415                 
416                 public JsRender.JsRender loadFileOnly (string path)
417                 {
418                         var xt = this.xtype;
419                         return JsRender.JsRender.factory(xt, this, path);
420                         
421                 }
422                 
423                 public JsRender.JsRender create(string filename)
424                 {
425                         var ret = this.loadFileOnly(filename);
426                         ret.save();
427                         this.addFile(ret);
428                         return ret;
429                         
430                 }
431                         
432                          
433                 public void addFile(JsRender.JsRender pfile) { // add a single file, and trigger changed.
434                 
435                 
436                         this.files.set(pfile.path, pfile); // duplicate check?
437                         this.on_changed();
438                 }
439                 
440                 public void add(string path, string type)
441                 {
442                         this.paths.set(path,type);
443                         //Seed.print(" type is '" + type + "'");
444                         if (type == "dir") {
445                                 this.scanDir(path);
446                         //    console.dump(this.files);
447                         }
448                         if (type == "file" ) {
449                         
450                                 this.files.set(path,this.loadFileOnly( path ));
451                         }
452                         this.on_changed();
453                         
454                 }
455                 public void  scanDirs() // cached version
456                 {
457                         if (this.is_scanned) {
458                                 return;
459                         }
460                         this.scanDirsForce();
461                         //console.dump(this.files);
462                         
463                 }
464                 
465                 public void  scanDirsForce()
466                 {
467                         this.is_scanned = true;  
468                         var iter = this.paths.map_iterator();
469                         while (iter.next()) {
470                                 //print("path: " + iter.get_key() + " : " + iter.get_value() +"\n");
471                                 if (iter.get_value() != "dir") {
472                                         continue;
473                                 }
474                                 this.scanDir(iter.get_key());
475                         }
476                         //console.dump(this.files);
477                         
478                 }
479                         // list files.
480                 public void scanDir(string dir, int dp =0 ) 
481                 {
482                         //dp = dp || 0;
483                         //print("Project.Base: Running scandir on " + dir +"\n");
484                         if (dp > 5) { // no more than 5 deep?
485                                 return;
486                         }
487                         // this should be done async -- but since we are getting the proto up ...
488                         
489                         var subs = new GLib.List<string>();;            
490                         var f = File.new_for_path(dir);
491                         try {
492                                 var file_enum = f.enumerate_children(GLib.FileAttribute.STANDARD_DISPLAY_NAME, GLib.FileQueryInfoFlags.NONE, null);
493                                 
494                                  
495                                 FileInfo next_file; 
496                                 while ((next_file = file_enum.next_file(null)) != null) {
497                                         var fn = next_file.get_display_name();
498                         
499                                          
500                                         //print("trying"  + dir + "/" + fn +"\n");
501                                         
502                                         if (fn[0] == '.') { // skip hidden
503                                                 continue;
504                                         }
505                                         
506                                         if (FileUtils.test(dir  + "/" + fn, GLib.FileTest.IS_DIR)) {
507                                                 subs.append(dir  + "/" + fn);
508                                                 continue;
509                                         }
510                                         
511                                         if (!Regex.match_simple("\\.bjs$", fn)) {
512                                                 //print("no a bjs\n");
513                                                 continue;
514                                         }
515                                         /*
516                                         var parent = "";
517                                         //if (dp > 0 ) {
518                                         
519                                         var sp = dir.split("/");
520                                         var parent = "";
521                                         for (var i = 0; i < sp.length; i++) {
522                                                 
523                                         }
524                                         
525                                         /*
526                                         sp = sp.splice(sp.length - (dp +1), (dp +1));
527                                         parent = sp.join('.');
528                                         
529                                         
530                                         if (typeof(_this.files[dir  + '/' + fn]) != 'undefined') {
531                                                 // we already have it..
532                                                 _this.files[dir  + '/' + fn].parent = parent;
533                                                 return;
534                                         }
535                                         */
536                                         var xt = this.xtype;
537                                         var el = JsRender.JsRender.factory(xt,this, dir + "/" + fn);
538                                         this.files.set( dir + "/" + fn, el);
539                                         // parent ?? 
540                                         
541                                          
542                                 }
543                         } catch (Error e) {
544                                 GLib.warning("Project::scanDirs failed : " + e.message + "\n");
545                         } catch (GLib.Error e) {
546                                 GLib.warning("Project::scanDirs failed : " + e.message + "\n");
547                         }
548                         for (var i = 0; i < subs.length(); i++) {
549                                 
550                                  this.scanDir(subs.nth_data(i), dp+1);
551                         }
552                         
553                 }
554                 // wrapper around the javascript data...
555                 public string get_string_member(string key) {
556                         
557                         if (!this.json_project_data.has_member(key)) {
558                                 return "";
559                         }
560                         var  ret = this.json_project_data.get_string_member(key);
561                         if (ret == null) {
562                                 return "";
563                         }
564                         return ret;
565                         
566                 }
567                   
568         }
569 }
570