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