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