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') || (typeof(cfg[i]) == 'function')) {
62             continue;
63         }
64         // these properties are not copied to cfg.
65         if (i == 'pack' ||
66                 i == 'id' ||
67                 i == 'xtype' ||
68                 i == 'xdebug' ||
69                 i == 'xns') {
70             continue;
71         }
72         
73         
74         this.config[i] = cfg[i];
75     }
76     this.items = this.items || [];
77     // pack can be false!
78     this.pack = typeof(this.pack) == 'undefined' ? ['add'] : this.pack;
79     
80     
81 }
82
83
84
85 XObject.prototype = {
86     /**
87      * @property el {GObject} the Gtk / etc. element.
88      */
89     el : false, 
90     /*
91      * @property items {Array} list of sub elements
92      */
93     /**
94      * @property parent {XObject} parent Element
95      */
96      
97      /**
98      * @property config {Object} the construction configuration.
99      */
100      /**
101       * @method init
102       * Initializes the Element (el) hooks up all the listeners
103       * and packs the children.
104       * you can override this, in child objects, then 
105       * do this to do thi initaliztion.
106       * 
107       * XObject.prototype.init.call(this); 
108       * 
109       */ 
110     init : function()
111     {
112          
113         var items = [];
114         this.items.forEach(function(i) {
115             items.push(i);
116         });
117         // remove items.
118         this.listeners = this.listeners || {}; 
119         this.items = [];
120          
121         // do we need to call 'beforeInit here?'
122          
123         // handle include?
124         //if ((this.xtype == 'Include')) {
125         //    o = this.pre_registry[cls];
126         //}
127         var isSeed = typeof(Seed) != 'undefined';
128          
129         // xtype= Gtk.Menu ?? what about c_new stuff?
130         if (XObject.debug) print("init: typeof(xtype): "  + typeof(this.xtype));
131         if (!this.el && typeof(this.xtype) == 'function') {
132             if (XObject.debug) print("func?"  + XObject.keys(this.config).join(','));
133             this.el = this.xtype(this.config);
134         }
135         if (!this.el && typeof(this.xtype) == 'object') {
136             if (XObject.debug) print("obj?"  + XObject.keys(this.config).join(','));
137             this.el = new (this.xtype)(this.config);
138         }
139         //print(this.el);
140         if (!this.el && this.xns) {
141             
142             var NS = imports.gi[this.xns];
143             if (!NS) {
144                 Seed.print('Invalid xns: ' + this.xns);
145             }
146             constructor = NS[this.xtype];
147             if (!constructor) {
148                 Seed.print('Invalid xtype: ' + this.xns + '.' + this.xtype);
149             }
150             this.el  =   isSeed ? new constructor(this.config) : new constructor();
151             
152         }
153         if (XObject.debug) print("init: typeof(el):" + typeof(this.el));
154         
155         // always overlay props..
156         // check for 'write' on object..
157         /*
158         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
159                 
160             var gi = GIRepository.IRepository.get_default();
161             var ty = gi.find_by_gtype(this.xtype.type);
162             var write = [];
163             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
164                 var p =   GIRepository.object_info_get_property(ty,i);
165                 if (GIRepository.property_info_get_flags(p) & 2) {
166                     write.push(GIRepository.base_info_get_name(p));
167                 }
168             }
169             XObject.writeablePropsCache[this.xtype.type] = write;
170             print(write.join(", "));
171         }
172         
173         */
174         
175         for (var i in this.config) {
176             // only write to writable properties
177           //  if (XObject.writeablePropsCache[this.xtype.type].indexOf(i) < 0) {
178           //      continue;
179            // }
180             this.el[i] = this.config[i];
181         }
182         // register it!
183         //if (o.xnsid  && o.id) {
184          //   XObject.registry = XObject.registry || { };
185          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
186          //   XObject.registry[o.xnsid][o.id] = this;
187         //}
188         var _this=this;
189         items.forEach(function(i) {
190             _this.addItem(i);
191         })
192             
193         
194         for (var i in this.listeners) {
195             this.addListener(i, this.listeners[i]);
196         }
197         // delete this.listeners ?
198         
199         
200         // do we need to call 'init here?'
201     },
202       
203      
204      /**
205       * @method addItem
206       * Adds an item to the object using a new XObject
207       * uses pack property to determine how to add it.
208       * @arg cfg {Object} same as XObject constructor.
209       */
210     addItem : function(o) {
211         if (typeof(o) == 'undefined') {
212             print("Invalid Item added to this!");
213             imports.console.dump(this);
214             Seed.quit();
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         if (XObject.debug) 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         if (XObject.debug) 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 /**
332  * Copies all the properties of config to obj.
333  *
334  * Pretty much the same as JQuery/Prototype..
335  * @param {Object} obj The receiver of the properties
336  * @param {Object} config The source of the properties
337  * @param {Object} defaults A different object that will also be applied for default values
338  * @return {Object} returns obj
339  * @member XObject extend
340  */
341
342
343 XObject.extend = function(o, c, defaults){
344     if(defaults){
345         // no "this" reference for friendly out of scope calls
346         XObject.extend(o, defaults);
347     }
348     if(o && c && typeof c == 'object'){
349         for(var p in c){
350             o[p] = c[p];
351         }
352     }
353     return o;
354 };
355
356 XObject.extend(XObject,
357 {
358     /**
359      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
360      * 
361      */
362     debug : false,
363     /**
364      * Copies all the properties of config to obj, if the do not exist.
365      * @param {Object} obj The receiver of the properties
366      * @param {Object} config The source of the properties
367      * @return {Object} returns obj
368      * @member Object extendIf
369      */
370
371
372     extendIf : function(o, c){
373
374         if(!o || !c || typeof c != 'object'){
375             return o;
376         }
377         for(var p in c){
378             if (typeof(o[p]) != 'undefined') {
379                 continue;
380             }
381             o[p] = c[p];
382         }
383         return o;
384     },
385
386  
387
388     /**
389      * Extends one class with another class and optionally overrides members with the passed literal. This class
390      * also adds the function "override()" to the class that can be used to override
391      * members on an instance.
392      *
393      * usage:
394      * MyObject = Object.define(
395      *     function(...) {
396      *          ....
397      *     },
398      *     parentClass, // or Object
399      *     {
400      *        ... methods and properties.
401      *     }
402      * });
403      * @param {Function} constructor The class inheriting the functionality
404      * @param {Object} superclass The class being extended
405      * @param {Object} overrides (optional) A literal with members
406      * @return {Function} constructor (eg. class
407      * @method define
408      */
409     define : function(){
410         // inline overrides
411         var io = function(o){
412             for(var m in o){
413                 this[m] = o[m];
414             }
415         };
416         return function(constructor, parentClass, overrides) {
417             if (typeof(parentClass) == 'undefined') {
418                 print("XObject.define: Missing parentClass: when applying: " );
419                 print(new String(constructor));
420                 Seed.quit(); 
421             }
422             if (typeof(parentClass.prototype) == 'undefined') {
423                 print("Missing protype: when applying: " );
424                 print(new String(constructor));
425                 print(new String(parentClass));
426                 Seed.quit(); 
427             }
428             var F = function(){};
429             var sbp;
430             var spp = parentClass.prototype;
431             
432             F.prototype = spp;
433             sbp = constructor.prototype = new F();
434             sbp.constructor=constructor;
435             constructor.superclass=spp;
436
437             // extends Object.
438             if(spp.constructor == Object.prototype.constructor){
439                 spp.constructor=parentClass;
440             }
441             
442             constructor.override = function(o){
443                 Object.extend(constructor.prototype, o);
444             };
445             sbp.override = io;
446             XObject.extend(constructor.prototype, overrides);
447             return constructor;
448         };
449     }(),
450
451          
452     /**
453      * returns a list of keys of the object.
454      * @param {Object} obj object to inspect
455      * @return {Array} returns list of kyes
456      * @member XObject keys
457      */
458     keys : function(o)
459     {
460         var ret = [];
461         for(var i in o) {
462             ret.push(i);
463         }
464         return ret;
465     },
466       
467     /**
468      * @member XObject createDelegate
469      * creates a delage metdhod
470      * @param {Function} method to wrap
471      * @param {Object} scope 
472      * @param {Array} args to add
473      * @param {Boolean|Number} append arguments or replace after N arguments.
474      * @return {Function} returns the delegate
475      */
476
477     createDelegate : function(method, obj, args, appendArgs){
478         
479         return function() {
480             var callArgs = args || arguments;
481             if(appendArgs === true){
482                 callArgs = Array.prototype.slice.call(arguments, 0);
483                 callArgs = callArgs.concat(args);
484             }else if(typeof appendArgs == "number"){
485                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
486                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
487                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
488                 }
489                 return method.apply(obj || window, callArgs);
490             };
491     }
492     
493 });