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