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