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