JsTemplate/Link.js
[gnome.introspection-doc-generator] / XObject.js
1 //<script type="text/javascript">
2
3 /**
4  * XObject
5  * Yet another attempt to create a usable object construction library for seed..
6  * 
7  * Why is this useful?
8  * A) It turns rather messy code into a tree structure, making it easy to find code relating to 
9  *    an interface element
10  * B) In theory it should be gjs/Seed compatible..
11  * C) It provides getElementById style lookups for elements.
12  * D) It provides classic OO constructors for Javascript (extend/define)
13  * E) It does not modify any buildin prototypes.. 
14  *
15  * Extend this.. to use it's wonderful features..
16  * 
17  * normal usage:
18  * XObject = imports.XObject.XObject;
19  * 
20  * Xyz = new XObject({
21  *     xtype: Gtk.Window,
22  *     id : 'window',
23  *     items : [
24  *     
25  *     ]
26  *  });
27  *  Xyz.init(); // create and show.
28  * 
29  * 
30  * 
31  * @arg xtype {String|Function} constructor or string.
32  * @arg id {String}  (optional) id for registry
33  * @arg xns {String|Object}   (optional) namespace eg. Gtk or 'Gtk' - used with xtype.
34  * @arg items {Array}   (optional) list of child elements which will be constructed.. using XObject
35  * @arg listeners {Object}   (optional) map Gobject signals to functions
36  * @arg pack {Function|String|Array}   (optional) how this object gets added to it's parent
37  * @arg el {Object}   (optional) premade GObject
38  * 
39  *  --- needs a xdebug option!
40  * 
41  * 
42  * He's some questions.
43  * - should we generate ID's for all elements? (if so we probably need to garbage collect)
44  * - should we have a special property to use as the constructor / gobject.properties rather
45  *   than sending all basic types to this?
46  * 
47  * 
48  */
49
50 function XObject (cfg) {
51     // first apply cfg if set.
52     this.config = cfg;
53     if (cfg.init) {
54         this.init = cfg.init; // override!
55     }
56     
57     
58 }
59
60
61
62 XObject.prototype = {
63     /**
64      * @property el {GObject} the Gtk / etc. element.
65      */
66     el : false, 
67     /*
68      * @property items {Array} list of sub elements
69      */
70     /**
71      * @property parent {XObject} parent Element
72      */
73      
74      /**
75      * @property config {Object} the construction configuration.
76      */
77      /**
78       * @method init
79       * Initializes the Element (el) hooks up all the listeners
80       * and packs the children.
81       * you can override this, in child objects, then 
82       * do this to do thi initaliztion.
83       * 
84       * XObject.prototype.init.call(this); 
85       * 
86       */ 
87     init : function()
88     {
89         var cfg = this.config;
90     
91         print("new xobj?"  + XObject.keys(cfg).join(','));
92         //print(cfg);
93         o =  {};
94         
95         cfg.items = cfg.items || [];
96         
97         XObject.extend(o, cfg); // copy everything into o.
98         
99         o.pack = typeof(o.pack) == 'undefined' ? 'add' : o.pack;
100         
101         XObject.extend(this, o);
102
103         // remove items.
104         
105         this.listeners = this.listeners || {}; 
106         this.items = [];
107         
108         // remove objects/functions from o, so they can be sent to the contructor.
109         for (var i in o) {
110             if ((typeof(o[i]) == 'object') || 
111                 (typeof(o[i]) == 'function') || 
112                 i == 'pack' ||
113                 i == 'id' ||
114                 i == 'xtype' ||
115                 i == 'xdebug' ||
116                 i == 'xns'
117             ) {
118                 delete o[i];
119             }
120         }
121         
122         // do we need to call 'beforeInit here?'
123          
124         // handle include?
125         //if ((this.xtype == 'Include')) {
126         //    o = this.pre_registry[cls];
127         //}
128         var isSeed = typeof(Seed) != 'undefined';
129          
130         // xtype= Gtk.Menu ?? what about c_new stuff?
131         print(this.xtype);
132         if (typeof(this.xtype) == 'function') {
133             print("func?"  + XObject.keys(o).join(','));
134             this.el = this.el ||   this.xtype(o);
135         }
136         if (typeof(this.xtype) == 'object') {
137             print("obj?"  + XObject.keys(o).join(','));
138             this.el = this.el ||  new this.xtype(o);
139         }
140         //print(this.el);
141         if (!this.el && o.xns) {
142             
143             var NS = imports.gi[o.xns];
144             if (!NS) {
145                 Seed.print('Invalid xns: ' + o.xns);
146             }
147             constructor = NS[o.xtype];
148             if (!constructor) {
149                 Seed.print('Invalid xtype: ' + o.xns + '.' + o.xtype);
150             }
151             this.el  =   isSeed ? new constructor(o) : new constructor();
152             
153         }
154         // always overlay props..
155         for (var i in o) {
156             this.el[i] = o[i];
157         }
158         // register it!
159         //if (o.xnsid  && o.id) {
160          //   XObject.registry = XObject.registry || { };
161          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
162          //   XObject.registry[o.xnsid][o.id] = this;
163         //}
164         
165         cfg.items.forEach(this.addItem, this);
166         
167         for (var i in this.listeners) {
168             this.addListener(i, this.listeners[i]);
169         }
170         // delete this.listeners ?
171         
172         
173         // do we need to call 'init here?'
174     },
175       
176      
177      /**
178       * @method addItem
179       * Adds an item to the object using a new XObject
180       * uses pack property to determine how to add it.
181       * @arg cfg {Object} same as XObject constructor.
182       */
183     addItem : function(o) {
184         
185          
186         var item = (o.constructor == XObject) ? o : new XObject(o);
187         item.init();
188         item.parent = this;
189         this.items.push(item);
190         
191         if (item.pack===false) {  // no 
192             return;
193         }
194         if (typeof(item.pack) == 'function') {
195             // parent, child
196             item.pack.apply(o, [ o , o.items[i] ]);
197             item.parent = this;
198             return;
199         }
200         var args = [];
201         var pack_m  = false;
202         if (typeof(item.pack) == 'string') {
203             pack_m = item.pack;
204         } else {
205             pack_m = item.pack.shift();
206             args = item.pack;
207         }
208         
209         // handle error.
210         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
211             Seed.print('pack method not available : ' + this.xtype + '.' +  pack_m);
212             return;
213         }
214         
215         
216         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
217
218         args.unshift(item.el);
219         print('[' + args.join(',') +']');
220         //Seed.print('args: ' + args.length);
221         if (pack_m) {
222             this.el[pack_m].apply(this.el, args);
223         }
224         
225        
226         
227     },
228     /**
229       * @method addListener
230       * Connects a method to a signal. (gjs/Seed aware)
231       * 
232       * @arg sig  {String} name of signal
233       * @arg fn  {Function} handler.
234       */
235     addListener  : function(sig, fn) 
236     {
237  
238         Seed.print("Add signal " + sig);
239  
240         var _li = XObject.createDelegate(fn,this);
241         // private listeners that are not copied to GTk.
242         
243         if (typeof(Seed) != 'undefined') {
244           //   Seed.print(typeof(_li));
245             this.el.signal[sig].connect(_li);
246         } else {
247             this.el.connect( sig, _li);
248         }
249              
250         
251     },
252      /**
253       * @method get
254       * Finds an object in the child elements using xid of object.
255       * prefix with '.' to look up the tree.. multiple '..' to look further up..
256       * 
257       * @arg name  {String} name of signal
258       * @return   {XObject|false} the object if found.
259       */
260     get : function(xid)
261     {
262         var ret=  false;
263         if (xid[0] == '.') {
264             return this.parent.get(xid.substring(1));
265         }
266         
267         
268         this.items.forEach(function(ch) {
269             if (ch.id == xid) {
270                 ret = ch;
271                 return true;
272             }
273         })
274         if (ret) {
275             return ret;
276         }
277         // iterate children.
278         this.items.forEach(function(ch) {
279             ret = ch.get(xid);
280             if (ret) {
281                 return true;
282             }
283         })
284         return ret;
285     }
286       
287       
288
289          
290         
291 /**
292  * Copies all the properties of config to obj.
293  *
294  * Pretty much the same as JQuery/Prototype..
295  * @param {Object} obj The receiver of the properties
296  * @param {Object} config The source of the properties
297  * @param {Object} defaults A different object that will also be applied for default values
298  * @return {Object} returns obj
299  * @member XObject extend
300  */
301
302
303 XObject.extend = function(o, c, defaults){
304     if(defaults){
305         // no "this" reference for friendly out of scope calls
306         XObject.extend(o, defaults);
307     }
308     if(o && c && typeof c == 'object'){
309         for(var p in c){
310             o[p] = c[p];
311         }
312     }
313     return o;
314 };
315
316 XObject.extend(XObject,
317 {
318     /**
319      * Copies all the properties of config to obj, if the do not exist.
320      * @param {Object} obj The receiver of the properties
321      * @param {Object} config The source of the properties
322      * @return {Object} returns obj
323      * @member Object extendIf
324      */
325
326
327     extendIf : function(o, c){
328
329         if(!o || !c || typeof c != 'object'){
330             return o;
331         }
332         for(var p in c){
333             if (typeof(o[p]) != 'undefined') {
334                 continue;
335             }
336             o[p] = c[p];
337         }
338         return o;
339     },
340
341  
342
343     /**
344      * Extends one class with another class and optionally overrides members with the passed literal. This class
345      * also adds the function "override()" to the class that can be used to override
346      * members on an instance.
347      *
348      * usage:
349      * MyObject = Object.define(
350      *     function(...) {
351      *          ....
352      *     },
353      *     parentClass, // or Object
354      *     {
355      *        ... methods and properties.
356      *     }
357      * });
358      * @param {Function} constructor The class inheriting the functionality
359      * @param {Object} superclass The class being extended
360      * @param {Object} overrides (optional) A literal with members
361      * @return {Function} constructor (eg. class
362      * @method define
363      */
364     define : function(){
365         // inline overrides
366         var io = function(o){
367             for(var m in o){
368                 this[m] = o[m];
369             }
370         };
371         return function(sb, sp, overrides) {
372             if (typeof(sp) == 'undefined') {
373                 // error condition - try and dump..
374                 throw "Missing superclass: when applying: " + sb
375             }
376
377             var F = function(){}, sbp, spp = sp.prototype;
378             F.prototype = spp;
379             sbp = sb.prototype = new F();
380             sbp.constructor=sb;
381             sb.superclass=spp;
382
383             // extends Object.
384             if(spp.constructor == Object.prototype.constructor){
385                 spp.constructor=sp;
386             }
387             
388             sb.override = function(o){
389                 Object.extend(sb.prototype, o);
390             };
391             sbp.override = io;
392             XObject.extend(sb.prototype, overrides);
393             return sb;
394         };
395     }(),
396
397          
398     /**
399      * returns a list of keys of the object.
400      * @param {Object} obj object to inspect
401      * @return {Array} returns list of kyes
402      * @member XObject keys
403      */
404     keys : function(o)
405     {
406         var ret = [];
407         for(var i in o) {
408             ret.push(i);
409         }
410         return ret;
411     },
412       
413     /**
414      * @member XObject createDelegate
415      * creates a delage metdhod
416      * @param {Function} method to wrap
417      * @param {Object} scope 
418      * @param {Array} args to add
419      * @param {Boolean|Number} append arguments or replace after N arguments.
420      * @return {Function} returns the delegate
421      */
422
423     createDelegate : function(method, obj, args, appendArgs){
424         
425         return function() {
426             var callArgs = args || arguments;
427             if(appendArgs === true){
428                 callArgs = Array.prototype.slice.call(arguments, 0);
429                 callArgs = callArgs.concat(args);
430             }else if(typeof appendArgs == "number"){
431                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
432                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
433                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
434                 }
435                 return method.apply(obj || window, callArgs);
436             };
437     }
438     
439 });