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