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