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