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