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