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