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