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