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