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 (typeof(this.xtype) == 'function') {
134             print("func?"  + XObject.keys(o).join(','));
135             this.el = this.el ||   this.xtype(o);
136         }
137         if (typeof(this.xtype) == 'object') {
138             print("obj?"  + XObject.keys(o).join(','));
139             this.el = 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         // 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 o) {
176             // only write to writable properties
177           //  if (XObject.writeablePropsCache[this.xtype.type].indexOf(i) < 0) {
178           //      continue;
179            // }
180             this.el[i] = o[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         
189         cfg.items.forEach(this.addItem, this);
190         
191         for (var i in this.listeners) {
192             this.addListener(i, this.listeners[i]);
193         }
194         // delete this.listeners ?
195         
196         
197         // do we need to call 'init here?'
198     },
199       
200      
201      /**
202       * @method addItem
203       * Adds an item to the object using a new XObject
204       * uses pack property to determine how to add it.
205       * @arg cfg {Object} same as XObject constructor.
206       */
207     addItem : function(o) {
208         
209         print("CTR:PROTO:" + ( o.id ? o.id : '??'));
210         print(o.constructor.prototype == XObject.prototype);
211         
212         var item = (o.constructor == XObject) ? o : new XObject(o);
213        
214         item.init();
215         print("addItem - call init [" + item.pack.join(',') + ']');
216         print(item.el);
217         item.parent = this;
218         this.items.push(item);
219         
220         if (item.pack===false) {  // no 
221             return;
222         }
223         if (typeof(item.pack) == 'function') {
224             // parent, child
225             item.pack.apply(o, [ o , o.items[i] ]);
226             item.parent = this;
227             return;
228         }
229         var args = [];
230         var pack_m  = false;
231         if (typeof(item.pack) == 'string') {
232             pack_m = item.pack;
233         } else {
234             pack_m = item.pack.shift();
235             args = item.pack;
236         }
237         
238         // handle error.
239         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
240             Seed.print('pack method not available : ' + this.xtype + '.' +  pack_m);
241             return;
242         }
243         
244         
245         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
246
247         args.unshift(item.el);
248         print('[' + args.join(',') +']');
249         //Seed.print('args: ' + args.length);
250         if (pack_m) {
251             this.el[pack_m].apply(this.el, args);
252         }
253         
254        
255         
256     },
257     /**
258       * @method addListener
259       * Connects a method to a signal. (gjs/Seed aware)
260       * 
261       * @arg sig  {String} name of signal
262       * @arg fn  {Function} handler.
263       */
264     addListener  : function(sig, fn) 
265     {
266  
267         Seed.print("Add signal " + sig);
268  
269         var _li = XObject.createDelegate(fn,this);
270         // private listeners that are not copied to GTk.
271         
272         if (typeof(Seed) != 'undefined') {
273           //   Seed.print(typeof(_li));
274             this.el.signal[sig].connect(_li);
275         } else {
276             this.el.connect( sig, _li);
277         }
278              
279         
280     },
281      /**
282       * @method get
283       * Finds an object in the child elements using xid of object.
284       * prefix with '.' to look up the tree.. multiple '..' to look further up..
285       * 
286       * @arg name  {String} name of signal
287       * @return   {XObject|false} the object if found.
288       */
289     get : function(xid)
290     {
291         var ret=  false;
292         if (xid[0] == '.') {
293             return this.parent.get(xid.substring(1));
294         }
295         
296         
297         this.items.forEach(function(ch) {
298             if (ch.id == xid) {
299                 ret = ch;
300                 return true;
301             }
302         })
303         if (ret) {
304             return ret;
305         }
306         // iterate children.
307         this.items.forEach(function(ch) {
308             ret = ch.get(xid);
309             if (ret) {
310                 return true;
311             }
312         })
313         return ret;
314     }
315       
316       
317
318          
319
320 XObject.writeablePropsCache = { }; 
321          
322 /**
323  * Copies all the properties of config to obj.
324  *
325  * Pretty much the same as JQuery/Prototype..
326  * @param {Object} obj The receiver of the properties
327  * @param {Object} config The source of the properties
328  * @param {Object} defaults A different object that will also be applied for default values
329  * @return {Object} returns obj
330  * @member XObject extend
331  */
332
333
334 XObject.extend = function(o, c, defaults){
335     if(defaults){
336         // no "this" reference for friendly out of scope calls
337         XObject.extend(o, defaults);
338     }
339     if(o && c && typeof c == 'object'){
340         for(var p in c){
341             o[p] = c[p];
342         }
343     }
344     return o;
345 };
346
347 XObject.extend(XObject,
348 {
349     /**
350      * Copies all the properties of config to obj, if the do not exist.
351      * @param {Object} obj The receiver of the properties
352      * @param {Object} config The source of the properties
353      * @return {Object} returns obj
354      * @member Object extendIf
355      */
356
357
358     extendIf : function(o, c){
359
360         if(!o || !c || typeof c != 'object'){
361             return o;
362         }
363         for(var p in c){
364             if (typeof(o[p]) != 'undefined') {
365                 continue;
366             }
367             o[p] = c[p];
368         }
369         return o;
370     },
371
372  
373
374     /**
375      * Extends one class with another class and optionally overrides members with the passed literal. This class
376      * also adds the function "override()" to the class that can be used to override
377      * members on an instance.
378      *
379      * usage:
380      * MyObject = Object.define(
381      *     function(...) {
382      *          ....
383      *     },
384      *     parentClass, // or Object
385      *     {
386      *        ... methods and properties.
387      *     }
388      * });
389      * @param {Function} constructor The class inheriting the functionality
390      * @param {Object} superclass The class being extended
391      * @param {Object} overrides (optional) A literal with members
392      * @return {Function} constructor (eg. class
393      * @method define
394      */
395     define : function(){
396         // inline overrides
397         var io = function(o){
398             for(var m in o){
399                 this[m] = o[m];
400             }
401         };
402         return function(constructor, parentClass, overrides) {
403             if (typeof(parentClass) == 'undefined') {
404                 print("XObject.define: Missing parentClass: when applying: " );
405                 print(new String(constructor));
406                 Seed.quit(); 
407             }
408             if (typeof(parentClass.prototype) == 'undefined') {
409                 print("Missing protype: when applying: " );
410                 print(new String(constructor));
411                 print(new String(parentClass));
412                 Seed.quit(); 
413             }
414             var F = function(){};
415             var sbp;
416             var spp = parentClass.prototype;
417             
418             F.prototype = spp;
419             sbp = constructor.prototype = new F();
420             sbp.constructor=constructor;
421             constructor.superclass=spp;
422
423             // extends Object.
424             if(spp.constructor == Object.prototype.constructor){
425                 spp.constructor=parentClass;
426             }
427             
428             constructor.override = function(o){
429                 Object.extend(constructor.prototype, o);
430             };
431             sbp.override = io;
432             XObject.extend(constructor.prototype, overrides);
433             return constructor;
434         };
435     }(),
436
437          
438     /**
439      * returns a list of keys of the object.
440      * @param {Object} obj object to inspect
441      * @return {Array} returns list of kyes
442      * @member XObject keys
443      */
444     keys : function(o)
445     {
446         var ret = [];
447         for(var i in o) {
448             ret.push(i);
449         }
450         return ret;
451     },
452       
453     /**
454      * @member XObject createDelegate
455      * creates a delage metdhod
456      * @param {Function} method to wrap
457      * @param {Object} scope 
458      * @param {Array} args to add
459      * @param {Boolean|Number} append arguments or replace after N arguments.
460      * @return {Function} returns the delegate
461      */
462
463     createDelegate : function(method, obj, args, appendArgs){
464         
465         return function() {
466             var callArgs = args || arguments;
467             if(appendArgs === true){
468                 callArgs = Array.prototype.slice.call(arguments, 0);
469                 callArgs = callArgs.concat(args);
470             }else if(typeof appendArgs == "number"){
471                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
472                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
473                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
474                 }
475                 return method.apply(obj || window, callArgs);
476             };
477     }
478     
479 });