builder_run.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         print("init: typeof(xtype): "  + typeof(this.xtype));
131         if (!this.el && typeof(this.xtype) == 'function') {
132             print("func?"  + XObject.keys(this.config).join(','));
133             this.el = this.xtype(this.config);
134         }
135         if (!this.el && typeof(this.xtype) == 'object') {
136             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         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         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 });