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