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