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  * use XObject.debug = 1 to turn on debugging
32  * 
33  * If XObject/[xns]/[xtype].js exists, it will use this to override properties..
34  * 
35  * 
36  * He's some questions.
37  * - should we have a special property to use as the constructor / gobject.properties rather
38  *   than sending all basic types to this?
39  * 
40  * @cfg xtype {String|Function} constructor or string.
41  * @cfg id {String}  (optional) id for registry
42  * @cfg xns {String|Object}   (optional) namespace eg. Gtk or 'Gtk' - used with xtype.
43  * @cfg items {Array}   (optional) list of child elements which will be constructed.. using XObject
44  * @cfg listeners {Object}   (optional) map Gobject signals to functions
45  * @cfg pack {Function|String|Array}   (optional) how this object gets added to it's parent
46  * @cfg el {Object}   (optional) premade GObject
47  * 
48  * 
49  * 
50  * 
51  * 
52  * 
53  */
54
55 function XObject (cfg) {
56     // first apply cfg if set.
57       //print("new XOBJECT!!!");
58     this.config = {};
59     this.constructor = XObject;
60     
61     
62     
63     // start by seeing if we have a base class....
64     try {
65         // loocks for XObject/Gtk/TreeView.js [   TreeView = { .... } ]
66         var base = imports.XObject[cfg.xns][cfg.xtype][cfg.xtype];
67         for (var i in base) {
68             this[i] = base[i];
69         }
70         
71     } catch (e) {
72         
73     }
74     
75     
76     // copy down all elements into self..
77     
78     for (var i in cfg) {
79         this[i] = cfg[i];
80         if (typeof(cfg[i]) == 'function') { // do we skip objects.
81             continue;
82         }
83         // these properties are not copied to cfg.
84         if (    i == 'pack' ||
85                 i == 'items' ||
86                 i == 'id' ||
87                 i == 'xtype' ||
88                 i == 'xdebug' ||
89                 i == 'xns') {
90             continue;
91         }
92         
93         
94         this.config[i] = cfg[i];
95     }
96     
97     
98     this.items = this.items || [];
99     
100     
101     // pack can be false!
102     if (typeof(this.pack) == 'undefined') {
103         
104         this.pack = [ 'add' ]
105         /*
106         var Gtk  = imports.gi.Gtk;
107         switch (true) {
108             // any others!!
109             case (this.xtype == Gtk.MenuItem):  this.pack = [ 'append' ]; break;
110             
111         }
112         */
113         
114     }
115     
116     
117     
118     
119     
120     
121 }
122
123
124
125 XObject.prototype = {
126     /**
127      * @property el {GObject} the Gtk / etc. element.
128      */
129     el : false, 
130     /*
131      * @property items {Array} list of sub elements
132      */
133     /**
134      * @property parent {XObject} parent Element
135      */
136      
137      /**
138      * @property config {Object} the construction configuration.
139      */
140      /**
141       * @method init
142       * Initializes the Element (el) hooks up all the listeners
143       * and packs the children.
144       * you can override this, in child objects, then 
145       * do this to do thi initaliztion.
146       * 
147       * XObject.prototype.init.call(this); 
148       * 
149       */ 
150     init : function()
151     {
152          
153         var items = [];
154         this.items.forEach(function(i) {
155             items.push(i);
156         });
157         // remove items.
158         this.listeners = this.listeners || {}; 
159         this.items = [];
160          
161         // do we need to call 'beforeInit here?'
162          
163         // handle include?
164         //if ((this.xtype == 'Include')) {
165         //    o = this.pre_registry[cls];
166         //}
167         var isSeed = typeof(Seed) != 'undefined';
168          
169         // xtype= Gtk.Menu ?? what about c_new stuff?
170         if (XObject.debug) print("init: ID:"+ this.id +" typeof(xtype): "  + typeof(this.xtype));
171         if (!this.el && typeof(this.xtype) == 'function') {
172             if (XObject.debug) print("func?"  + XObject.keys(this.config).join(','));
173             this.el = this.xtype(this.config);
174            
175         }
176         if (!this.el && typeof(this.xtype) == 'object') {
177             if (XObject.debug) print("obj?"  + XObject.keys(this.config).join(','));
178             this.el = new (this.xtype)(this.config);
179       
180         }
181         //print(this.el);
182         if (!this.el && this.xns) {
183             
184             var NS = imports.gi[this.xns];
185             if (!NS) {
186                 Seed.print('Invalid xns: ' + this.xns);
187             }
188             constructor = NS[this.xtype];
189             if (!constructor) {
190                 Seed.print('Invalid xtype: ' + this.xns + '.' + this.xtype);
191             }
192             this.el  =   isSeed ? new constructor(this.config) : new constructor();
193             
194         }
195         if (XObject.debug) print("init: ID:"+ this.id +" typeof(el):" + this.el);
196         
197         // always overlay props..
198         // check for 'write' on object..
199         /*
200         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
201                 
202             var gi = GIRepository.IRepository.get_default();
203             var ty = gi.find_by_gtype(this.xtype.type);
204             var write = [];
205             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
206                 var p =   GIRepository.object_info_get_property(ty,i);
207                 if (GIRepository.property_info_get_flags(p) & 2) {
208                     write.push(GIRepository.base_info_get_name(p));
209                 }
210             }
211             XObject.writeablePropsCache[this.xtype.type] = write;
212             print(write.join(", "));
213         }
214         
215         */
216         
217          
218         for (var i in this.config) {
219             if (i == 'type') { // problem with Gtk.Window... - not decided on a better way to handle this.
220                 continue;
221             }
222             if (i == 'buttons') { // problem with Gtk.MessageDialog..
223                 continue;
224             }
225             if (i[0] == '.') { // parent? - 
226                 continue;
227             }
228             this.el[i] = this.config[i];
229         }
230         
231         // register it!
232         //if (o.xnsid  && o.id) {
233          //   XObject.registry = XObject.registry || { };
234          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
235          //   XObject.registry[o.xnsid][o.id] = this;
236         //}
237         
238         var type = this.xtype.type ? GObject.type_name(this.xtype.type) : '';
239         print("MAKE " + type);
240         
241         
242         var _this=this;
243         items.forEach(function(i,n) {
244             
245             if (type == 'GtkTable' && i.pack == 'add') {
246                 var c = n % _this.config.n_columns;
247                 var r = Math.floor(n/_this.config.n_columns);
248                 i.pack = [ 'attach', c, c+1, r, r+1, 
249                         typeof(i.x_options) == 'undefined' ?  5 : i.x_options,
250                         typeof(i.y_options) == 'undefined' ?  5 : i.y_options,
251                         typeof(i.x_padding) == 'undefined' ?  0 : i.x_padding,
252                         typeof(i.x_padding) == 'undefined' ?  0 : i.x_padding
253                        
254                 ]
255             }
256             
257             _this.addItem(i);
258         })
259             
260         
261         for (var i in this.listeners) {
262             this.addListener(i, this.listeners[i]);
263         }
264         
265         // delete this.listeners ?
266         // do again so child props work!
267        
268         // do we need to call 'init here?'
269     },
270       
271      
272      /**
273       * @method addItem
274       * Adds an item to the object using a new XObject
275       * uses pack property to determine how to add it.
276       * @arg cfg {Object} same as XObject constructor.
277       */
278     addItem : function(o) {
279         if (typeof(o) == 'undefined') {
280             print("Invalid Item added to this!");
281             imports.console.dump(this);
282             Seed.quit();
283         }
284         // what about extended items!?!?!?
285         var item = (o.constructor == XObject) ? o : new XObject(o);
286         item.parent = this;
287         this.items.push(item);
288         item.init();
289         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
290        // print("addItem - call init [" + item.pack.join(',') + ']');
291         if (!item.el) {
292             print("NO EL!");
293             imports.console.dump(item);
294             Seed.quit();
295         }
296          
297         
298         if (item.pack===false) {  // no 
299             return;
300         }
301         if (typeof(item.pack) == 'function') {
302             // parent, child
303             item.pack.apply(item, [ this , item  ]);
304             item.parent = this;
305             return;
306         }
307         var args = [];
308         var pack_m  = false;
309         if (typeof(item.pack) == 'string') {
310              
311             item.pack.split(',').forEach(function(e, i) {
312                 
313                 if (e == 'false') { args.push( false); return; }
314                 if (e == 'true') {  args.push( true);  return; }
315                 if (!isNaN(parseInt(e))) { args.push( parseInt(e)); return; }
316                 args.push(e);
317             });
318             //print(args.join(","));
319             
320             pack_m = args.shift();
321         } else {
322             pack_m = item.pack.shift();
323             args = item.pack;
324         }
325         
326         // handle error.
327         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
328             
329             throw {
330                 name: "ArgumentError", 
331                 message : 'pack method not available : ' + this.id + " : " + this.xtype + '.' +  pack_m + " ADDING " + item.el
332                     
333             }
334            
335             
336             
337             
338             return;
339         }
340         
341         
342         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
343
344         args.unshift(item.el);
345         if (XObject.debug) print(pack_m + '[' + args.join(',') +']');
346         //Seed.print('args: ' + args.length);
347         if (pack_m) {
348             this.el[pack_m].apply(this.el, args);
349         }
350         
351        
352         
353     },
354     /**
355       * @method addListener
356       * Connects a method to a signal. (gjs/Seed aware)
357       * 
358       * @arg sig  {String} name of signal
359       * @arg fn  {Function} handler.
360       */
361     addListener  : function(sig, fn) 
362     {
363  
364         if (XObject.debug) Seed.print("Add signal " + sig);
365         fn.id= sig;
366         var _li = XObject.createDelegate(fn,this);
367         // private listeners that are not copied to GTk.
368         
369         if (typeof(Seed) != 'undefined') {
370           //   Seed.print(typeof(_li));
371             this.el.signal[sig].connect(_li);
372         } else {
373             this.el.connect( sig, _li);
374         }
375              
376         
377     },
378      /**
379       * @method get
380       * Finds an object in the child elements using xid of object.
381       * prefix with '.' to look up the tree.. 
382       * prefix with multiple '..' to look further up..
383       * prefix with '/' to look from the top, eg. '^LeftTree.model'
384       * 
385       * @arg name  {String} name of signal
386       * @return   {XObject|false} the object if found.
387       */
388     get : function(xid)
389     {
390         if (XObject.debug) print("SEARCH FOR " + xid + " in " + this.id);
391         var ret=  false;
392         var oid = '' + xid;
393         if (!xid.length) {
394             throw {
395                 name: "ArgumentError", 
396                 message : "ID not found : empty id"
397             }
398         }
399         
400         if (xid[0] == '.') {
401             return this.parent.get(xid.substring(1));
402         }
403         if (xid[0] == '/') {
404             
405             if (typeof(XObject.cache[xid]) != 'undefined') {
406                 return XObject.cache[xid]; 
407             }
408             if (xid.indexOf('.') > -1) {
409                 
410                 var child = xid.split('.');
411                 var nxid = child.shift();
412                     
413                 child = child.join('.');
414                 if (typeof(XObject.cache[nxid]) != 'undefined') {
415                     return XObject.cache[nxid].get(child);
416                 }
417                 
418                 
419             }
420             var e = this;
421             while (e.parent) {
422                 e = e.parent;
423             }
424             
425             try {
426                 ret = e.get(xid.substring(1));
427             } catch (ex) { }
428             
429             if (!ret) {
430                 throw {
431                     name: "ArgumentError", 
432                     message : "ID not found : " + oid
433                 }
434             }
435             XObject.cache[xid] = ret;
436             return XObject.cache[xid];
437         }
438         var child = false;
439         
440         if (xid.indexOf('.') > -1) {
441             child = xid.split('.');
442             xid = child.shift();
443             
444             child = child.join('.');
445             
446         }
447         if (xid == this.id) {
448             try {
449                 return child === false ? this : this.get(child);
450             } catch (ex) {
451                 throw {
452                     name: "ArgumentError", 
453                     message : "ID not found : " + oid
454                 }
455             }
456             
457         }
458         
459         
460         this.items.forEach(function(ch) {
461             if (ret) {
462                 return;
463             }
464             if (ch.id == xid) {
465                 ret = ch;
466             }
467         })
468         if (ret) {
469             try {
470                 return child === false ? ret : ret.get(child);
471             } catch (ex) {
472                 throw {
473                     name: "ArgumentError", 
474                     message : "ID not found : " + oid
475                 }
476             }
477             
478         }
479         // iterate children.
480         var _this = this;
481         this.items.forEach(function(ch) {
482             if (ret) {
483                 return;
484             }
485             if (!ch.get) {
486                 print("invalid item...");
487                 imports.console.dump(_this);
488                 Seed.quit();
489             }
490             try {
491                 ret = ch.get(xid);
492             } catch (ex) { }
493             
494             
495         });
496         if (!ret) {
497             throw {
498                 name: "ArgumentError", 
499                 message : "ID not found : " + oid
500             }
501         }
502         try {
503             return child === false ? ret : ret.get(child);
504         } catch (ex) {
505             throw {
506                 name: "ArgumentError", 
507                 message : "ID not found : " + oid
508             }
509         }
510     }
511       
512       
513
514          
515      
516 /**
517  * Copies all the properties of config to obj.
518  *
519  * Pretty much the same as JQuery/Prototype.. or Roo.apply
520  * @param {Object} obj The receiver of the properties
521  * @param {Object} config The source of the properties
522  * @param {Object} defaults A different object that will also be applied for default values
523  * @return {Object} returns obj
524  * @member XObject extend
525  */
526
527
528 XObject.extend = function(o, c, defaults){
529     if(defaults){
530         // no "this" reference for friendly out of scope calls
531         XObject.extend(o, defaults);
532     }
533     if(o && c && typeof c == 'object'){
534         for(var p in c){
535             o[p] = c[p];
536         }
537     }
538     return o;
539 };
540
541 XObject.extend(XObject,
542 {
543      
544     /**
545      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
546      * 
547      */
548     debug : true,
549     /**
550      * @property {Object} cache - cache of object ids
551      * 
552      */
553     cache: { },
554     
555     /**
556      * Copies all the properties of config to obj, if the do not exist.
557      * @param {Object} obj The receiver of the properties
558      * @param {Object} config The source of the properties
559      * @return {Object} returns obj
560      * @member Object extendIf
561      */
562
563
564     extendIf : function(o, c)
565     {
566
567         if(!o || !c || typeof c != 'object'){
568             return o;
569         }
570         for(var p in c){
571             if (typeof(o[p]) != 'undefined') {
572                 continue;
573             }
574             o[p] = c[p];
575         }
576         return o;
577     },
578
579  
580
581     /**
582      * Extends one class with another class and optionally overrides members with the passed literal. This class
583      * also adds the function "override()" to the class that can be used to override
584      * members on an instance.
585      *
586      * usage:
587      * MyObject = Object.define(
588      *     function(...) {
589      *          ....
590      *     },
591      *     parentClass, // or Object
592      *     {
593      *        ... methods and properties.
594      *     }
595      * });
596      * @param {Function} constructor The class inheriting the functionality
597      * @param {Object} superclass The class being extended
598      * @param {Object} overrides (optional) A literal with members
599      * @return {Function} constructor (eg. class
600      * @method define
601      */
602     define : function()
603     {
604         // inline overrides
605         var io = function(o){
606             for(var m in o){
607                 this[m] = o[m];
608             }
609         };
610         return function(constructor, parentClass, overrides) {
611             if (typeof(parentClass) == 'undefined') {
612                 print("XObject.define: Missing parentClass: when applying: " );
613                 print(new String(constructor));
614                 Seed.quit(); 
615             }
616             if (typeof(parentClass.prototype) == 'undefined') {
617                 print("Missing protype: when applying: " );
618                 print(new String(constructor));
619                 print(new String(parentClass));
620                 Seed.quit(); 
621             }
622             var F = function(){};
623             var sbp;
624             var spp = parentClass.prototype;
625             
626             F.prototype = spp;
627             sbp = constructor.prototype = new F();
628             sbp.constructor=constructor;
629             constructor.superclass=spp;
630
631             // extends Object.
632             if(spp.constructor == Object.prototype.constructor){
633                 spp.constructor=parentClass;
634             }
635             
636             constructor.override = function(o){
637                 Object.extend(constructor.prototype, o);
638             };
639             sbp.override = io;
640             XObject.extend(constructor.prototype, overrides);
641             return constructor;
642         };
643     }(),
644
645          
646     /**
647      * returns a list of keys of the object.
648      * @param {Object} obj object to inspect
649      * @return {Array} returns list of kyes
650      * @member XObject keys
651      */
652     keys : function(o)
653     {
654         var ret = [];
655         for(var i in o) {
656             ret.push(i);
657         }
658         return ret;
659     },
660       
661     /**
662      * @member XObject createDelegate
663      * creates a delage metdhod
664      * @param {Function} method to wrap
665      * @param {Object} scope 
666      * @param {Array} args to add
667      * @param {Boolean|Number} append arguments or replace after N arguments.
668      * @return {Function} returns the delegate
669      */
670
671     createDelegate : function(method, obj, args, appendArgs){
672         
673         return function() {
674             if (XObject.debug) print("CALL: " + obj.id + ':'+ method.id);
675             
676             var callArgs = args || arguments;
677             if(appendArgs === true){
678                 callArgs = Array.prototype.slice.call(arguments, 0);
679                 callArgs = callArgs.concat(args);
680             }else if(typeof appendArgs == "number"){
681                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
682                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
683                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
684                 }
685                 return method.apply(obj || window, callArgs);
686             };
687     }
688     
689 });