XObject.js
[app.Builder.js] / XObject.js
1 //<script type="text/javascript">
2 GIRepository = imports.gi.GIRepository;
3 GObject = imports.gi.GObject;
4 /**
5  * XObject
6  * Yet another attempt to create a usable object construction library for seed..
7  * 
8  * Why is this useful?
9  * A) It turns rather messy code into a tree structure, making it easy to find code relating to 
10  *    an interface element
11  * B) In theory it should be gjs/Seed compatible..
12  * C) It provides getElementById style lookups for elements.
13  * D) It provides classic OO constructors for Javascript (extend/define)
14  * E) It does not modify any buildin prototypes.. 
15  *
16  * Extend this.. to use it's wonderful features..
17  * 
18  * normal usage:
19  * XObject = imports.XObject.XObject;
20  * 
21  * Xyz = new XObject({
22  *     xtype: Gtk.Window,
23  *     id : 'window',
24  *     items : [
25  *     
26  *     ]
27  *  });
28  *  Xyz.init(); // create and show.
29  * 
30  * 
31  * use XObject.debug = 1 to turn on debugging
32  * 
33  * If XObject/[xns]/[xtype].js exists, it will use this to override properties..
34  * 
35  * 
36  * He's some questions.
37  * - should we have a special property to use as the constructor / gobject.properties rather
38  *   than sending all basic types to this?
39  * 
40  * @cfg xtype {String|Function} constructor or string.
41  * @cfg id {String}  (optional) id for registry
42  * @cfg xns {String|Object}   (optional) namespace eg. Gtk or 'Gtk' - used with xtype.
43  * @cfg items {Array}   (optional) list of child elements which will be constructed.. using XObject
44  * @cfg listeners {Object}   (optional) map Gobject signals to functions
45  * @cfg pack {Function|String|Array}   (optional) how this object gets added to it's parent
46  * @cfg el {Object}   (optional) premade GObject
47  * 
48  * 
49  * 
50  * 
51  * 
52  * 
53  */
54
55 function XObject (cfg) {
56     // first apply cfg if set.
57       //print("new XOBJECT!!!");
58       
59     //print ("XObject ctr");
60       
61     this.config = {};
62     this.constructor = XObject;
63     
64     
65     
66     // start by seeing if we have a base class....
67     try {
68         // loocks for XObject/Gtk/TreeView.js [   TreeView = { .... } ]
69         // xns is not a string!!!?
70         var gname = false;
71         if (typeof(cfg.xtype) == 'object') {
72             gname = GObject.type_name(cfg.xtype.type);
73            // print("GNAME:" +gname + " GTYPE:"+cfg.xtype.type);
74         }
75         
76         var base = gname  ? imports.XObjectBase[gname][gname] : false;
77         if (base) {
78           //  print("Overlaying XOBJBECT-BASE."  + cfg.xtype);
79             XObject.extend(this,base);
80         }
81         
82     } catch (e) {
83         // if debug?
84         XObject.log("error finding " + gname + " - " + e.toString());
85     }
86     
87     
88     // copy down all elements into self..
89     
90     for (var i in cfg) {
91         this[i] = cfg[i];
92         if (typeof(cfg[i]) == 'function') { // do we skip objects.
93             continue;
94         }
95         // these properties are not copied to cfg.
96         if (    i == 'pack' ||
97                 i == 'items' ||
98                 i == 'id' ||
99                 i == 'xtype' ||
100                 i == 'xdebug' ||
101                 i == 'xns') {
102             continue;
103         }
104         
105         
106         this.config[i] = cfg[i];
107     }
108     
109     
110     this.items = this.items || [];
111     
112     
113     // pack can be false!
114     if (typeof(this.pack) == 'undefined') {
115         
116         this.pack = [ 'add' ]
117         /*
118         var Gtk  = imports.gi.Gtk;
119         switch (true) {
120             // any others!!
121             case (this.xtype == Gtk.MenuItem):  this.pack = [ 'append' ]; break;
122             
123         }
124         */
125         
126     }
127     
128     // interesting question should we call constructor on items here...
129     // as the real work is done in init anyway..
130     var _this= this;
131     
132     var items = [];
133     this.items.forEach(function(i) {
134         items.push(i);
135     });
136     this.items = [];
137     // create XObject for all the children.
138     items.forEach(function(i,n) {
139          
140         var item = (i.constructor == XObject) ? o : new XObject(i);
141         item.parent = _this;
142         _this.items.push(item);
143         //_this.addItem(i);
144     });
145     if (this.onConstruct) {
146         this.onConstruct.call(this);
147     }
148     
149 }
150
151
152
153 XObject.prototype = {
154     /**
155      * @property el {GObject} the Gtk / etc. element.
156      */
157     el : false, 
158     /*
159      * @property items {Array} list of sub elements
160      */
161     /**
162      * @property parent {XObject} parent Element
163      */
164      
165      /**
166      * @property config {Object} the construction configuration.
167      */
168      /**
169       * @method init
170       * Initializes the Element (el) hooks up all the listeners
171       * and packs the children.
172       * you can override this, in child objects, then 
173       * do this to do thi initaliztion.
174       * 
175       * XObject.prototype.init.call(this); 
176       * 
177       */ 
178     init : function()
179     {
180          
181        // var items = [];
182         //this.items.forEach(function(i) {
183         //    items.push(i);
184         //});
185         // remove items.
186         this.listeners = this.listeners || {}; 
187         //this.items = [];
188          
189         // do we need to call 'beforeInit here?'
190          
191         // handle include?
192         //if ((this.xtype == 'Include')) {
193         //    o = this.pre_registry[cls];
194         //}
195         var isSeed = typeof(Seed) != 'undefined';
196          
197         // xtype= Gtk.Menu ?? what about c_new stuff?
198         XObject.log("init: ID:"+ this.id +" typeof(xtype): "  + typeof(this.xtype));
199         if (!this.el && typeof(this.xtype) == 'function') {
200             XObject.log("func?"  + XObject.keys(this.config).join(','));
201             this.el = this.xtype(this.config);
202            
203         }
204         if (!this.el && typeof(this.xtype) == 'object') {
205             XObject.log("obj?"  + XObject.keys(this.config).join(','));
206             this.el = new (this.xtype)(this.config);
207       
208         }
209         //print(this.el);
210         if (!this.el && this.xns) {
211             
212             var NS = imports.gi[this.xns];
213             if (!NS) {
214                 XObject.error('Invalid xns: ' + this.xns, true);
215             }
216             constructor = NS[this.xtype];
217             if (!constructor) {
218                 XObject.error('Invalid xtype: ' + this.xns + '.' + this.xtype);
219             }
220             this.el  =   isSeed ? new constructor(this.config) : new constructor();
221             
222         }
223         XObject.log("init: ID:"+ this.id +" typeof(el):" + this.el);
224         
225         // always overlay props..
226         // check for 'write' on object..
227         /*
228         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
229                 
230             var gi = GIRepository.IRepository.get_default();
231             var ty = gi.find_by_gtype(this.xtype.type);
232             var write = [];
233             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
234                 var p =   GIRepository.object_info_get_property(ty,i);
235                 if (GIRepository.property_info_get_flags(p) & 2) {
236                     write.push(GIRepository.base_info_get_name(p));
237                 }
238             }
239             XObject.writeablePropsCache[this.xtype.type] = write;
240             print(write.join(", "));
241         }
242         
243         */
244         
245          
246         for (var i in this.config) {
247             if (i == 'type') { // problem with Gtk.Window... - not decided on a better way to handle this.
248                 continue;
249             }
250             if (i == 'buttons') { // problem with Gtk.MessageDialog..
251                 continue;
252             }
253             if (i[0] == '.') { // parent? - 
254                 continue;
255             }
256             this.el[i] = this.config[i];
257         }
258         
259         // register it!
260         //if (o.xnsid  && o.id) {
261          //   XObject.registry = XObject.registry || { };
262          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
263          //   XObject.registry[o.xnsid][o.id] = this;
264         //}
265         
266         var type = this.xtype.type ? GObject.type_name(this.xtype.type) : '';
267         XObject.log("add children to " + type);
268         
269         var _this=this;
270         this.items.forEach(function(i,n) {
271             _this.addItem(i,n);
272         })
273             
274         
275         for (var i in this.listeners) {
276             this.addListener(i, this.listeners[i]);
277         }
278         
279         this.init = XObject.emptyFn;
280            
281         // delete this.listeners ?
282         // do again so child props work!
283        
284         // do we need to call 'init here?'
285     },
286       
287      
288      /**
289       * @method addItem
290       * Adds an item to the object using a new XObject
291       * uses pack property to determine how to add it.
292       * @arg cfg {Object} same as XObject constructor.
293       */
294     addItem : function(item, pos) 
295     {
296         
297         if (typeof(item) == 'undefined') {
298             XObject.error("Invalid Item added to this!");
299             imports.console.dump(this);
300             Seed.quit();
301         }
302         // what about extended items!?!?!?
303        
304         item.init();
305         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
306        // print("addItem - call init [" + item.pack.join(',') + ']');
307         if (!item.el) {
308             XObject.err("NO EL!");
309             imports.console.dump(item);
310             Seed.quit();
311         }
312          
313         
314         if (item.pack===false) {  // no packing.. various items have this ..
315             return;
316         }
317         
318         if (typeof(item.pack) == 'function') { // pack is a function..
319             // parent, child
320             item.pack.apply(item, [ this , item  ]);
321             item.parent = this;
322             return;
323         }
324         
325         // pack =  'add,x,y'
326         var args = [];
327         var pack_m  = false;
328         if (typeof(item.pack) == 'string') {
329              
330             item.pack.split(',').forEach(function(e, i) {
331                 
332                 if (e == 'false') { args.push( false); return; }
333                 if (e == 'true') {  args.push( true);  return; }
334                 if (!isNaN(parseInt(e))) { args.push( parseInt(e)); return; }
335                 args.push(e);
336             });
337             //print(args.join(","));
338             
339             pack_m = args.shift();
340         } else {
341             pack_m = item.pack.shift();
342             args = item.pack;
343         }
344         
345         // handle error.
346         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
347             
348             throw {
349                 name: "ArgumentError", 
350                 message : 'pack method not available : ' + this.id + " : " + this.xtype + '.' +  pack_m + " ADDING " + item.el
351                     
352             }
353            
354             return;
355         }
356         
357         
358         // finally call the pack method 
359         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
360         
361         args.unshift(item.el);
362         
363          
364         
365         
366         
367         XObject.log(pack_m + '[' + args.join(',') +']');
368         //Seed.print('args: ' + args.length);
369         if (pack_m) {
370             this.el[pack_m].apply(this.el, args);
371         }
372         
373        
374         
375     },
376     /**
377       * @method addListener
378       * Connects a method to a signal. (gjs/Seed aware)
379       * 
380       * @arg sig  {String} name of signal
381       * @arg fn  {Function} handler.
382       */
383     addListener  : function(sig, fn) 
384     {
385  
386         XObject.log("Add signal " + sig);
387         fn.id= sig;
388         var _li = XObject.createDelegate(fn,this);
389         // private listeners that are not copied to GTk.
390         
391         if (typeof(Seed) != 'undefined') {
392           //   Seed.print(typeof(_li));
393             this.el.signal[sig].connect(_li);
394         } else {
395             this.el.connect( sig, _li);
396         }
397              
398         
399     },
400      /**
401       * @method get
402       * Finds an object in the child elements using xid of object.
403       * prefix with '.' to look up the tree.. 
404       * prefix with multiple '..' to look further up..
405       * prefix with '/' to look from the top, eg. '^LeftTree.model'
406       * 
407       * @arg name  {String} name of signal
408       * @return   {XObject|false} the object if found.
409       */
410     get : function(xid)
411     {
412         XObject.log("SEARCH FOR " + xid + " in " + this.id);
413         var ret=  false;
414         var oid = '' + xid;
415         if (!xid.length) {
416             throw {
417                 name: "ArgumentError", 
418                 message : "ID not found : empty id"
419             }
420         }
421         
422         if (xid[0] == '.') {
423             return this.parent.get(xid.substring(1));
424         }
425         if (xid[0] == '/') {
426             
427             if (typeof(XObject.cache[xid]) != 'undefined') {
428                 return XObject.cache[xid]; 
429             }
430             if (xid.indexOf('.') > -1) {
431                 
432                 var child = xid.split('.');
433                 var nxid = child.shift();
434                     
435                 child = child.join('.');
436                 if (typeof(XObject.cache[nxid]) != 'undefined') {
437                     return XObject.cache[nxid].get(child);
438                 }
439                 
440                 
441             }
442             var e = this;
443             while (e.parent) {
444                 e = e.parent;
445             }
446             
447             try {
448                 ret = e.get(xid.substring(1));
449             } catch (ex) { }
450             
451             if (!ret) {
452                 throw {
453                     name: "ArgumentError", 
454                     message : "ID not found : " + oid
455                 }
456             }
457             XObject.cache[xid] = ret;
458             return XObject.cache[xid];
459         }
460         var child = false;
461         
462         if (xid.indexOf('.') > -1) {
463             child = xid.split('.');
464             xid = child.shift();
465             
466             child = child.join('.');
467             
468         }
469         if (xid == this.id) {
470             try {
471                 return child === false ? this : this.get(child);
472             } catch (ex) {
473                 throw {
474                     name: "ArgumentError", 
475                     message : "ID not found : " + oid
476                 }
477             }
478             
479         }
480         
481         
482         this.items.forEach(function(ch) {
483             if (ret) {
484                 return;
485             }
486             if (ch.id == xid) {
487                 ret = ch;
488             }
489         })
490         if (ret) {
491             try {
492                 return child === false ? ret : ret.get(child);
493             } catch (ex) {
494                 throw {
495                     name: "ArgumentError", 
496                     message : "ID not found : " + oid
497                 }
498             }
499             
500         }
501         // iterate children.
502         var _this = this;
503         this.items.forEach(function(ch) {
504             if (ret) {
505                 return;
506             }
507             if (!ch.get) {
508                 XObject.error("invalid item...");
509                 imports.console.dump(_this);
510                 Seed.quit();
511             }
512             try {
513                 ret = ch.get(xid);
514             } catch (ex) { }
515             
516             
517         });
518         if (!ret) {
519             throw {
520                 name: "ArgumentError", 
521                 message : "ID not found : " + oid
522             }
523         }
524         try {
525             return child === false ? ret : ret.get(child);
526         } catch (ex) {
527             throw {
528                 name: "ArgumentError", 
529                 message : "ID not found : " + oid
530             }
531         }
532     }
533       
534       
535
536          
537      
538 /**
539  * Copies all the properties of config to obj.
540  *
541  * Pretty much the same as JQuery/Prototype.. or Roo.apply
542  * @param {Object} obj The receiver of the properties
543  * @param {Object} config The source of the properties
544  * @param {Object} defaults A different object that will also be applied for default values
545  * @return {Object} returns obj
546  * @member XObject extend
547  */
548
549
550 XObject.extend = function(o, c, defaults){
551     if(defaults){
552         // no "this" reference for friendly out of scope calls
553         XObject.extend(o, defaults);
554     }
555     if(o && c && typeof c == 'object'){
556         for(var p in c){
557             o[p] = c[p];
558         }
559     }
560     return o;
561 };
562
563 XObject.extend(XObject,
564 {
565      
566     /**
567      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
568      * 
569      */
570     debug : false,
571     /**
572      * @property {Object} cache - cache of object ids
573      * 
574      */
575     cache: { },
576     /**
577      * Empty function
578      * 
579      */
580     emptyFn : function () { },
581       
582       
583       
584     /**
585      * Debug Logging
586      * @param {String|Object} output String to print.
587      */
588     log : function(output)
589     {
590         if (!this.debug) {
591             return;
592         }
593         print("LOG:" + output);  
594     },
595      
596     /**
597      * Error Logging
598      * @param {String|Object} output String to print.
599      */
600     error : function(output)
601     {
602         print("ERROR: " + output);  
603     },
604      
605    
606     /**
607      * Copies all the properties of config to obj, if the do not exist.
608      * @param {Object} obj The receiver of the properties
609      * @param {Object} config The source of the properties
610      * @return {Object} returns obj
611      * @member Object extendIf
612      */
613
614
615     extendIf : function(o, c)
616     {
617
618         if(!o || !c || typeof c != 'object'){
619             return o;
620         }
621         for(var p in c){
622             if (typeof(o[p]) != 'undefined') {
623                 continue;
624             }
625             o[p] = c[p];
626         }
627         return o;
628     },
629
630  
631
632     /**
633      * Extends one class with another class and optionally overrides members with the passed literal. This class
634      * also adds the function "override()" to the class that can be used to override
635      * members on an instance.
636      *
637      * usage:
638      * MyObject = Object.define(
639      *     function(...) {
640      *          ....
641      *     },
642      *     parentClass, // or Object
643      *     {
644      *        ... methods and properties.
645      *     }
646      * });
647      * @param {Function} constructor The class inheriting the functionality
648      * @param {Object} superclass The class being extended
649      * @param {Object} overrides (optional) A literal with members
650      * @return {Function} constructor (eg. class
651      * @method define
652      */
653     define : function()
654     {
655         // inline overrides
656         var io = function(o){
657             for(var m in o){
658                 this[m] = o[m];
659             }
660         };
661         return function(constructor, parentClass, overrides) {
662             if (typeof(parentClass) == 'undefined') {
663                 XObject.error("XObject.define: Missing parentClass: when applying: " );
664                 XObject.error(new String(constructor));
665                 Seed.quit(); 
666             }
667             if (typeof(parentClass.prototype) == 'undefined') {
668                 XObject.error("Missing protype: when applying: " );
669                 XObject.error(new String(constructor));
670                 XObject.error(new String(parentClass));
671                 Seed.quit(); 
672             }
673             var F = function(){};
674             var sbp;
675             var spp = parentClass.prototype;
676             
677             F.prototype = spp;
678             sbp = constructor.prototype = new F();
679             sbp.constructor=constructor;
680             constructor.superclass=spp;
681
682             // extends Object.
683             if(spp.constructor == Object.prototype.constructor){
684                 spp.constructor=parentClass;
685             }
686             
687             constructor.override = function(o){
688                 Object.extend(constructor.prototype, o);
689             };
690             sbp.override = io;
691             XObject.extend(constructor.prototype, overrides);
692             return constructor;
693         };
694     }(),
695
696          
697     /**
698      * returns a list of keys of the object.
699      * @param {Object} obj object to inspect
700      * @return {Array} returns list of kyes
701      * @member XObject keys
702      */
703     keys : function(o)
704     {
705         var ret = [];
706         for(var i in o) {
707             ret.push(i);
708         }
709         return ret;
710     },
711       
712     /**
713      * @member XObject createDelegate
714      * creates a delage metdhod
715      * @param {Function} method to wrap
716      * @param {Object} scope 
717      * @param {Array} args to add
718      * @param {Boolean|Number} append arguments or replace after N arguments.
719      * @return {Function} returns the delegate
720      */
721
722     createDelegate : function(method, obj, args, appendArgs){
723         
724         return function() {
725             XObject.log("CALL: " + obj.id + ':'+ method.id);
726             
727             var callArgs = args || arguments;
728             if(appendArgs === true){
729                 callArgs = Array.prototype.slice.call(arguments, 0);
730                 callArgs = callArgs.concat(args);
731             }else if(typeof appendArgs == "number"){
732                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
733                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
734                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
735                 }
736                 return method.apply(obj || window, callArgs);
737             };
738     }
739     
740 });