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