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