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