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