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