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                 
195                 var xtypeof = isSeed ? typeof(this.xtype) :
196                         // oterhwise it's gjs, which case ctors are functions, not objects...
197                         ( typeof(this.xtype) == 'function' ? 'object' : typeof(this.xtype) );
198                 
199         if (!this.el && xtypeof == 'function') {
200             XObject.log("func?"  + XObject.keys(this.config).join(','));
201             this.el = this.xtype(this.config);
202            
203         }
204         if (!this.el && xtypeof == 'object') {
205             
206             XObject.log("obj?"  + XObject.keys(this.config).join(','));
207             try {
208                                 if (!isSeed) {
209                                         // gjs does not like properties that do not exist..
210                                         
211                                         
212                                         var li = this.config.listeners;
213                                         delete this.config['listeners'];
214                                 }
215                                 
216                 this.el = new (this.xtype)(this.config);
217             } catch(e) {
218                 print(JSON.stringify(e,null,4));
219                 print(JSON.stringify(this.config,null,4));
220                 print(e.stack);
221                 
222                  throw {
223                     name: "ArgumentError", 
224                     message :"Error creating object from xtype(object)"
225                  };
226             }
227               
228       
229         }
230         //print(this.el);
231         if (!this.el && this.xns) {
232             
233             var NS = imports.gi[this.xns];
234             if (!NS) {
235                 XObject.error('Invalid xns: ' + this.xns, true);
236             }
237             constructor = NS[this.xtype];
238             if (!constructor) {
239                 XObject.error('Invalid xtype: ' + this.xns + '.' + this.xtype);
240             }
241             this.el  =   isSeed ? new constructor(this.config) : new constructor();
242             
243         }
244         XObject.log("init: ID:"+ this.id +" typeof(el):" + this.el);
245         
246         // always overlay props..
247         // check for 'write' on object..
248         /*
249         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
250                 
251             var gi = GIRepository.IRepository.get_default();
252             var ty = gi.find_by_gtype(this.xtype.type);
253             var write = [];
254             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
255                 var p =   GIRepository.object_info_get_property(ty,i);
256                 if (GIRepository.property_info_get_flags(p) & 2) {
257                     write.push(GIRepository.base_info_get_name(p));
258                 }
259             }
260             XObject.writeablePropsCache[this.xtype.type] = write;
261             print(write.join(", "));
262         }
263         
264         */
265         
266          
267         for (var i in this.config) {
268             if (i == 'type') { // problem with Gtk.Window... - not decided on a better way to handle this.
269                 continue;
270             }
271             if (i == 'buttons') { // problem with Gtk.MessageDialog..
272                 continue;
273             }
274             if (i[0] == '.') { // parent? - 
275                 continue;
276             }
277             this.el[i] = this.config[i];
278         }
279         
280         // register it!
281         //if (o.xnsid  && o.id) {
282          //   XObject.registry = XObject.registry || { };
283          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
284          //   XObject.registry[o.xnsid][o.id] = this;
285         //}
286         
287         var type = this.xtype && this.xtype.type ? GObject.type_name(this.xtype.type) : '';
288         XObject.log("add children to " + type);
289         
290         var _this=this;
291         for (var i = 0; i < this.items.length;i++) { 
292             _this.addItem(this.items[i],i);
293         }
294             
295         
296         for (var i in this.listeners) {
297             this.addListener(i, this.listeners[i]);
298         }
299         
300         this.init = XObject.emptyFn;
301            
302         // delete this.listeners ?
303         // do again so child props work!
304        
305         // do we need to call 'init here?'
306     },
307       
308      
309      /**
310       * Adds an item to the object using a new XObject
311       * uses pack property to determine how to add it.
312       * @arg cfg {Object} same as XObject constructor.
313       */
314     addItem : function(item, pos) 
315     {
316         
317         if (typeof(item) == 'undefined') {
318             XObject.error("Invalid Item added to this!");
319             imports.console.dump(this.cfg);
320             Seed.quit();
321         }
322         // what about extended items!?!?!?
323        
324         item.init(this);
325         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
326        // print("addItem - call init [" + item.pack.join(',') + ']');
327         if (!item.el) {
328             XObject.error("NO EL!");
329             imports.console.dump(item);
330             Seed.quit();
331         }
332         XObject.log(XObject.type(this.xtype) + ":pack=" + item.pack);
333         
334         if (item.pack===false) {  // no packing.. various items have this ..
335             return;
336         }
337         
338         if (typeof(item.pack) == 'function') { // pack is a function..
339             // parent, child
340             item.pack.apply(item, [ this , item  ]);
341             item.parent = this;
342             return;
343         }
344         
345         // pack =  'add,x,y'
346         var args = [];
347         var pack_m  = false;
348         if (typeof(item.pack) == 'string') {
349              
350             item.pack.split(',').forEach(function(e, i) {
351                 
352                 if (e == 'false') { args.push( false); return; }
353                 if (e == 'true') {  args.push( true);  return; }
354                 if (!isNaN(parseInt(e))) { args.push( parseInt(e)); return; }
355                 args.push(e);
356             });
357             //print(args.join(","));
358             
359             pack_m = args.shift();
360         } else {
361             pack_m = item.pack.shift();
362             args = item.pack;
363         }
364         
365         // handle error.
366         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
367             
368             throw {
369                 name: "ArgumentError", 
370                 message : 'pack method not available : ' + this.id + " : " + this.xtype + '.' +  pack_m + " ADDING " + item.el
371                     
372             }
373            
374             return;
375         }
376         
377         
378         // finally call the pack method 
379         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
380         
381         args.unshift(item.el);
382         
383          
384         
385         
386         
387         XObject.log(pack_m + '[' + args.join(',') +']');
388         //Seed.print('args: ' + args.length);
389         if (pack_m) {
390             this.el[pack_m].apply(this.el, args);
391         }
392         
393        
394         
395     },
396     /**
397     * Connects a method to a signal. (gjs/Seed aware)
398     * 
399     * @param {String} sig  name of signal
400     * @param {Function} fn  handler.
401     */
402     addListener  : function(sig, fn) 
403     {
404  
405         XObject.log("Add signal " + sig);
406         fn.id= sig;
407         var _li = XObject.createDelegate(fn,this);
408         // private listeners that are not copied to GTk.
409         
410                 if (!this.el) {
411                         print('missing el?');
412                         print(fn);
413                         print(JSON.stringify(this.cfg));
414                         }
415                 
416                 
417         if (typeof(Seed) != 'undefined') {
418           //   Seed.print(typeof(_li));
419             this.el.signal[sig].connect(_li);
420         } else {
421             this.el.connect( sig, _li);
422         }
423              
424         
425     },
426      /**
427       * @method get
428       * Finds an object in the child elements using xid of object.
429       * prefix with '.' to look up the tree.. 
430       * prefix with multiple '..' to look further up..
431       * prefix with '/' to look from the top, eg. '^LeftTree.model'
432       * 
433       * @param {String} name name of signal
434       * @return  {XObject|false} the object if found.
435       */
436     get : function(xid)
437     {
438         XObject.log("SEARCH FOR " + xid + " in " + this.id);
439         var ret=  false;
440         var oid = '' + xid;
441         if (!xid.length) {
442             throw {
443                 name: "ArgumentError", 
444                 message : "ID not found : empty id"
445             }
446         }
447         
448         if (xid[0] == '.') {
449             return this.parent.get(xid.substring(1));
450         }
451         if (xid[0] == '/') {
452             
453             if (typeof(XObject.cache[xid]) != 'undefined') {
454                 return XObject.cache[xid]; 
455             }
456             if (xid.indexOf('.') > -1) {
457                 
458                 var child = xid.split('.');
459                 var nxid = child.shift();
460                     
461                 child = child.join('.');
462                 if (typeof(XObject.cache[nxid]) != 'undefined') {
463                     return XObject.cache[nxid].get(child);
464                 }
465                 
466                 
467             }
468             var e = this;
469             while (e.parent) {
470                 e = e.parent;
471             }
472             
473             try {
474                 ret = e.get(xid.substring(1));
475             } catch (ex) { }
476             
477             if (!ret) {
478                 throw {
479                     name: "ArgumentError", 
480                     message : "ID not found : " + oid
481                 }
482             }
483             XObject.cache[xid] = ret;
484             return XObject.cache[xid];
485         }
486         var child = false;
487         
488         if (xid.indexOf('.') > -1) {
489             child = xid.split('.');
490             xid = child.shift();
491             
492             child = child.join('.');
493             
494         }
495         if (xid == this.id) {
496             try {
497                 return child === false ? this : this.get(child);
498             } catch (ex) {
499                 throw {
500                     name: "ArgumentError", 
501                     message : "ID not found : " + oid
502                 }
503             }
504             
505         }
506         
507         
508         this.items.forEach(function(ch) {
509             if (ret) {
510                 return;
511             }
512             if (ch.id == xid) {
513                 ret = ch;
514             }
515         })
516         if (ret) {
517             try {
518                 return child === false ? ret : ret.get(child);
519             } catch (ex) {
520                 throw {
521                     name: "ArgumentError", 
522                     message : "ID not found : " + oid
523                 }
524             }
525             
526         }
527         // iterate children.
528         var _this = this;
529         this.items.forEach(function(ch) {
530             if (ret) {
531                 return;
532             }
533             if (!ch.get) {
534                 XObject.error("invalid item...");
535                 imports.console.dump(_this);
536                 Seed.quit();
537             }
538             try {
539                 ret = ch.get(xid);
540             } catch (ex) { }
541             
542             
543         });
544         if (!ret) {
545             throw {
546                 name: "ArgumentError", 
547                 message : "ID not found : " + oid
548             }
549         }
550         try {
551             return child === false ? ret : ret.get(child);
552         } catch (ex) {
553             throw {
554                 name: "ArgumentError", 
555                 message : "ID not found : " + oid
556             }
557         }
558     }
559       
560       
561
562          
563      
564 /**
565  * Copies all the properties of config to obj.
566  *
567  * Pretty much the same as JQuery/Prototype.. or Roo.apply
568  * @param {Object} obj The receiver of the properties
569  * @param {Object} config The source of the properties
570  * @param {Object} defaults A different object that will also be applied for default values
571  * @return {Object} returns obj
572  * @member XObject extend
573  */
574
575
576 XObject.extend = function(o, c, defaults){
577     if(defaults){
578         // no "this" reference for friendly out of scope calls
579         XObject.extend(o, defaults);
580     }
581     if(o && c && typeof c == 'object'){
582         for(var p in c){
583             o[p] = c[p];
584         }
585     }
586     return o;
587 };
588
589 XObject.extend(XObject,
590 {
591      
592     /**
593      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
594      * 
595      */
596     debug : true,
597     /**
598      * @property {Object} cache - cache of object ids
599      * 
600      */
601     cache: { },
602     /**
603      * Empty function
604      * 
605      */
606     emptyFn : function () { },
607       
608       
609       
610     /**
611      * Debug Logging
612      * @param {String|Object} output String to print.
613      */
614     log : function(output)
615     {
616         if (!this.debug) {
617             return;
618         }
619         print("LOG:" + output);  
620     },
621      
622     /**
623      * Error Logging
624      * @param {String|Object} output String to print.
625      */
626     error : function(output)
627     {
628         print("ERROR: " + output);  
629     },
630     /**
631      * fatal error
632      * @param {String|Object} output String to print.
633      */
634     fatal : function(output)
635     {
636         
637         throw {
638                 name: "ArgumentError", 
639                 message : output
640                     
641             }
642     },
643    
644     /**
645      * Copies all the properties of config to obj, if the do not exist.
646      * @param {Object} obj The receiver of the properties
647      * @param {Object} config The source of the properties
648      * @return {Object} returns obj
649      * @member Object extendIf
650      */
651
652
653     extendIf : function(o, c)
654     {
655
656         if(!o || !c || typeof c != 'object'){
657             return o;
658         }
659         for(var p in c){
660             if (typeof(o[p]) != 'undefined') {
661                 continue;
662             }
663             o[p] = c[p];
664         }
665         return o;
666     },
667
668  
669
670     /**
671      * Extends one class with another class and optionally overrides members with the passed literal. This class
672      * also adds the function "override()" to the class that can be used to override
673      * members on an instance.
674      *
675      * usage:
676      * MyObject = Object.define(
677      *     function(...) {
678      *          ....
679      *     },
680      *     parentClass, // or Object
681      *     {
682      *        ... methods and properties.
683      *     }
684      * });
685      * @param {Function} constructor The class inheriting the functionality
686      * @param {Object} superclass The class being extended
687      * @param {Object} overrides (optional) A literal with members
688      * @return {Function} constructor (eg. class
689      * @method define
690      */
691     define : function()
692     {
693         // inline overrides
694         var io = function(o){
695             for(var m in o){
696                 this[m] = o[m];
697             }
698         };
699         return function(constructor, parentClass, overrides) {
700             if (typeof(parentClass) == 'undefined') {
701                 XObject.error("XObject.define: Missing parentClass: when applying: " );
702                 XObject.error(new String(constructor));
703                 Seed.quit(); 
704             }
705             if (typeof(parentClass.prototype) == 'undefined') {
706                 XObject.error("Missing protype: when applying: " );
707                 XObject.error(new String(constructor));
708                 XObject.error(new String(parentClass));
709                 Seed.quit(); 
710             }
711             var F = function(){};
712             var sbp;
713             var spp = parentClass.prototype;
714             
715             F.prototype = spp;
716             sbp = constructor.prototype = new F();
717             sbp.constructor=constructor;
718             constructor.superclass=spp;
719
720             // extends Object.
721             if(spp.constructor == Object.prototype.constructor){
722                 spp.constructor=parentClass;
723             }
724             
725             constructor.override = function(o){
726                 Object.extend(constructor.prototype, o);
727             };
728             sbp.override = io;
729             XObject.extend(constructor.prototype, overrides);
730             return constructor;
731         };
732     }(),
733
734          
735     /**
736      * returns a list of keys of the object.
737      * @param {Object} obj object to inspect
738      * @return {Array} returns list of kyes
739      * @member XObject keys
740      */
741     keys : function(o)
742     {
743         var ret = [];
744         for(var i in o) {
745             ret.push(i);
746         }
747         return ret;
748     },
749     /**
750      * return the Gobject name of a constructor - does not appear to work on structs..
751      * @param {Object} gobject ctr
752      * @return {String} returns name
753      * @member XObject type
754      */
755     type : function(o)
756     {
757         if (typeof(o) == 'object') {
758             return GObject.type_name(o.type);
759            // print("GNAME:" +gname + " GTYPE:"+cfg.xtype.type);
760         }
761         return 'unknown';
762     },
763     /**
764      * return the XObjectBase class for a cfg (which includes an xtype)
765      * @param {Object} configuration.
766      * @return {function} constructor
767      * @member XObject baseXObject
768      */
769     baseXObject : function(cfg)
770     {
771           try {
772             // loocks for XObject/Gtk/TreeView.js [   TreeView = { .... } ]
773             // xns is not a string!!!?
774             var gname = false;
775             if (typeof(cfg.xtype) == 'object') {
776                 gname = XObject.type(cfg.xtype);
777             
778             }
779             if (typeof(cfg.xtype) == 'string') {
780                 gname  = cfg.xtype;
781             }
782             
783             XObject.log("TRYING BASE OBJECT : " + gname);
784                           
785             // in the situation where we have been called and there is a base object
786             // defining the behavior..
787             // then we should copy the prototypes from the base object into this..
788             
789             // see if file exists???
790             
791             var base = gname  ? imports.XObjectBase[gname][gname] : false;
792             return base;
793             
794         } catch (e) {
795             // if debug?
796             XObject.log("error finding " + gname + " - " + e.toString());
797             return false;
798         }
799         
800         
801     },
802     
803     /**
804      * @member XObject createDelegate
805      * creates a delage metdhod
806      * @param {Function} method to wrap
807      * @param {Object} scope 
808      * @param {Array} args to add
809      * @param {Boolean|Number} append arguments or replace after N arguments.
810      * @return {Function} returns the delegate
811      */
812
813     createDelegate : function(method, obj, args, appendArgs){
814         
815         return function() {
816             XObject.log("CALL: " + obj.id + ':'+ method.id);
817             
818             var callArgs = args || arguments;
819             if(appendArgs === true){
820                 callArgs = Array.prototype.slice.call(arguments, 0);
821                 callArgs = callArgs.concat(args);
822             }else if(typeof appendArgs == "number"){
823                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
824                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
825                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
826                 }
827                 return method.apply(obj || window, callArgs);
828             };
829     }
830     
831 });