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