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