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