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 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  * 
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 = {}; // used to initialize GObject
62     
63     this.cfg = XObject.extend({}, cfg); // used to store original configuration.. for referencing..
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     this.constructor = XObject;
69     
70     
71     
72     // start by seeing if we have a base class....
73     try {
74         // loocks for XObject/Gtk/TreeView.js [   TreeView = { .... } ]
75         // xns is not a string!!!?
76         var gname = false;
77         if (typeof(cfg.xtype) == 'object') {
78             gname = GObject.type_name(cfg.xtype.type);
79            // print("GNAME:" +gname + " GTYPE:"+cfg.xtype.type);
80         }
81         
82         var base = gname  ? imports.XObjectBase[gname][gname] : false;
83         if (base) {
84           //  print("Overlaying XOBJBECT-BASE."  + cfg.xtype);
85             XObject.extend(this,base);
86         }
87         
88     } catch (e) {
89         // if debug?
90         XObject.log("error finding " + gname + " - " + e.toString());
91     }
92     
93     
94     // copy down all elements into self..
95     // make an extra copy in this.config?? - which is the one used in the constructor later
96     
97     for (var i in cfg) {
98         this[i] = cfg[i];
99         if (typeof(cfg[i]) == 'function') { // do we skip objects.
100             continue;
101         }
102         // these properties are not copied to cfg.
103         if (    i == 'pack' ||
104                 i == 'items' ||
105                 i == 'id' ||
106                 i == 'xtype' ||
107                 i == 'xdebug' ||
108                 i == 'xns') {
109             continue;
110         }
111         
112         
113         this.config[i] = cfg[i];
114     }
115     
116     
117     this.items = this.items || [];
118     
119     
120     // pack can be false!
121     if (typeof(this.pack) == 'undefined') {
122         
123         this.pack = [ 'add' ]
124         /*
125         var Gtk  = imports.gi.Gtk;
126         switch (true) {
127             // any others!!
128             case (this.xtype == Gtk.MenuItem):  this.pack = [ 'append' ]; break;
129             
130         }
131         */
132         
133     }
134     
135     // interesting question should we call constructor on items here...
136     // as the real work is done in init anyway..
137     var _this= this;
138     
139     var items = [];
140     this.items.forEach(function(i) {
141         items.push(i);
142     });
143     this.items = [];
144     // create XObject for all the children.
145     items.forEach(function(i,n) {
146          
147         var item = (i.constructor == XObject) ? o : new XObject(i);
148         item.parent = _this;
149         _this.items.push(item);
150         //_this.addItem(i);
151     });
152     if (this.onConstruct) {
153         this.onConstruct.call(this);
154     }
155     
156 }
157
158
159
160 XObject.prototype = {
161     /**
162      * @property el {GObject} the Gtk / etc. element.
163      */
164     el : false, 
165     /*
166      * @property items {Array} list of sub elements
167      */
168     /**
169      * @property parent {XObject} parent Element
170      */
171      
172      /**
173      * @property config {Object} the construction configuration.
174      */
175      /**
176       * @method init
177       * Initializes the Element (el) hooks up all the listeners
178       * and packs the children.
179       * you can override this, in child objects, then 
180       * do this to do thi initaliztion.
181       * 
182       * XObject.prototype.init.call(this); 
183       * 
184       */ 
185     init : function()
186     {
187          
188        // var items = [];
189         //this.items.forEach(function(i) {
190         //    items.push(i);
191         //});
192         // remove items.
193         this.listeners = this.listeners || {}; 
194         //this.items = [];
195          
196         // do we need to call 'beforeInit here?'
197          
198         // handle include?
199         //if ((this.xtype == 'Include')) {
200         //    o = this.pre_registry[cls];
201         //}
202         var isSeed = typeof(Seed) != 'undefined';
203          
204         // xtype= Gtk.Menu ?? what about c_new stuff?
205         XObject.log("init: ID:"+ this.id +" typeof(xtype): "  + typeof(this.xtype));
206         if (!this.el && typeof(this.xtype) == 'function') {
207             XObject.log("func?"  + XObject.keys(this.config).join(','));
208             this.el = this.xtype(this.config);
209            
210         }
211         if (!this.el && typeof(this.xtype) == 'object') {
212             XObject.log("obj?"  + XObject.keys(this.config).join(','));
213             this.el = new (this.xtype)(this.config);
214       
215         }
216         //print(this.el);
217         if (!this.el && this.xns) {
218             
219             var NS = imports.gi[this.xns];
220             if (!NS) {
221                 XObject.error('Invalid xns: ' + this.xns, true);
222             }
223             constructor = NS[this.xtype];
224             if (!constructor) {
225                 XObject.error('Invalid xtype: ' + this.xns + '.' + this.xtype);
226             }
227             this.el  =   isSeed ? new constructor(this.config) : new constructor();
228             
229         }
230         XObject.log("init: ID:"+ this.id +" typeof(el):" + this.el);
231         
232         // always overlay props..
233         // check for 'write' on object..
234         /*
235         if (typeof(XObject.writeablePropsCache[this.xtype.type]) == 'undefined') {
236                 
237             var gi = GIRepository.IRepository.get_default();
238             var ty = gi.find_by_gtype(this.xtype.type);
239             var write = [];
240             for (var i =0; i < GIRepository.object_info_get_n_properties(ty);i++) {
241                 var p =   GIRepository.object_info_get_property(ty,i);
242                 if (GIRepository.property_info_get_flags(p) & 2) {
243                     write.push(GIRepository.base_info_get_name(p));
244                 }
245             }
246             XObject.writeablePropsCache[this.xtype.type] = write;
247             print(write.join(", "));
248         }
249         
250         */
251         
252          
253         for (var i in this.config) {
254             if (i == 'type') { // problem with Gtk.Window... - not decided on a better way to handle this.
255                 continue;
256             }
257             if (i == 'buttons') { // problem with Gtk.MessageDialog..
258                 continue;
259             }
260             if (i[0] == '.') { // parent? - 
261                 continue;
262             }
263             this.el[i] = this.config[i];
264         }
265         
266         // register it!
267         //if (o.xnsid  && o.id) {
268          //   XObject.registry = XObject.registry || { };
269          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
270          //   XObject.registry[o.xnsid][o.id] = this;
271         //}
272         
273         var type = this.xtype.type ? GObject.type_name(this.xtype.type) : '';
274         XObject.log("add children to " + type);
275         
276         var _this=this;
277         this.items.forEach(function(i,n) {
278             _this.addItem(i,n);
279         })
280             
281         
282         for (var i in this.listeners) {
283             this.addListener(i, this.listeners[i]);
284         }
285         
286         this.init = XObject.emptyFn;
287            
288         // delete this.listeners ?
289         // do again so child props work!
290        
291         // do we need to call 'init here?'
292     },
293       
294      
295      /**
296       * @method addItem
297       * Adds an item to the object using a new XObject
298       * uses pack property to determine how to add it.
299       * @arg cfg {Object} same as XObject constructor.
300       */
301     addItem : function(item, pos) 
302     {
303         
304         if (typeof(item) == 'undefined') {
305             XObject.error("Invalid Item added to this!");
306             imports.console.dump(this.cfg);
307             Seed.quit();
308         }
309         // what about extended items!?!?!?
310        
311         item.init();
312         //print("CTR:PROTO:" + ( item.id ? item.id : '??'));
313        // print("addItem - call init [" + item.pack.join(',') + ']');
314         if (!item.el) {
315             XObject.error("NO EL!");
316             imports.console.dump(item);
317             Seed.quit();
318         }
319         print(XObject.type(this.xtype) + ":pack=" + item.pack);
320         
321         if (item.pack===false) {  // no packing.. various items have this ..
322             return;
323         }
324         
325         if (typeof(item.pack) == 'function') { // pack is a function..
326             // parent, child
327             item.pack.apply(item, [ this , item  ]);
328             item.parent = this;
329             return;
330         }
331         
332         // pack =  'add,x,y'
333         var args = [];
334         var pack_m  = false;
335         if (typeof(item.pack) == 'string') {
336              
337             item.pack.split(',').forEach(function(e, i) {
338                 
339                 if (e == 'false') { args.push( false); return; }
340                 if (e == 'true') {  args.push( true);  return; }
341                 if (!isNaN(parseInt(e))) { args.push( parseInt(e)); return; }
342                 args.push(e);
343             });
344             //print(args.join(","));
345             
346             pack_m = args.shift();
347         } else {
348             pack_m = item.pack.shift();
349             args = item.pack;
350         }
351         
352         // handle error.
353         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
354             
355             throw {
356                 name: "ArgumentError", 
357                 message : 'pack method not available : ' + this.id + " : " + this.xtype + '.' +  pack_m + " ADDING " + item.el
358                     
359             }
360            
361             return;
362         }
363         
364         
365         // finally call the pack method 
366         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
367         
368         args.unshift(item.el);
369         
370          
371         
372         
373         
374         XObject.log(pack_m + '[' + args.join(',') +']');
375         //Seed.print('args: ' + args.length);
376         if (pack_m) {
377             this.el[pack_m].apply(this.el, args);
378         }
379         
380        
381         
382     },
383     /**
384       * @method addListener
385       * Connects a method to a signal. (gjs/Seed aware)
386       * 
387       * @arg sig  {String} name of signal
388       * @arg fn  {Function} handler.
389       */
390     addListener  : function(sig, fn) 
391     {
392  
393         XObject.log("Add signal " + sig);
394         fn.id= sig;
395         var _li = XObject.createDelegate(fn,this);
396         // private listeners that are not copied to GTk.
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       * @arg name  {String} 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
732      * @param {Object} gobject ctr
733      * @return {String} returns name
734      * @member XObject keys
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      * @member XObject createDelegate
746      * creates a delage metdhod
747      * @param {Function} method to wrap
748      * @param {Object} scope 
749      * @param {Array} args to add
750      * @param {Boolean|Number} append arguments or replace after N arguments.
751      * @return {Function} returns the delegate
752      */
753
754     createDelegate : function(method, obj, args, appendArgs){
755         
756         return function() {
757             XObject.log("CALL: " + obj.id + ':'+ method.id);
758             
759             var callArgs = args || arguments;
760             if(appendArgs === true){
761                 callArgs = Array.prototype.slice.call(arguments, 0);
762                 callArgs = callArgs.concat(args);
763             }else if(typeof appendArgs == "number"){
764                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
765                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
766                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
767                 }
768                 return method.apply(obj || window, callArgs);
769             };
770     }
771     
772 });