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