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