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                                 print("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                         print("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                                 print("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                         projects.set(proj.id,proj);
203                         
204                         
205                         
206                         
207                 }
208                 
209                 
210                 public static Project factory(string xtype, string path)
211                 {
212
213                         // check to see if it's already loaded..
214
215                          
216                         var iter = projects.map_iterator();
217                         while (iter.next()) {
218                                 if (iter.get_value().hasPath( path)) {
219                                         return iter.get_value();
220                                  }
221                         }
222
223
224                         switch(xtype) {
225                                 case "Gtk":
226                                         return new Gtk(path);
227                                 case "Roo":
228                                         return new Roo(path);
229                         }
230                         throw new Error.INVALID_TYPE("invalid project type");
231                                 
232                 }
233                 
234                 
235                 
236                  public static void  remove(Project project)
237                 {
238                         // delete the file..
239                         var dirname = GLib.Environment.get_home_dir() + "/.Builder";
240                          
241                         FileUtils.unlink(dirname + "/" + project.fn + ".json");
242                         projects.unset(project.id,null);
243                         
244
245                 }
246                  
247
248                 public void save()
249                 {
250                                 // fixme..
251             
252                         if (this.fn.length < 1) {
253                                 // make the filename..
254                                 //var t = new DateTime.now_local ();
255                                 //TimeVal tv;
256                                 //t.to_timeval(out tv);
257                                 //var str = "%l:%l".printf(tv.tv_sec,tv.tv_usec);
258                                 var str = this.firstPath();
259                                 
260                                 this.fn = GLib.Checksum.compute_for_string(GLib.ChecksumType.MD5, str, str.length);
261                         }
262
263                         var dirname = GLib.Environment.get_home_dir() + "/.Builder";
264                         var  s =  this.toJSON(false);
265                         FileUtils.set_contents(dirname + "/" + this.fn + ".json", s, s.length);  
266                         
267                         
268                 }
269
270                 
271                 
272                 public string toJSON(bool show_all)
273                 {
274                     
275                         
276                         this.json_project_data.set_string_member("name", this.name);
277                         this.json_project_data.set_string_member("fn", this.fn);
278                         this.json_project_data.set_string_member("xtype", this.xtype);
279                         this.json_project_data.set_string_member("runhtml", this.runhtml);
280                         this.json_project_data.set_string_member("rootURL", this.rootURL);
281                         this.json_project_data.set_string_member("base_template", this.base_template);
282                         this.json_project_data.set_string_member("rootURL", this.rootURL);
283  
284                         var paths = new Json.Object(); 
285
286
287                         var iter = this.paths.map_iterator();
288                         while (iter.next()) {
289                                 paths.set_string_member(iter.get_key(), "path");
290                         }
291                         this.json_project_data.set_object_member("paths", paths);
292
293                         
294                         if (show_all) {
295                                 var files = new Json.Array();
296                                 
297                                 
298                                 var fiter = this.files.map_iterator();
299                                 while (fiter.next()) {
300                                     files.add_string_element (fiter.get_key());
301                                 }
302                                 this.json_project_data.set_array_member("files", files);
303                                 
304                         }
305
306                 
307                         var  generator = new Json.Generator ();
308                         var  root = new Json.Node(Json.NodeType.OBJECT);
309                         root.init_object(this.json_project_data);
310                         generator.set_root (root);
311                         if (show_all) {
312                                 generator.pretty = true;
313                                 generator.indent = 4;
314                         }
315
316                         return  generator.to_data (null);
317                           
318                       
319                 }
320                 public string firstPath()
321                 {
322                     var iter = this.paths.map_iterator();
323                     while (iter.next()) {
324                         return iter.get_key();
325                     }
326                   
327                     return "";
328                 }
329
330                 public bool hasPath(string path)
331                 {
332                     var iter = this.paths.map_iterator();
333                     while (iter.next()) {
334                         if (iter.get_key() == path) {
335                                 return true;
336                         }
337                     }
338                   
339                     return false;
340                 }
341
342                 
343                 // returns the first path
344                 public string getName()
345                 {
346                     var iter = this.paths.map_iterator();
347                     while (iter.next()) {
348                         return GLib.Path.get_basename(iter.get_key());
349                     }
350                   
351                     return "";
352                 }
353
354                 public Gee.ArrayList<JsRender.JsRender> sortedFiles()
355                 {
356                         var files = new Gee.ArrayList<JsRender.JsRender>();
357
358                         var fiter = this.files.map_iterator();
359                         while(fiter.next()) {
360                                 files.add(fiter.get_value());
361                         }
362                         files.sort((fa,fb) => {
363                                 return ((JsRender.JsRender)fa).name.collate(((JsRender.JsRender)fb).name);
364
365                         });
366                         return files;
367
368                 }
369                 
370          
371                 public JsRender.JsRender? getByName(string name)
372                 {
373                     
374                         var fiter = files.map_iterator();
375                     while(fiter.next()) {
376                      
377                         var f = fiter.get_value();
378                         
379                         
380                         print ("Project.getByName: %s ?= %s\n" ,f.name , name);
381                         if (f.name == name) {
382                             return f;
383                         }
384                     };
385                     return null;
386                 }
387                 
388                 public JsRender.JsRender? getById(string id)
389                 {
390                     
391                         var fiter = files.map_iterator();
392                         while(fiter.next()) {
393                      
394                                 var f = fiter.get_value();
395                                 
396                                 
397                                 //console.log(f.id + '?=' + id);
398                                 if (f.id == id) {
399                                     return f;
400                                 }
401                             };
402                         return null;
403                 }
404
405                 public JsRender.JsRender newFile (string name)
406                 {
407                         var ret =  JsRender.JsRender.factory(this.xtype, 
408                                                          this, 
409                                                          this.firstPath() + "/" + name + ".bjs");
410                         this.addFile(ret);
411                         return ret;
412                 }
413                 
414                 public JsRender.JsRender loadFileOnly (string path)
415                 {
416                     var xt = this.xtype;
417                     return JsRender.JsRender.factory(xt, this, path);
418                     
419                 }
420                 
421                 public JsRender.JsRender create(string filename)
422                 {
423                     var ret = this.loadFileOnly(filename);
424                     ret.save();
425                     this.addFile(ret);
426                     return ret;
427                     
428                 }
429                     
430                      
431                 public void addFile(JsRender.JsRender pfile) { // add a single file, and trigger changed.
432                 
433                 
434                     this.files.set(pfile.path, pfile); // duplicate check?
435                     this.on_changed();
436                 }
437                 
438                 public void add(string path, string type)
439                 {
440                     this.paths.set(path,type);
441                     //Seed.print(" type is '" + type + "'");
442                     if (type == "dir") {
443                         this.scanDir(path);
444                     //    console.dump(this.files);
445                     }
446                     if (type == "file" ) {
447                         
448                         this.files.set(path,this.loadFileOnly( path ));
449                     }
450                     this.on_changed();
451                     
452                 }
453                 public void  scanDirs() // cached version
454                 {
455                     if (this.is_scanned) {
456                                 return;
457                         }
458                         this.scanDirsForce();
459                     //console.dump(this.files);
460                     
461                 }
462                 
463                 public void  scanDirsForce()
464                 {
465                         this.is_scanned = true;  
466                         var iter = this.paths.map_iterator();
467                     while (iter.next()) {
468                                 //print("path: " + iter.get_key() + " : " + iter.get_value() +"\n");
469                         if (iter.get_value() != "dir") {
470                             continue;
471                         }
472                         this.scanDir(iter.get_key());
473                     }
474                     //console.dump(this.files);
475                     
476                 }
477                     // list files.
478                 public void scanDir(string dir, int dp =0 ) 
479                 {
480                     //dp = dp || 0;
481                     //print("Project.Base: Running scandir on " + dir +"\n");
482                     if (dp > 5) { // no more than 5 deep?
483                         return;
484                     }
485                     // this should be done async -- but since we are getting the proto up ...
486                     
487                     var subs = new GLib.List<string>();;            
488                     var f = File.new_for_path(dir);
489                     try {
490                         var file_enum = f.enumerate_children(GLib.FileAttribute.STANDARD_DISPLAY_NAME, GLib.FileQueryInfoFlags.NONE, null);
491                         
492                          
493                         FileInfo next_file; 
494                         while ((next_file = file_enum.next_file(null)) != null) {
495                             var fn = next_file.get_display_name();
496                     
497                              
498                             //print("trying"  + dir + "/" + fn +"\n");
499                             
500                             if (fn[0] == '.') { // skip hidden
501                                 continue;
502                             }
503                             
504                             if (FileUtils.test(dir  + "/" + fn, GLib.FileTest.IS_DIR)) {
505                                 subs.append(dir  + "/" + fn);
506                                 continue;
507                             }
508                             
509                             if (!Regex.match_simple("\\.bjs$", fn)) {
510                                                 //print("no a bjs\n");
511                                 continue;
512                             }
513                             /*
514                             var parent = "";
515                             //if (dp > 0 ) {
516                             
517                             var sp = dir.split("/");
518                             var parent = "";
519                             for (var i = 0; i < sp.length; i++) {
520                                 
521                             }
522                             
523                             /*
524                             sp = sp.splice(sp.length - (dp +1), (dp +1));
525                             parent = sp.join('.');
526                             
527                             
528                             if (typeof(_this.files[dir  + '/' + fn]) != 'undefined') {
529                                 // we already have it..
530                                 _this.files[dir  + '/' + fn].parent = parent;
531                                 return;
532                             }
533                             */
534                             var xt = this.xtype;
535                                         var el = JsRender.JsRender.factory(xt,this, dir + "/" + fn);
536                             this.files.set( dir + "/" + fn, el);
537                             // parent ?? 
538                             
539                              
540                         }
541                     } catch (Error e) {
542                         print("Project::scanDirs failed : " + e.message + "\n");
543                     } catch (GLib.Error e) {
544                                 print("Project::scanDirs failed : " + e.message + "\n");
545                         }
546                         for (var i = 0; i < subs.length(); i++) {
547                         
548                          this.scanDir(subs.nth_data(i), dp+1);
549                     }
550                     
551                 }
552                 // wrapper around the javascript data...
553                 public string get_string_member(string key) {
554                         
555                         if (!this.json_project_data.has_member(key)) {
556                                 return "";
557                         }
558                         var  ret = this.json_project_data.get_string_member(key);
559                         if (ret == null) {
560                                 return "";
561                         }
562                         return ret;
563                         
564                 }
565                   
566         }
567 }
568