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