XObject.js
[app.Builder.js] / 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 XObject/[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  * 
51  * 
52  * 
53  */
54
55 function XObject (cfg) {
56     // first apply cfg if set.
57       //print("new XOBJECT!!!");
58       
59     //print ("XObject ctr");
60       
61     this.config = {};
62     this.constructor = XObject;
63     
64     
65     
66     // start by seeing if we have a base class....
67     try {
68         // loocks for XObject/Gtk/TreeView.js [   TreeView = { .... } ]
69         // xns is not a string!!!?
70         var gname = false;
71         if (typeof(cfg.xtype) == 'object') {
72             gname = GObject.type_name(cfg.xtype.type);
73            // print("GNAME:" +gname + " GTYPE:"+cfg.xtype.type);
74         }
75         
76         var base = gname  ? imports.XObjectBase[gname][gname] : false;
77         if (base) {
78           //  print("Overlaying XOBJBECT-BASE."  + cfg.xtype);
79             XObject.extend(this,base);
80         }
81         
82     } catch (e) {
83         // if debug?
84         XObject.log("error finding " + gname + " - " + e.toString());
85     }
86     
87     
88     // copy down all elements into self..
89     
90     for (var i in cfg) {
91         this[i] = cfg[i];
92         if (typeof(cfg[i]) == 'function') { // do we skip objects.
93             continue;
94         }
95         // these properties are not copied to cfg.
96         if (    i == 'pack' ||
97                 i == 'items' ||
98                 i == 'id' ||
99                 i == 'xtype' ||
100                 i == 'xdebug' ||
101                 i == 'xns') {
102             continue;
103         }
104         
105         
106         this.config[i] = cfg[i];
107     }
108     
109     
110     this.items = this.items || [];
111     
112     
113     // pack can be false!
114     if (typeof(this.pack) == 'undefined') {
115         
116         this.pack = [ 'add' ]
117         /*
118         var Gtk  = imports.gi.Gtk;
119         switch (true) {
120             // any others!!
121             case (this.xtype == Gtk.MenuItem):  this.pack = [ 'append' ]; break;
122             
123         }
124         */
125         
126     }
127     
128     // interesting question should we call constructor on items here...
129     // as the real work is done in init anyway..
130     var _this= this;
131     
132     var items = [];
133     this.items.forEach(function(i) {
134         items.push(i);
135     });
136     this.items = [];
137     items.forEach(function(i,n) {
138          
139         var item = (i.constructor == XObject) ? o : new XObject(i);
140         item.parent = _this;
141         _this.items.push(item);
142         //_this.addItem(i);
143     });
144     if (this.onConstruct) {
145         this.onConstruct.call(this);
146     }
147     
148 }
149
150
151
152 XObject.prototype = {
153     /**
154      * @property el {GObject} the Gtk / etc. element.
155      */
156     el : false, 
157     /*
158      * @property items {Array} list of sub elements
159      */
160     /**
161      * @property parent {XObject} parent Element
162      */
163      
164      /**
165      * @property config {Object} the construction configuration.
166      */
167      /**
168       * @method init
169       * Initializes the Element (el) hooks up all the listeners
170       * and packs the children.
171       * you can override this, in child objects, then 
172       * do this to do thi initaliztion.
173       * 
174       * XObject.prototype.init.call(this); 
175       * 
176       */ 
177     init : function()
178     {
179          
180        // var items = [];
181         //this.items.forEach(function(i) {
182         //    items.push(i);
183         //});
184         // remove items.
185         this.listeners = this.listeners || {}; 
186         //this.items = [];
187          
188         // do we need to call 'beforeInit here?'
189          
190         // handle include?
191         //if ((this.xtype == 'Include')) {
192         //    o = this.pre_registry[cls];
193         //}
194         var isSeed = typeof(Seed) != 'undefined';
195          
196         // xtype= Gtk.Menu ?? what about c_new stuff?
197         XObject.log("init: ID:"+ this.id +" typeof(xtype): "  + typeof(this.xtype));
198         if (!this.el && typeof(this.xtype) == 'function') {
199             XObject.log("func?"  + XObject.keys(this.config).join(','));
200             this.el = this.xtype(this.config);
201            
202         }
203         if (!this.el && typeof(this.xtype) == 'object') {
204             XObject.log("obj?"  + XObject.keys(this.config).join(','));
205             this.el = new (this.xtype)(this.config);
206       
207         }
208         //print(this.el);
209         if (!this.el && this.xns) {
210             
211             var NS = imports.gi[this.xns];
212             if (!NS) {
213                 XObject.error('Invalid xns: ' + this.xns, true);
214             }
215             constructor = NS[this.xtype];
216             if (!constructor) {
217                 XObject.error('Invalid xtype: ' + this.xns + '.' + this.xtype);
218             }
219             this.el  =   isSeed ? new constructor(this.config) : new constructor();
220             
221         }
222         XObject.log("init: ID:"+ this.id +" typeof(el):" + this.el);
223         
224         // always overlay props..
225         // check for 'write' on object..
226         /*
227         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
228                 
229             var gi = GIRepository.IRepository.get_default();
230             var ty = gi.find_by_gtype(this.xtype.type);
231             var write = [];
232             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
233                 var p =   GIRepository.object_info_get_property(ty,i);
234                 if (GIRepository.property_info_get_flags(p) & 2) {
235                     write.push(GIRepository.base_info_get_name(p));
236                 }
237             }
238             XObject.writeablePropsCache[this.xtype.type] = write;
239             print(write.join(", "));
240         }
241         
242         */
243         
244          
245         for (var i in this.config) {
246             if (i == 'type') { // problem with Gtk.Window... - not decided on a better way to handle this.
247                 continue;
248             }
249             if (i == 'buttons') { // problem with Gtk.MessageDialog..
250                 continue;
251             }
252             if (i[0] == '.') { // parent? - 
253                 continue;
254             }
255             this.el[i] = this.config[i];
256         }
257         
258         // register it!
259         //if (o.xnsid  && o.id) {
260          //   XObject.registry = XObject.registry || { };
261          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
262          //   XObject.registry[o.xnsid][o.id] = this;
263         //}
264         
265         var type = this.xtype.type ? GObject.type_name(this.xtype.type) : '';
266         XObject.log("add children to " + type);
267         
268         var _this=this;
269         this.items.forEach(function(i,n) {
270             _this.addItem(i,n);
271         })
272             
273         
274         for (var i in this.listeners) {
275             this.addListener(i, this.listeners[i]);
276         }
277         
278         this.init = XObject.emptyFn;
279            
280         // delete this.listeners ?
281         // do again so child props work!
282        
283         // do we need to call 'init here?'
284     },
285       
286      
287      /**
288       * @method addItem
289       * Adds an item to the object using a new XObject
290       * uses pack property to determine how to add it.
291       * @arg cfg {Object} same as XObject constructor.
292       */
293     addItem : function(item, pos) 
294     {
295         
296         if (typeof(item) == 'undefined') {
297             XObject.error("Invalid Item added to this!");
298             imports.console.dump(this);
299             Seed.quit();
300         }
301         // what about extended items!?!?!?
302        
303         item.init();
304         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
305        // print("addItem - call init [" + item.pack.join(',') + ']');
306         if (!item.el) {
307             XObject.err("NO EL!");
308             imports.console.dump(item);
309             Seed.quit();
310         }
311          
312         
313         if (item.pack===false) {  // no packing.. various items have this ..
314             return;
315         }
316         
317         if (typeof(item.pack) == 'function') { // pack is a function..
318             // parent, child
319             item.pack.apply(item, [ this , item  ]);
320             item.parent = this;
321             return;
322         }
323         
324         // pack =  'add,x,y'
325         var args = [];
326         var pack_m  = false;
327         if (typeof(item.pack) == 'string') {
328              
329             item.pack.split(',').forEach(function(e, i) {
330                 
331                 if (e == 'false') { args.push( false); return; }
332                 if (e == 'true') {  args.push( true);  return; }
333                 if (!isNaN(parseInt(e))) { args.push( parseInt(e)); return; }
334                 args.push(e);
335             });
336             //print(args.join(","));
337             
338             pack_m = args.shift();
339         } else {
340             pack_m = item.pack.shift();
341             args = item.pack;
342         }
343         
344         // handle error.
345         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
346             
347             throw {
348                 name: "ArgumentError", 
349                 message : 'pack method not available : ' + this.id + " : " + this.xtype + '.' +  pack_m + " ADDING " + item.el
350                     
351             }
352            
353             return;
354         }
355         
356         
357         // finally call the pack method 
358         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
359         
360         args.unshift(item.el);
361         
362          
363         
364         
365         
366         XObject.log(pack_m + '[' + args.join(',') +']');
367         //Seed.print('args: ' + args.length);
368         if (pack_m) {
369             this.el[pack_m].apply(this.el, args);
370         }
371         
372        
373         
374     },
375     /**
376       * @method addListener
377       * Connects a method to a signal. (gjs/Seed aware)
378       * 
379       * @arg sig  {String} name of signal
380       * @arg fn  {Function} handler.
381       */
382     addListener  : function(sig, fn) 
383     {
384  
385         XObject.log("Add signal " + sig);
386         fn.id= sig;
387         var _li = XObject.createDelegate(fn,this);
388         // private listeners that are not copied to GTk.
389         
390         if (typeof(Seed) != 'undefined') {
391           //   Seed.print(typeof(_li));
392             this.el.signal[sig].connect(_li);
393         } else {
394             this.el.connect( sig, _li);
395         }
396              
397         
398     },
399      /**
400       * @method get
401       * Finds an object in the child elements using xid of object.
402       * prefix with '.' to look up the tree.. 
403       * prefix with multiple '..' to look further up..
404       * prefix with '/' to look from the top, eg. '^LeftTree.model'
405       * 
406       * @arg name  {String} name of signal
407       * @return   {XObject|false} the object if found.
408       */
409     get : function(xid)
410     {
411         XObject.log("SEARCH FOR " + xid + " in " + this.id);
412         var ret=  false;
413         var oid = '' + xid;
414         if (!xid.length) {
415             throw {
416                 name: "ArgumentError", 
417                 message : "ID not found : empty id"
418             }
419         }
420         
421         if (xid[0] == '.') {
422             return this.parent.get(xid.substring(1));
423         }
424         if (xid[0] == '/') {
425             
426             if (typeof(XObject.cache[xid]) != 'undefined') {
427                 return XObject.cache[xid]; 
428             }
429             if (xid.indexOf('.') > -1) {
430                 
431                 var child = xid.split('.');
432                 var nxid = child.shift();
433                     
434                 child = child.join('.');
435                 if (typeof(XObject.cache[nxid]) != 'undefined') {
436                     return XObject.cache[nxid].get(child);
437                 }
438                 
439                 
440             }
441             var e = this;
442             while (e.parent) {
443                 e = e.parent;
444             }
445             
446             try {
447                 ret = e.get(xid.substring(1));
448             } catch (ex) { }
449             
450             if (!ret) {
451                 throw {
452                     name: "ArgumentError", 
453                     message : "ID not found : " + oid
454                 }
455             }
456             XObject.cache[xid] = ret;
457             return XObject.cache[xid];
458         }
459         var child = false;
460         
461         if (xid.indexOf('.') > -1) {
462             child = xid.split('.');
463             xid = child.shift();
464             
465             child = child.join('.');
466             
467         }
468         if (xid == this.id) {
469             try {
470                 return child === false ? this : this.get(child);
471             } catch (ex) {
472                 throw {
473                     name: "ArgumentError", 
474                     message : "ID not found : " + oid
475                 }
476             }
477             
478         }
479         
480         
481         this.items.forEach(function(ch) {
482             if (ret) {
483                 return;
484             }
485             if (ch.id == xid) {
486                 ret = ch;
487             }
488         })
489         if (ret) {
490             try {
491                 return child === false ? ret : ret.get(child);
492             } catch (ex) {
493                 throw {
494                     name: "ArgumentError", 
495                     message : "ID not found : " + oid
496                 }
497             }
498             
499         }
500         // iterate children.
501         var _this = this;
502         this.items.forEach(function(ch) {
503             if (ret) {
504                 return;
505             }
506             if (!ch.get) {
507                 XObject.error("invalid item...");
508                 imports.console.dump(_this);
509                 Seed.quit();
510             }
511             try {
512                 ret = ch.get(xid);
513             } catch (ex) { }
514             
515             
516         });
517         if (!ret) {
518             throw {
519                 name: "ArgumentError", 
520                 message : "ID not found : " + oid
521             }
522         }
523         try {
524             return child === false ? ret : ret.get(child);
525         } catch (ex) {
526             throw {
527                 name: "ArgumentError", 
528                 message : "ID not found : " + oid
529             }
530         }
531     }
532       
533       
534
535          
536      
537 /**
538  * Copies all the properties of config to obj.
539  *
540  * Pretty much the same as JQuery/Prototype.. or Roo.apply
541  * @param {Object} obj The receiver of the properties
542  * @param {Object} config The source of the properties
543  * @param {Object} defaults A different object that will also be applied for default values
544  * @return {Object} returns obj
545  * @member XObject extend
546  */
547
548
549 XObject.extend = function(o, c, defaults){
550     if(defaults){
551         // no "this" reference for friendly out of scope calls
552         XObject.extend(o, defaults);
553     }
554     if(o && c && typeof c == 'object'){
555         for(var p in c){
556             o[p] = c[p];
557         }
558     }
559     return o;
560 };
561
562 XObject.extend(XObject,
563 {
564      
565     /**
566      * @property {Boolean} debug XObject  debugging.  - set to true to debug.
567      * 
568      */
569     debug : false,
570     /**
571      * @property {Object} cache - cache of object ids
572      * 
573      */
574     cache: { },
575     /**
576      * Empty function
577      * 
578      */
579     emptyFn : function () { },
580       
581       
582       
583     /**
584      * Debug Logging
585      * @param {String|Object} output String to print.
586      */
587     log : function(output)
588     {
589         if (!this.debug) {
590             return;
591         }
592         print("LOG:" + output);  
593     },
594      
595     /**
596      * Error Logging
597      * @param {String|Object} output String to print.
598      */
599     error : function(output)
600     {
601         print("ERROR: " + output);  
602     },
603      
604    
605     /**
606      * Copies all the properties of config to obj, if the do not exist.
607      * @param {Object} obj The receiver of the properties
608      * @param {Object} config The source of the properties
609      * @return {Object} returns obj
610      * @member Object extendIf
611      */
612
613
614     extendIf : function(o, c)
615     {
616
617         if(!o || !c || typeof c != 'object'){
618             return o;
619         }
620         for(var p in c){
621             if (typeof(o[p]) != 'undefined') {
622                 continue;
623             }
624             o[p] = c[p];
625         }
626         return o;
627     },
628
629  
630
631     /**
632      * Extends one class with another class and optionally overrides members with the passed literal. This class
633      * also adds the function "override()" to the class that can be used to override
634      * members on an instance.
635      *
636      * usage:
637      * MyObject = Object.define(
638      *     function(...) {
639      *          ....
640      *     },
641      *     parentClass, // or Object
642      *     {
643      *        ... methods and properties.
644      *     }
645      * });
646      * @param {Function} constructor The class inheriting the functionality
647      * @param {Object} superclass The class being extended
648      * @param {Object} overrides (optional) A literal with members
649      * @return {Function} constructor (eg. class
650      * @method define
651      */
652     define : function()
653     {
654         // inline overrides
655         var io = function(o){
656             for(var m in o){
657                 this[m] = o[m];
658             }
659         };
660         return function(constructor, parentClass, overrides) {
661             if (typeof(parentClass) == 'undefined') {
662                 XObject.error("XObject.define: Missing parentClass: when applying: " );
663                 XObject.error(new String(constructor));
664                 Seed.quit(); 
665             }
666             if (typeof(parentClass.prototype) == 'undefined') {
667                 XObject.error("Missing protype: when applying: " );
668                 XObject.error(new String(constructor));
669                 XObject.error(new String(parentClass));
670                 Seed.quit(); 
671             }
672             var F = function(){};
673             var sbp;
674             var spp = parentClass.prototype;
675             
676             F.prototype = spp;
677             sbp = constructor.prototype = new F();
678             sbp.constructor=constructor;
679             constructor.superclass=spp;
680
681             // extends Object.
682             if(spp.constructor == Object.prototype.constructor){
683                 spp.constructor=parentClass;
684             }
685             
686             constructor.override = function(o){
687                 Object.extend(constructor.prototype, o);
688             };
689             sbp.override = io;
690             XObject.extend(constructor.prototype, overrides);
691             return constructor;
692         };
693     }(),
694
695          
696     /**
697      * returns a list of keys of the object.
698      * @param {Object} obj object to inspect
699      * @return {Array} returns list of kyes
700      * @member XObject keys
701      */
702     keys : function(o)
703     {
704         var ret = [];
705         for(var i in o) {
706             ret.push(i);
707         }
708         return ret;
709     },
710       
711     /**
712      * @member XObject createDelegate
713      * creates a delage metdhod
714      * @param {Function} method to wrap
715      * @param {Object} scope 
716      * @param {Array} args to add
717      * @param {Boolean|Number} append arguments or replace after N arguments.
718      * @return {Function} returns the delegate
719      */
720
721     createDelegate : function(method, obj, args, appendArgs){
722         
723         return function() {
724             XObject.log("CALL: " + obj.id + ':'+ method.id);
725             
726             var callArgs = args || arguments;
727             if(appendArgs === true){
728                 callArgs = Array.prototype.slice.call(arguments, 0);
729                 callArgs = callArgs.concat(args);
730             }else if(typeof appendArgs == "number"){
731                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
732                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
733                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
734                 }
735                 return method.apply(obj || window, callArgs);
736             };
737     }
738     
739 });