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