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