Re-arrange files, add support for classic JS Documentor, and packer
[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         })
278         if (ret) {
279             return ret;
280         }
281         // iterate children.
282         this.items.forEach(function(ch) {
283             ret = ch.get(xid);
284             if (ret) {
285                 return true;
286             }
287         })
288         return ret;
289     }
290       
291       
292
293          
294         
295 /**
296  * Copies all the properties of config to obj.
297  *
298  * Pretty much the same as JQuery/Prototype..
299  * @param {Object} obj The receiver of the properties
300  * @param {Object} config The source of the properties
301  * @param {Object} defaults A different object that will also be applied for default values
302  * @return {Object} returns obj
303  * @member XObject extend
304  */
305
306
307 XObject.extend = function(o, c, defaults){
308     if(defaults){
309         // no "this" reference for friendly out of scope calls
310         XObject.extend(o, defaults);
311     }
312     if(o && c && typeof c == 'object'){
313         for(var p in c){
314             o[p] = c[p];
315         }
316     }
317     return o;
318 };
319
320 XObject.extend(XObject,
321 {
322     /**
323      * Copies all the properties of config to obj, if the do not exist.
324      * @param {Object} obj The receiver of the properties
325      * @param {Object} config The source of the properties
326      * @return {Object} returns obj
327      * @member Object extendIf
328      */
329
330
331     extendIf : function(o, c){
332
333         if(!o || !c || typeof c != 'object'){
334             return o;
335         }
336         for(var p in c){
337             if (typeof(o[p]) != 'undefined') {
338                 continue;
339             }
340             o[p] = c[p];
341         }
342         return o;
343     },
344
345  
346
347     /**
348      * Extends one class with another class and optionally overrides members with the passed literal. This class
349      * also adds the function "override()" to the class that can be used to override
350      * members on an instance.
351      *
352      * usage:
353      * MyObject = Object.define(
354      *     function(...) {
355      *          ....
356      *     },
357      *     parentClass, // or Object
358      *     {
359      *        ... methods and properties.
360      *     }
361      * });
362      * @param {Function} constructor The class inheriting the functionality
363      * @param {Object} superclass The class being extended
364      * @param {Object} overrides (optional) A literal with members
365      * @return {Function} constructor (eg. class
366      * @method define
367      */
368     define : function(){
369         // inline overrides
370         var io = function(o){
371             for(var m in o){
372                 this[m] = o[m];
373             }
374         };
375         return function(sb, sp, overrides) {
376             if (typeof(sp) == 'undefined') {
377                 // error condition - try and dump..
378                 throw "Missing superclass: when applying: " + sb
379             }
380
381             var F = function(){}, sbp, spp = sp.prototype;
382             F.prototype = spp;
383             sbp = sb.prototype = new F();
384             sbp.constructor=sb;
385             sb.superclass=spp;
386
387             // extends Object.
388             if(spp.constructor == Object.prototype.constructor){
389                 spp.constructor=sp;
390             }
391             
392             sb.override = function(o){
393                 Object.extend(sb.prototype, o);
394             };
395             sbp.override = io;
396             XObject.extend(sb.prototype, overrides);
397             return sb;
398         };
399     }(),
400
401          
402     /**
403      * returns a list of keys of the object.
404      * @param {Object} obj object to inspect
405      * @return {Array} returns list of kyes
406      * @member XObject keys
407      */
408     keys : function(o)
409     {
410         var ret = [];
411         for(var i in o) {
412             ret.push(i);
413         }
414         return ret;
415     },
416       
417     /**
418      * @member XObject createDelegate
419      * creates a delage metdhod
420      * @param {Function} method to wrap
421      * @param {Object} scope 
422      * @param {Array} args to add
423      * @param {Boolean|Number} append arguments or replace after N arguments.
424      * @return {Function} returns the delegate
425      * 
426      * Usage: 
427      *  function a() .... 
428      * 
429      * x = XObject.createDelegate(a, this);
430      * 
431      */
432
433     createDelegate : function(method, obj, args, appendArgs){
434         
435         return function() {
436             var callArgs = args || arguments;
437             if(appendArgs === true){
438                 callArgs = Array.prototype.slice.call(arguments, 0);
439                 callArgs = callArgs.concat(args);
440             }else if(typeof appendArgs == "number"){
441                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
442                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
443                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
444                 }
445                 return method.apply(obj || window, callArgs);
446             };
447     }
448     
449 });