README.txt
[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       //print("new XOBJECT!!!");
54     this.config = {};
55     this.constructor = XObject;
56     
57     // copy down all elements into self..
58     
59     for (var i in cfg) {
60         this[i] = cfg[i];
61         if ((typeof(cfg[i]) == 'function') || (typeof(cfg[i]) == 'function')) {
62             continue;
63         }
64         // these properties are not copied to cfg.
65         if (i == 'pack' ||
66                 i == 'id' ||
67                 i == 'xtype' ||
68                 i == 'xdebug' ||
69                 i == 'xns') {
70             continue;
71         }
72         
73         
74         this.config[i] = cfg[i];
75     }
76     this.items = this.items || [];
77     // pack can be false!
78     this.pack = typeof(this.pack) == 'undefined' ? ['add'] : this.pack;
79     
80     
81 }
82
83
84
85 XObject.prototype = {
86     /**
87      * @property el {GObject} the Gtk / etc. element.
88      */
89     el : false, 
90     /*
91      * @property items {Array} list of sub elements
92      */
93     /**
94      * @property parent {XObject} parent Element
95      */
96      
97      /**
98      * @property config {Object} the construction configuration.
99      */
100      /**
101       * @method init
102       * Initializes the Element (el) hooks up all the listeners
103       * and packs the children.
104       * you can override this, in child objects, then 
105       * do this to do thi initaliztion.
106       * 
107       * XObject.prototype.init.call(this); 
108       * 
109       */ 
110     init : function()
111     {
112          
113         var items = [];
114         this.items.forEach(function(i) {
115             items.push(i);
116         });
117         // remove items.
118         this.listeners = this.listeners || {}; 
119         this.items = [];
120          
121         // do we need to call 'beforeInit here?'
122          
123         // handle include?
124         //if ((this.xtype == 'Include')) {
125         //    o = this.pre_registry[cls];
126         //}
127         var isSeed = typeof(Seed) != 'undefined';
128          
129         // xtype= Gtk.Menu ?? what about c_new stuff?
130         if (XObject.debug) print("init: typeof(xtype): "  + typeof(this.xtype));
131         if (!this.el && typeof(this.xtype) == 'function') {
132             if (XObject.debug) print("func?"  + XObject.keys(this.config).join(','));
133             this.el = this.xtype(this.config);
134         }
135         if (!this.el && typeof(this.xtype) == 'object') {
136             if (XObject.debug) print("obj?"  + XObject.keys(this.config).join(','));
137             this.el = new (this.xtype)(this.config);
138         }
139         //print(this.el);
140         if (!this.el && this.xns) {
141             
142             var NS = imports.gi[this.xns];
143             if (!NS) {
144                 Seed.print('Invalid xns: ' + this.xns);
145             }
146             constructor = NS[this.xtype];
147             if (!constructor) {
148                 Seed.print('Invalid xtype: ' + this.xns + '.' + this.xtype);
149             }
150             this.el  =   isSeed ? new constructor(this.config) : new constructor();
151             
152         }
153         if (XObject.debug) print("init: typeof(el):" + typeof(this.el));
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 this.config) {
176             // only write to writable properties
177           //  if (XObject.writeablePropsCache[this.xtype.type].indexOf(i) < 0) {
178           //      continue;
179            // }
180             this.el[i] = this.config[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         var _this=this;
189         items.forEach(function(i) {
190             _this.addItem(i);
191         })
192             
193         
194         for (var i in this.listeners) {
195             this.addListener(i, this.listeners[i]);
196         }
197         // delete this.listeners ?
198         
199         
200         // do we need to call 'init here?'
201     },
202       
203      
204      /**
205       * @method addItem
206       * Adds an item to the object using a new XObject
207       * uses pack property to determine how to add it.
208       * @arg cfg {Object} same as XObject constructor.
209       */
210     addItem : function(o) {
211         if (typeof(o) == 'undefined') {
212             print("Invalid Item added to this!");
213             imports.console.dump(this);
214             Seed.quit();
215            }
216         
217         var item = (o.constructor == XObject) ? o : new XObject(o);
218        
219         item.init();
220         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
221        // print("addItem - call init [" + item.pack.join(',') + ']');
222         if (!item.el) {
223             print("NO EL!");
224             imports.console.dump(item);
225             Seed.quit();
226         }
227         
228         item.parent = this;
229         this.items.push(item);
230         
231         if (item.pack===false) {  // no 
232             return;
233         }
234         if (typeof(item.pack) == 'function') {
235             // parent, child
236             item.pack.apply(item, [ this , item  ]);
237             item.parent = this;
238             return;
239         }
240         var args = [];
241         var pack_m  = false;
242         if (typeof(item.pack) == 'string') {
243             pack_m = item.pack;
244         } else {
245             pack_m = item.pack.shift();
246             args = item.pack;
247         }
248         
249         // handle error.
250         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
251             Seed.print('pack method not available : ' + this.xtype + '.' +  pack_m);
252             return;
253         }
254         
255         
256         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
257
258         args.unshift(item.el);
259         if (XObject.debug) print('[' + args.join(',') +']');
260         //Seed.print('args: ' + args.length);
261         if (pack_m) {
262             this.el[pack_m].apply(this.el, args);
263         }
264         
265        
266         
267     },
268     /**
269       * @method addListener
270       * Connects a method to a signal. (gjs/Seed aware)
271       * 
272       * @arg sig  {String} name of signal
273       * @arg fn  {Function} handler.
274       */
275     addListener  : function(sig, fn) 
276     {
277  
278         if (XObject.debug) Seed.print("Add signal " + sig);
279  
280         var _li = XObject.createDelegate(fn,this);
281         // private listeners that are not copied to GTk.
282         
283         if (typeof(Seed) != 'undefined') {
284           //   Seed.print(typeof(_li));
285             this.el.signal[sig].connect(_li);
286         } else {
287             this.el.connect( sig, _li);
288         }
289              
290         
291     },
292      /**
293       * @method get
294       * Finds an object in the child elements using xid of object.
295       * prefix with '.' to look up the tree.. multiple '..' to look further up..
296       * 
297       * @arg name  {String} name of signal
298       * @return   {XObject|false} the object if found.
299       */
300     get : function(xid)
301     {
302         var ret=  false;
303         if (xid[0] == '.') {
304             return this.parent.get(xid.substring(1));
305         }
306         
307         
308         this.items.forEach(function(ch) {
309             if (ret) {
310                 return;
311             }
312             if (ch.id == xid) {
313                 ret = ch;
314             }
315         })
316         if (ret) {
317             return ret;
318         }
319         // iterate children.
320         var _this = this;
321         this.items.forEach(function(ch) {
322             if (ret) {
323                 return;
324             }
325             if (!ch.get) {
326                 print("invalid item...");
327                 imports.console.dump(_this);
328                 Seed.quit();
329             }
330             ret = ch.get(xid);
331             
332         })
333         return ret;
334     }
335       
336       
337
338          
339      
340 /**
341  * Copies all the properties of config to obj.
342  *
343  * Pretty much the same as JQuery/Prototype..
344  * @param {Object} obj The receiver of the properties
345  * @param {Object} config The source of the properties
346  * @param {Object} defaults A different object that will also be applied for default values
347  * @return {Object} returns obj
348  * @member XObject extend
349  */
350
351
352 XObject.extend = function(o, c, defaults){
353     if(defaults){
354         // no "this" reference for friendly out of scope calls
355         XObject.extend(o, defaults);
356     }
357     if(o && c && typeof c == 'object'){
358         for(var p in c){
359             o[p] = c[p];
360         }
361     }
362     return o;
363 };
364
365 XObject.extend(XObject,
366 {
367     /**
368      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
369      * 
370      */
371     debug : false,
372     /**
373      * Copies all the properties of config to obj, if the do not exist.
374      * @param {Object} obj The receiver of the properties
375      * @param {Object} config The source of the properties
376      * @return {Object} returns obj
377      * @member Object extendIf
378      */
379
380
381     extendIf : function(o, c){
382
383         if(!o || !c || typeof c != 'object'){
384             return o;
385         }
386         for(var p in c){
387             if (typeof(o[p]) != 'undefined') {
388                 continue;
389             }
390             o[p] = c[p];
391         }
392         return o;
393     },
394
395  
396
397     /**
398      * Extends one class with another class and optionally overrides members with the passed literal. This class
399      * also adds the function "override()" to the class that can be used to override
400      * members on an instance.
401      *
402      * usage:
403      * MyObject = Object.define(
404      *     function(...) {
405      *          ....
406      *     },
407      *     parentClass, // or Object
408      *     {
409      *        ... methods and properties.
410      *     }
411      * });
412      * @param {Function} constructor The class inheriting the functionality
413      * @param {Object} superclass The class being extended
414      * @param {Object} overrides (optional) A literal with members
415      * @return {Function} constructor (eg. class
416      * @method define
417      */
418     define : function(){
419         // inline overrides
420         var io = function(o){
421             for(var m in o){
422                 this[m] = o[m];
423             }
424         };
425         return function(constructor, parentClass, overrides) {
426             if (typeof(parentClass) == 'undefined') {
427                 print("XObject.define: Missing parentClass: when applying: " );
428                 print(new String(constructor));
429                 Seed.quit(); 
430             }
431             if (typeof(parentClass.prototype) == 'undefined') {
432                 print("Missing protype: when applying: " );
433                 print(new String(constructor));
434                 print(new String(parentClass));
435                 Seed.quit(); 
436             }
437             var F = function(){};
438             var sbp;
439             var spp = parentClass.prototype;
440             
441             F.prototype = spp;
442             sbp = constructor.prototype = new F();
443             sbp.constructor=constructor;
444             constructor.superclass=spp;
445
446             // extends Object.
447             if(spp.constructor == Object.prototype.constructor){
448                 spp.constructor=parentClass;
449             }
450             
451             constructor.override = function(o){
452                 Object.extend(constructor.prototype, o);
453             };
454             sbp.override = io;
455             XObject.extend(constructor.prototype, overrides);
456             return constructor;
457         };
458     }(),
459
460          
461     /**
462      * returns a list of keys of the object.
463      * @param {Object} obj object to inspect
464      * @return {Array} returns list of kyes
465      * @member XObject keys
466      */
467     keys : function(o)
468     {
469         var ret = [];
470         for(var i in o) {
471             ret.push(i);
472         }
473         return ret;
474     },
475       
476     /**
477      * @member XObject createDelegate
478      * creates a delage metdhod
479      * @param {Function} method to wrap
480      * @param {Object} scope 
481      * @param {Array} args to add
482      * @param {Boolean|Number} append arguments or replace after N arguments.
483      * @return {Function} returns the delegate
484      */
485
486     createDelegate : function(method, obj, args, appendArgs){
487         
488         return function() {
489             var callArgs = args || arguments;
490             if(appendArgs === true){
491                 callArgs = Array.prototype.slice.call(arguments, 0);
492                 callArgs = callArgs.concat(args);
493             }else if(typeof appendArgs == "number"){
494                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
495                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
496                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
497                 }
498                 return method.apply(obj || window, callArgs);
499             };
500     }
501     
502 });