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     this.config = cfg;
54     //print("new XOBJECT!!!");
55     if (cfg.init) {
56         this.init = cfg.init; // override!
57     }
58     this.constructor = XObject;
59     
60     
61 }
62
63
64
65 XObject.prototype = {
66     /**
67      * @property el {GObject} the Gtk / etc. element.
68      */
69     el : false, 
70     /*
71      * @property items {Array} list of sub elements
72      */
73     /**
74      * @property parent {XObject} parent Element
75      */
76      
77      /**
78      * @property config {Object} the construction configuration.
79      */
80      /**
81       * @method init
82       * Initializes the Element (el) hooks up all the listeners
83       * and packs the children.
84       * you can override this, in child objects, then 
85       * do this to do thi initaliztion.
86       * 
87       * XObject.prototype.init.call(this); 
88       * 
89       */ 
90     init : function()
91     {
92         var cfg = this.config;
93     
94         print("init:XOBJECT?"  + XObject.keys(cfg).join(','));
95         //print(cfg);
96         o =  {};
97         
98         cfg.items = cfg.items || [];
99         
100         XObject.extend(o, cfg); // copy everything into o.
101         
102         this.pack = typeof(cfg.pack) == 'undefined' ? ['add'] : cfg.pack;
103         
104         XObject.extend(this, o);
105
106         // remove items.
107         
108         this.listeners = this.listeners || {}; 
109         this.items = [];
110         
111         // remove objects/functions from o, so they can be sent to the contructor.
112         for (var i in o) {
113             if ((typeof(o[i]) == 'object') || 
114                 (typeof(o[i]) == 'function') || 
115                 i == 'pack' ||
116                 i == 'id' ||
117                 i == 'xtype' ||
118                 i == 'xdebug' ||
119                 i == 'xns'
120             ) {
121                 delete o[i];
122             }
123         }
124         
125         // do we need to call 'beforeInit here?'
126          
127         // handle include?
128         //if ((this.xtype == 'Include')) {
129         //    o = this.pre_registry[cls];
130         //}
131         var isSeed = typeof(Seed) != 'undefined';
132          
133         // xtype= Gtk.Menu ?? what about c_new stuff?
134         print("init: typeof(xtype): "  + typeof(this.xtype));
135         if (!this.el && typeof(this.xtype) == 'function') {
136             print("func?"  + XObject.keys(o).join(','));
137             this.el = this.xtype(o);
138         }
139         if (!this.el && typeof(this.xtype) == 'object') {
140             print("obj?"  + XObject.keys(o).join(','));
141             this.el = new (this.xtype)(o);
142         }
143         //print(this.el);
144         if (!this.el && o.xns) {
145             
146             var NS = imports.gi[o.xns];
147             if (!NS) {
148                 Seed.print('Invalid xns: ' + o.xns);
149             }
150             constructor = NS[o.xtype];
151             if (!constructor) {
152                 Seed.print('Invalid xtype: ' + o.xns + '.' + o.xtype);
153             }
154             this.el  =   isSeed ? new constructor(o) : new constructor();
155             
156         }
157         print("init: typeof(el):" + typeof(this.el));
158         
159         // always overlay props..
160         // check for 'write' on object..
161         /*
162         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
163                 
164             var gi = GIRepository.IRepository.get_default();
165             var ty = gi.find_by_gtype(this.xtype.type);
166             var write = [];
167             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
168                 var p =   GIRepository.object_info_get_property(ty,i);
169                 if (GIRepository.property_info_get_flags(p) & 2) {
170                     write.push(GIRepository.base_info_get_name(p));
171                 }
172             }
173             XObject.writeablePropsCache[this.xtype.type] = write;
174             print(write.join(", "));
175         }
176         
177         */
178         
179         for (var i in o) {
180             // only write to writable properties
181           //  if (XObject.writeablePropsCache[this.xtype.type].indexOf(i) < 0) {
182           //      continue;
183            // }
184             this.el[i] = o[i];
185         }
186         // register it!
187         //if (o.xnsid  && o.id) {
188          //   XObject.registry = XObject.registry || { };
189          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
190          //   XObject.registry[o.xnsid][o.id] = this;
191         //}
192         var _this=this;
193         cfg.items.forEach(function(i) {
194             _this.addItem(i);
195         })
196             
197         
198         for (var i in this.listeners) {
199             this.addListener(i, this.listeners[i]);
200         }
201         // delete this.listeners ?
202         
203         
204         // do we need to call 'init here?'
205     },
206       
207      
208      /**
209       * @method addItem
210       * Adds an item to the object using a new XObject
211       * uses pack property to determine how to add it.
212       * @arg cfg {Object} same as XObject constructor.
213       */
214     addItem : function(o) {
215         
216         
217         var item = (o.constructor == XObject) ? o : new XObject(o);
218        
219         item.init();
220         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
221        // print("addItem - call init [" + item.pack.join(',') + ']');
222         if (!item.el) {
223             print("NO EL!");
224             imports.console.dump(item);
225             Seed.quit();
226         }
227         
228         item.parent = this;
229         this.items.push(item);
230         
231         if (item.pack===false) {  // no 
232             return;
233         }
234         if (typeof(item.pack) == 'function') {
235             // parent, child
236             item.pack.apply(o, [ o , o.items[i] ]);
237             item.parent = this;
238             return;
239         }
240         var args = [];
241         var pack_m  = false;
242         if (typeof(item.pack) == 'string') {
243             pack_m = item.pack;
244         } else {
245             pack_m = item.pack.shift();
246             args = item.pack;
247         }
248         
249         // handle error.
250         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
251             Seed.print('pack method not available : ' + this.xtype + '.' +  pack_m);
252             return;
253         }
254         
255         
256         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
257
258         args.unshift(item.el);
259         print('[' + args.join(',') +']');
260         //Seed.print('args: ' + args.length);
261         if (pack_m) {
262             this.el[pack_m].apply(this.el, args);
263         }
264         
265        
266         
267     },
268     /**
269       * @method addListener
270       * Connects a method to a signal. (gjs/Seed aware)
271       * 
272       * @arg sig  {String} name of signal
273       * @arg fn  {Function} handler.
274       */
275     addListener  : function(sig, fn) 
276     {
277  
278         Seed.print("Add signal " + sig);
279  
280         var _li = XObject.createDelegate(fn,this);
281         // private listeners that are not copied to GTk.
282         
283         if (typeof(Seed) != 'undefined') {
284           //   Seed.print(typeof(_li));
285             this.el.signal[sig].connect(_li);
286         } else {
287             this.el.connect( sig, _li);
288         }
289              
290         
291     },
292      /**
293       * @method get
294       * Finds an object in the child elements using xid of object.
295       * prefix with '.' to look up the tree.. multiple '..' to look further up..
296       * 
297       * @arg name  {String} name of signal
298       * @return   {XObject|false} the object if found.
299       */
300     get : function(xid)
301     {
302         var ret=  false;
303         if (xid[0] == '.') {
304             return this.parent.get(xid.substring(1));
305         }
306         
307         
308         this.items.forEach(function(ch) {
309             if (ch.id == xid) {
310                 ret = ch;
311                 return true;
312             }
313         })
314         if (ret) {
315             return ret;
316         }
317         // iterate children.
318         this.items.forEach(function(ch) {
319             ret = ch.get(xid);
320             if (ret) {
321                 return true;
322             }
323         })
324         return ret;
325     }
326       
327       
328
329          
330
331 XObject.writeablePropsCache = { }; 
332          
333 /**
334  * Copies all the properties of config to obj.
335  *
336  * Pretty much the same as JQuery/Prototype..
337  * @param {Object} obj The receiver of the properties
338  * @param {Object} config The source of the properties
339  * @param {Object} defaults A different object that will also be applied for default values
340  * @return {Object} returns obj
341  * @member XObject extend
342  */
343
344
345 XObject.extend = function(o, c, defaults){
346     if(defaults){
347         // no "this" reference for friendly out of scope calls
348         XObject.extend(o, defaults);
349     }
350     if(o && c && typeof c == 'object'){
351         for(var p in c){
352             o[p] = c[p];
353         }
354     }
355     return o;
356 };
357
358 XObject.extend(XObject,
359 {
360     /**
361      * Copies all the properties of config to obj, if the do not exist.
362      * @param {Object} obj The receiver of the properties
363      * @param {Object} config The source of the properties
364      * @return {Object} returns obj
365      * @member Object extendIf
366      */
367
368
369     extendIf : function(o, c){
370
371         if(!o || !c || typeof c != 'object'){
372             return o;
373         }
374         for(var p in c){
375             if (typeof(o[p]) != 'undefined') {
376                 continue;
377             }
378             o[p] = c[p];
379         }
380         return o;
381     },
382
383  
384
385     /**
386      * Extends one class with another class and optionally overrides members with the passed literal. This class
387      * also adds the function "override()" to the class that can be used to override
388      * members on an instance.
389      *
390      * usage:
391      * MyObject = Object.define(
392      *     function(...) {
393      *          ....
394      *     },
395      *     parentClass, // or Object
396      *     {
397      *        ... methods and properties.
398      *     }
399      * });
400      * @param {Function} constructor The class inheriting the functionality
401      * @param {Object} superclass The class being extended
402      * @param {Object} overrides (optional) A literal with members
403      * @return {Function} constructor (eg. class
404      * @method define
405      */
406     define : function(){
407         // inline overrides
408         var io = function(o){
409             for(var m in o){
410                 this[m] = o[m];
411             }
412         };
413         return function(constructor, parentClass, overrides) {
414             if (typeof(parentClass) == 'undefined') {
415                 print("XObject.define: Missing parentClass: when applying: " );
416                 print(new String(constructor));
417                 Seed.quit(); 
418             }
419             if (typeof(parentClass.prototype) == 'undefined') {
420                 print("Missing protype: when applying: " );
421                 print(new String(constructor));
422                 print(new String(parentClass));
423                 Seed.quit(); 
424             }
425             var F = function(){};
426             var sbp;
427             var spp = parentClass.prototype;
428             
429             F.prototype = spp;
430             sbp = constructor.prototype = new F();
431             sbp.constructor=constructor;
432             constructor.superclass=spp;
433
434             // extends Object.
435             if(spp.constructor == Object.prototype.constructor){
436                 spp.constructor=parentClass;
437             }
438             
439             constructor.override = function(o){
440                 Object.extend(constructor.prototype, o);
441             };
442             sbp.override = io;
443             XObject.extend(constructor.prototype, overrides);
444             return constructor;
445         };
446     }(),
447
448          
449     /**
450      * returns a list of keys of the object.
451      * @param {Object} obj object to inspect
452      * @return {Array} returns list of kyes
453      * @member XObject keys
454      */
455     keys : function(o)
456     {
457         var ret = [];
458         for(var i in o) {
459             ret.push(i);
460         }
461         return ret;
462     },
463       
464     /**
465      * @member XObject createDelegate
466      * creates a delage metdhod
467      * @param {Function} method to wrap
468      * @param {Object} scope 
469      * @param {Array} args to add
470      * @param {Boolean|Number} append arguments or replace after N arguments.
471      * @return {Function} returns the delegate
472      */
473
474     createDelegate : function(method, obj, args, appendArgs){
475         
476         return function() {
477             var callArgs = args || arguments;
478             if(appendArgs === true){
479                 callArgs = Array.prototype.slice.call(arguments, 0);
480                 callArgs = callArgs.concat(args);
481             }else if(typeof appendArgs == "number"){
482                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
483                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
484                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
485                 }
486                 return method.apply(obj || window, callArgs);
487             };
488     }
489     
490 });