[MERGE] js and css enumeration and loading by chs
[odoo/odoo.git] / addons / web / static / src / js / core.js
1 /*---------------------------------------------------------
2  * OpenERP Web core
3  *--------------------------------------------------------*/
4 var console;
5 if (!console) {
6     console = {log: function () {}};
7 }
8 if (!console.debug) {
9     console.debug = console.log;
10 }
11
12 openerp.web.core = function(openerp) {
13 openerp.web.qweb = new QWeb2.Engine();
14 openerp.web.qweb.debug = (window.location.search.indexOf('?debug') !== -1);
15 /**
16  * John Resig Class with factory improvement
17  */
18 (function() {
19     var initializing = false,
20         fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
21     // The web Class implementation (does nothing)
22     /**
23      * Extended version of John Resig's Class pattern
24      *
25      * @class
26      */
27     openerp.web.Class = function(){};
28
29     /**
30      * Subclass an existing class
31      *
32      * @param {Object} prop class-level properties (class attributes and instance methods) to set on the new class
33      */
34     openerp.web.Class.extend = function(prop) {
35         var _super = this.prototype;
36
37         // Instantiate a web class (but only create the instance,
38         // don't run the init constructor)
39         initializing = true;
40         var prototype = new this();
41         initializing = false;
42
43         // Copy the properties over onto the new prototype
44         for (var name in prop) {
45             // Check if we're overwriting an existing function
46             prototype[name] = typeof prop[name] == "function" &&
47                               typeof _super[name] == "function" &&
48                               fnTest.test(prop[name]) ?
49                     (function(name, fn) {
50                         return function() {
51                             var tmp = this._super;
52
53                             // Add a new ._super() method that is the same
54                             // method but on the super-class
55                             this._super = _super[name];
56
57                             // The method only need to be bound temporarily, so
58                             // we remove it when we're done executing
59                             var ret = fn.apply(this, arguments);
60                             this._super = tmp;
61
62                             return ret;
63                         };
64                     })(name, prop[name]) :
65                     prop[name];
66         }
67
68         // The dummy class constructor
69         function Class() {
70             // All construction is actually done in the init method
71             if (!initializing && this.init) {
72                 var ret = this.init.apply(this, arguments);
73                 if (ret) { return ret; }
74             }
75             return this;
76         }
77         Class.include = function (properties) {
78             for (var name in properties) {
79                 if (typeof properties[name] !== 'function'
80                         || !fnTest.test(properties[name])) {
81                     prototype[name] = properties[name];
82                 } else if (typeof prototype[name] === 'function'
83                            && prototype.hasOwnProperty(name)) {
84                     prototype[name] = (function (name, fn, previous) {
85                         return function () {
86                             var tmp = this._super;
87                             this._super = previous;
88                             var ret = fn.apply(this, arguments);
89                             this._super = tmp;
90                             return ret;
91                         }
92                     })(name, properties[name], prototype[name]);
93                 } else if (typeof _super[name] === 'function') {
94                     prototype[name] = (function (name, fn) {
95                         return function () {
96                             var tmp = this._super;
97                             this._super = _super[name];
98                             var ret = fn.apply(this, arguments);
99                             this._super = tmp;
100                             return ret;
101                         }
102                     })(name, properties[name]);
103                 }
104             }
105         };
106
107         // Populate our constructed prototype object
108         Class.prototype = prototype;
109
110         // Enforce the constructor to be what we expect
111         Class.constructor = Class;
112
113         // And make this class extendable
114         Class.extend = arguments.callee;
115
116         return Class;
117     };
118 })();
119
120 openerp.web.callback = function(obj, method) {
121     var callback = function() {
122         var args = Array.prototype.slice.call(arguments);
123         var r;
124         for(var i = 0; i < callback.callback_chain.length; i++)  {
125             var c = callback.callback_chain[i];
126             if(c.unique) {
127                 callback.callback_chain.splice(i, 1);
128                 i -= 1;
129             }
130             r = c.callback.apply(c.self, c.args.concat(args));
131             // TODO special value to stop the chain
132             // openerp.web.callback_stop
133         }
134         return r;
135     };
136     callback.callback_chain = [];
137     callback.add = function(f) {
138         if(typeof(f) == 'function') {
139             f = { callback: f, args: Array.prototype.slice.call(arguments, 1) };
140         }
141         f.self = f.self || null;
142         f.args = f.args || [];
143         f.unique = !!f.unique;
144         if(f.position == 'last') {
145             callback.callback_chain.push(f);
146         } else {
147             callback.callback_chain.unshift(f);
148         }
149         return callback;
150     };
151     callback.add_first = function(f) {
152         return callback.add.apply(null,arguments);
153     };
154     callback.add_last = function(f) {
155         return callback.add({
156             callback: f,
157             args: Array.prototype.slice.call(arguments, 1),
158             position: "last"
159         });
160     };
161
162     return callback.add({
163         callback: method,
164         self:obj,
165         args:Array.prototype.slice.call(arguments, 2)
166     });
167 };
168
169 /**
170  * Generates an inherited class that replaces all the methods by null methods (methods
171  * that does nothing and always return undefined).
172  *
173  * @param {Class} claz
174  * @param {Object} add Additional functions to override.
175  * @return {Class}
176  */
177 openerp.web.generate_null_object_class = function(claz, add) {
178     var newer = {};
179     var copy_proto = function(prototype) {
180         for (var name in prototype) {
181             if(typeof prototype[name] == "function") {
182                 newer[name] = function() {};
183             }
184         }
185         if (prototype.prototype)
186             copy_proto(prototype.prototype);
187     };
188     copy_proto(claz.prototype);
189     newer.init = openerp.web.Widget.prototype.init;
190     var tmpclass = claz.extend(newer);
191     return tmpclass.extend(add || {});
192 };
193
194 /**
195  * web error for lookup failure
196  *
197  * @class
198  */
199 openerp.web.NotFound = openerp.web.Class.extend( /** @lends openerp.web.NotFound# */ {
200 });
201 openerp.web.KeyNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.KeyNotFound# */ {
202     /**
203      * Thrown when a key could not be found in a mapping
204      *
205      * @constructs openerp.web.KeyNotFound
206      * @extends openerp.web.NotFound
207      * @param {String} key the key which could not be found
208      */
209     init: function (key) {
210         this.key = key;
211     },
212     toString: function () {
213         return "The key " + this.key + " was not found";
214     }
215 });
216 openerp.web.ObjectNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.ObjectNotFound# */ {
217     /**
218      * Thrown when an object path does not designate a valid class or object
219      * in the openerp hierarchy.
220      *
221      * @constructs openerp.web.ObjectNotFound
222      * @extends openerp.web.NotFound
223      * @param {String} path the invalid object path
224      */
225     init: function (path) {
226         this.path = path;
227     },
228     toString: function () {
229         return "Could not find any object of path " + this.path;
230     }
231 });
232 openerp.web.Registry = openerp.web.Class.extend( /** @lends openerp.web.Registry# */ {
233     /**
234      * Stores a mapping of arbitrary key (strings) to object paths (as strings
235      * as well).
236      *
237      * Resolves those paths at query time in order to always fetch the correct
238      * object, even if those objects have been overloaded/replaced after the
239      * registry was created.
240      *
241      * An object path is simply a dotted name from the openerp root to the
242      * object pointed to (e.g. ``"openerp.web.Session"`` for an OpenERP
243      * session object).
244      *
245      * @constructs openerp.web.Registry
246      * @param {Object} mapping a mapping of keys to object-paths
247      */
248     init: function (mapping) {
249         this.map = mapping || {};
250     },
251     /**
252      * Retrieves the object matching the provided key string.
253      *
254      * @param {String} key the key to fetch the object for
255      * @returns {Class} the stored class, to initialize
256      *
257      * @throws {openerp.web.KeyNotFound} if the object was not in the mapping
258      * @throws {openerp.web.ObjectNotFound} if the object path was invalid
259      */
260     get_object: function (key) {
261         var path_string = this.map[key];
262         if (path_string === undefined) {
263             throw new openerp.web.KeyNotFound(key);
264         }
265
266         var object_match = openerp;
267         var path = path_string.split('.');
268         // ignore first section
269         for(var i=1; i<path.length; ++i) {
270             object_match = object_match[path[i]];
271
272             if (object_match === undefined) {
273                 throw new openerp.web.ObjectNotFound(path_string);
274             }
275         }
276         return object_match;
277     },
278     /**
279      * Tries a number of keys, and returns the first object matching one of
280      * the keys.
281      *
282      * @param {Array} keys a sequence of keys to fetch the object for
283      * @returns {Class} the first class found matching an object
284      *
285      * @throws {openerp.web.KeyNotFound} if none of the keys was in the mapping
286      * @trows {openerp.web.ObjectNotFound} if a found object path was invalid
287      */
288     get_any: function (keys) {
289         for (var i=0; i<keys.length; ++i) {
290             var key = keys[i];
291             if (key === undefined || !(key in this.map)) {
292                 continue;
293             }
294
295             return this.get_object(key);
296         }
297         throw new openerp.web.KeyNotFound(keys.join(','));
298     },
299     /**
300      * Adds a new key and value to the registry.
301      *
302      * This method can be chained.
303      *
304      * @param {String} key
305      * @param {String} object_path fully qualified dotted object path
306      * @returns {openerp.web.Registry} itself
307      */
308     add: function (key, object_path) {
309         this.map[key] = object_path;
310         return this;
311     },
312     /**
313      * Creates and returns a copy of the current mapping, with the provided
314      * mapping argument added in (replacing existing keys if needed)
315      *
316      * @param {Object} [mapping={}] a mapping of keys to object-paths
317      */
318     clone: function (mapping) {
319         return new openerp.web.Registry(
320             _.extend({}, this.map, mapping || {}));
321     }
322 });
323
324 openerp.web.CallbackEnabled = openerp.web.Class.extend(/** @lends openerp.web.CallbackEnabled# */{
325     /**
326      * @constructs openerp.web.CallbackEnabled
327      * @extends openerp.web.Class
328      */
329     init: function() {
330         // Transform on_* method into openerp.web.callbacks
331         for (var name in this) {
332             if(typeof(this[name]) == "function") {
333                 this[name].debug_name = name;
334                 // bind ALL function to this not only on_and _do ?
335                 if((/^on_|^do_/).test(name)) {
336                     this[name] = openerp.web.callback(this, this[name]);
337                 }
338             }
339         }
340     }
341 });
342
343 openerp.web.Session = openerp.web.CallbackEnabled.extend( /** @lends openerp.web.Session# */{
344     /**
345      * @constructs openerp.web.Session
346      * @extends openerp.web.CallbackEnabled
347      *
348      * @param {String} [server] JSON-RPC endpoint hostname
349      * @param {String} [port] JSON-RPC endpoint port
350      */
351     init: function(server, port) {
352         this._super();
353         this.server = (server == undefined) ? location.hostname : server;
354         this.port = (port == undefined) ? location.port : port;
355         this.rpc_mode = (server == location.hostname) ? "ajax" : "jsonp";
356         this.debug = (window.location.search.indexOf('?debug') !== -1);
357         this.session_id = false;
358         this.uid = false;
359         this.user_context= {};
360         this.db = false;
361         this.module_list = [];
362         this.module_loaded = {"web": true};
363         this.context = {};
364         this.shortcuts = [];
365         this.active_id = null;
366     },
367     start: function() {
368         this.session_restore();
369     },
370     /**
371      * Executes an RPC call, registering the provided callbacks.
372      *
373      * Registers a default error callback if none is provided, and handles
374      * setting the correct session id and session context in the parameter
375      * objects
376      *
377      * @param {String} url RPC endpoint
378      * @param {Object} params call parameters
379      * @param {Function} success_callback function to execute on RPC call success
380      * @param {Function} error_callback function to execute on RPC call failure
381      * @returns {jQuery.Deferred} jquery-provided ajax deferred
382      */
383     rpc: function(url, params, success_callback, error_callback) {
384         var self = this;
385         // Construct a JSON-RPC2 request, method is currently unused
386         params.session_id = this.session_id;
387         if (this.debug)
388             params.debug = 1;
389
390         // Call using the rpc_mode
391         var deferred = $.Deferred();
392         this.rpc_ajax(url, {
393             jsonrpc: "2.0",
394             method: "call",
395             params: params,
396             id: _.uniqueId('browser-client-')
397         }).then(function () {deferred.resolve.apply(deferred, arguments);},
398                 function(error) {deferred.reject(error, $.Event());});
399         return deferred.fail(function() {
400             deferred.fail(function(error, event) {
401                 if (!event.isDefaultPrevented()) {
402                     self.on_rpc_error(error, event);
403                 }
404             });
405         }).then(success_callback, error_callback).promise();
406     },
407     /**
408      * Raw JSON-RPC call
409      *
410      * @returns {jQuery.Deferred} ajax-webd deferred object
411      */
412     rpc_ajax: function(url, payload) {
413         var self = this;
414         this.on_rpc_request();
415         // url can be an $.ajax option object
416         if (_.isString(url)) {
417             url = {
418                 url: url
419             }
420         }
421         var ajax = _.extend({
422             type: "POST",
423             url: url,
424             dataType: 'json',
425             contentType: 'application/json',
426             data: JSON.stringify(payload),
427             processData: false
428         }, url);
429         var deferred = $.Deferred();
430         $.ajax(ajax).done(function(response, textStatus, jqXHR) {
431             self.on_rpc_response();
432             if (!response.error) {
433                 deferred.resolve(response["result"], textStatus, jqXHR);
434                 return;
435             }
436             if (response.error.data.type !== "session_invalid") {
437                 deferred.reject(response.error);
438                 return;
439             }
440             self.uid = false;
441             self.on_session_invalid(function() {
442                 self.rpc(url, payload.params,
443                     function() {
444                         deferred.resolve.apply(deferred, arguments);
445                     },
446                     function(error, event) {
447                         event.preventDefault();
448                         deferred.reject.apply(deferred, arguments);
449                     });
450             });
451         }).fail(function(jqXHR, textStatus, errorThrown) {
452             self.on_rpc_response();
453             var error = {
454                 code: -32098,
455                 message: "XmlHttpRequestError " + errorThrown,
456                 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
457             };
458             deferred.reject(error);
459         });
460         return deferred.promise();
461     },
462     on_rpc_request: function() {
463     },
464     on_rpc_response: function() {
465     },
466     on_rpc_error: function(error) {
467     },
468     /**
469      * The session is validated either by login or by restoration of a previous session
470      */
471     on_session_valid: function() {
472         if(!openerp._modules_loaded)
473             this.load_modules();
474     },
475     on_session_invalid: function(contination) {
476     },
477     session_is_valid: function() {
478         return this.uid;
479     },
480     session_login: function(db, login, password, success_callback) {
481         var self = this;
482         var params = { db: db, login: login, password: password };
483         return this.rpc("/web/session/login", params, function(result) {
484             self.session_id = result.session_id;
485             self.uid = result.uid;
486             self.user_context = result.context;
487             self.db = result.db;
488             self.session_save();
489             return true;
490         }).then(success_callback);
491     },
492     /**
493      * Reloads uid and session_id from local storage, if they exist
494      */
495     session_restore: function () {
496         var self = this;
497         this.session_id = this.get_cookie('session_id');
498         return this.rpc("/web/session/get_session_info", {}).then(function(result) {
499             self.uid = result.uid;
500             self.user_context = result.context;
501             self.db = result.db;
502             if (self.uid)
503                 self.on_session_valid();
504             else
505                 self.on_session_invalid();
506         }, function() {
507             self.on_session_invalid();
508         });
509     },
510     /**
511      * Saves the session id and uid locally
512      */
513     session_save: function () {
514         this.set_cookie('session_id', this.session_id);
515     },
516     logout: function() {
517         this.set_cookie('session_id', '');
518         this.reload_client();
519     },
520     reload_client: function() {
521         window.location.reload();
522     },
523     /**
524      * Fetches a cookie stored by an openerp session
525      *
526      * @private
527      * @param name the cookie's name
528      */
529     get_cookie: function (name) {
530         var nameEQ = this.element_id + '|' + name + '=';
531         var cookies = document.cookie.split(';');
532         for(var i=0; i<cookies.length; ++i) {
533             var cookie = cookies[i].replace(/^\s*/, '');
534             if(cookie.indexOf(nameEQ) === 0) {
535                 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
536             }
537         }
538         return null;
539     },
540     /**
541      * Create a new cookie with the provided name and value
542      *
543      * @private
544      * @param name the cookie's name
545      * @param value the cookie's value
546      * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
547      */
548     set_cookie: function (name, value, ttl) {
549         ttl = ttl || 24*60*60*365;
550         document.cookie = [
551             this.element_id + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
552             'max-age=' + ttl,
553             'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
554         ].join(';');
555     },
556     /**
557      * Load additional web addons of that instance and init them
558      */
559     load_modules: function() {
560         var self = this;
561         this.rpc('/web/session/modules', {}, function(result) {
562             self.module_list = result;
563             var lang = self.user_context.lang;
564             var params = { mods: ["web"].concat(result), lang: lang};
565             self.rpc('/web/webclient/translations',params).then(function(transs) {
566                 openerp.web._t.database.set_bundle(transs);
567                 var modules = self.module_list.join(',');
568                 var file_list = ["/web/static/lib/datejs/globalization/" +
569                     self.user_context.lang.replace("_", "-") + ".js"
570                 ];
571
572                 self.rpc('/web/webclient/csslist', {"mods": modules}, self.do_load_css);
573                 self.rpc('/web/webclient/jslist', {"mods": modules}, function(files) {
574                     self.do_load_js(file_list.concat(files));
575                 });
576                 openerp._modules_loaded = true;
577             });
578         });
579     },
580     do_load_css: function (files) {
581         var self = this;
582         _.each(files, function (file) {
583             $('head').append($('<link>', {
584                 'href': file,
585                 'rel': 'stylesheet',
586                 'type': 'text/css'
587             }));
588         });
589     },
590     do_load_js: function(files) {
591         var self = this;
592         if(files.length != 0) {
593             var file = files.shift();
594             var tag = document.createElement('script');
595             tag.type = 'text/javascript';
596             tag.src = file;
597             tag.onload = tag.onreadystatechange = function() {
598                 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
599                     return;
600                 tag.onload_done = true;
601                 self.do_load_js(files);
602             };
603             document.head.appendChild(tag);
604         } else {
605             this.on_modules_loaded();
606         }
607     },
608     on_modules_loaded: function() {
609         for(var j=0; j<this.module_list.length; j++) {
610             var mod = this.module_list[j];
611             if(this.module_loaded[mod])
612                 continue;
613             openerp[mod] = {};
614             // init module mod
615             if(openerp._openerp[mod] != undefined) {
616                 openerp._openerp[mod](openerp);
617                 this.module_loaded[mod] = true;
618             }
619         }
620     },
621     /**
622      * Cooperative file download implementation, for ajaxy APIs.
623      *
624      * Requires that the server side implements an httprequest correctly
625      * setting the `fileToken` cookie to the value provided as the `token`
626      * parameter. The cookie *must* be set on the `/` path and *must not* be
627      * `httpOnly`.
628      *
629      * It would probably also be a good idea for the response to use a
630      * `Content-Disposition: attachment` header, especially if the MIME is a
631      * "known" type (e.g. text/plain, or for some browsers application/json
632      *
633      * @param {Object} options
634      * @param {String} [options.url] used to dynamically create a form
635      * @param {Object} [options.data] data to add to the form submission. If can be used without a form, in which case a form is created from scratch. Otherwise, added to form data
636      * @param {HTMLFormElement} [options.form] the form to submit in order to fetch the file
637      * @param {Function} [options.success] callback in case of download success
638      * @param {Function} [options.error] callback in case of request error, provided with the error body
639      * @param {Function} [options.complete] called after both ``success`` and ``error` callbacks have executed
640      */
641     get_file: function (options) {
642         // need to detect when the file is done downloading (not used
643         // yet, but we'll need it to fix the UI e.g. with a throbber
644         // while dump is being generated), iframe load event only fires
645         // when the iframe content loads, so we need to go smarter:
646         // http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
647         var timer, token = new Date().getTime(),
648             cookie_name = 'fileToken', cookie_length = cookie_name.length,
649             CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
650             remove_form = false;
651
652         var $form, $form_data = $('<div>');
653
654         var complete = function () {
655             if (options.complete) { options.complete(); }
656             clearTimeout(timer);
657             $form_data.remove();
658             $target.remove();
659             if (remove_form && $form) { $form.remove(); }
660         };
661         var $target = $('<iframe style="display: none;">')
662             .attr({id: id, name: id})
663             .appendTo(document.body)
664             .load(function () {
665                 if (options.error) { options.error(this.contentDocument.body); }
666                 complete();
667             });
668
669         if (options.form) {
670             $form = $(options.form);
671         } else {
672             remove_form = true;
673             $form = $('<form>', {
674                 action: options.url,
675                 method: 'POST'
676             }).appendTo(document.body);
677         }
678
679         _(_.extend({}, options.data || {},
680                    {session_id: this.session_id, token: token}))
681             .each(function (value, key) {
682                 $('<input type="hidden" name="' + key + '">')
683                     .val(value)
684                     .appendTo($form_data);
685             });
686
687         $form
688             .append($form_data)
689             .attr('target', id)
690             .get(0).submit();
691
692         var waitLoop = function () {
693             var cookies = document.cookie.split(';');
694             // setup next check
695             timer = setTimeout(waitLoop, CHECK_INTERVAL);
696             for (var i=0; i<cookies.length; ++i) {
697                 var cookie = cookies[i].replace(/^\s*/, '');
698                 if (!cookie.indexOf(cookie_name === 0)) { continue; }
699                 var cookie_val = cookie.substring(cookie_length + 1);
700                 if (parseInt(cookie_val, 10) !== token) { continue; }
701
702                 // clear cookie
703                 document.cookie = _.sprintf("%s=;expires=%s;path=/",
704                     cookie_name, new Date().toGMTString());
705                 if (options.success) { options.success(); }
706                 complete();
707                 return;
708             }
709         };
710         timer = setTimeout(waitLoop, CHECK_INTERVAL);
711     }
712 });
713
714 openerp.web.SessionAware = openerp.web.CallbackEnabled.extend(/** @lends openerp.web.SessionAware# */{
715     /**
716      * Utility class that any class is allowed to extend to easy common manipulations.
717      *
718      * It provides rpc calls, callback on all methods preceded by "on_" or "do_" and a
719      * logging facility.
720      *
721      * @constructs openerp.web.SessionAware
722      * @extends openerp.web.CallbackEnabled
723      *
724      * @param {openerp.web.Session} session
725      */
726     init: function(session) {
727         this._super();
728         this.session = session;
729     },
730     /**
731      * Performs a JSON-RPC call
732      *
733      * @param {String} url endpoint url
734      * @param {Object} data RPC parameters
735      * @param {Function} success RPC call success callback
736      * @param {Function} error RPC call error callback
737      * @returns {jQuery.Deferred} deferred object for the RPC call
738      */
739     rpc: function(url, data, success, error) {
740         return this.session.rpc(url, data, success, error);
741     }
742 });
743
744 /**
745  * Base class for all visual components. Provides a lot of functionalities helpful
746  * for the management of a part of the DOM.
747  *
748  * Widget handles:
749  * - Rendering with QWeb.
750  * - Life-cycle management and parenting (when a parent is destroyed, all its children are
751  *     destroyed too).
752  * - Insertion in DOM.
753  *
754  * Widget also extends SessionAware for ease of use.
755  *
756  * Guide to create implementations of the Widget class:
757  * ==============================================
758  *
759  * Here is a sample child class:
760  *
761  * MyWidget = openerp.base.Widget.extend({
762  *     // the name of the QWeb template to use for rendering
763  *     template: "MyQWebTemplate",
764  *     // identifier prefix, it is useful to put an obvious one for debugging
765  *     identifier_prefix: 'my-id-prefix-',
766  *
767  *     init: function(parent) {
768  *         this._super(parent);
769  *         // stuff that you want to init before the rendering
770  *     },
771  *     start: function() {
772  *         // stuff you want to make after the rendering, `this.$element` holds a correct value
773  *         this.$element.find(".my_button").click(/* an example of event binding * /);
774  *
775  *         // if you have some asynchronous operations, it's a good idea to return
776  *         // a promise in start()
777  *         var promise = this.rpc(...);
778  *         return promise;
779  *     }
780  * });
781  *
782  * Now this class can simply be used with the following syntax:
783  *
784  * var my_widget = new MyWidget(this);
785  * my_widget.appendTo($(".some-div"));
786  *
787  * With these two lines, the MyWidget instance was inited, rendered, it was inserted into the
788  * DOM inside the ".some-div" div and its events were binded.
789  *
790  * And of course, when you don't need that widget anymore, just do:
791  *
792  * my_widget.stop();
793  *
794  * That will kill the widget in a clean way and erase its content from the dom.
795  */
796 openerp.web.Widget = openerp.web.SessionAware.extend(/** @lends openerp.web.Widget# */{
797     /**
798      * The name of the QWeb template that will be used for rendering. Must be
799      * redefined in subclasses or the default render() method can not be used.
800      *
801      * @type string
802      */
803     template: null,
804     /**
805      * The prefix used to generate an id automatically. Should be redefined in
806      * subclasses. If it is not defined, a generic identifier will be used.
807      *
808      * @type string
809      */
810     identifier_prefix: 'generic-identifier-',
811     /**
812      * Construct the widget and set its parent if a parent is given.
813      *
814      * @constructs openerp.web.Widget
815      * @extends openerp.web.SessionAware
816      *
817      * @param {openerp.web.Widget} parent Binds the current instance to the given Widget instance.
818      * When that widget is destroyed by calling stop(), the current instance will be
819      * destroyed too. Can be null.
820      * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
821      * to bind the current Widget to an already existing part of the DOM, which is not compatible
822      * with the DOM insertion methods provided by the current implementation of Widget. So
823      * for new components this argument should not be provided any more.
824      */
825     init: function(parent, /** @deprecated */ element_id) {
826         this._super((parent || {}).session);
827         // if given an element_id, try to get the associated DOM element and save
828         // a reference in this.$element. Else just generate a unique identifier.
829         this.element_id = element_id;
830         this.element_id = this.element_id || _.uniqueId(this.identifier_prefix);
831         var tmp = document.getElementById(this.element_id);
832         this.$element = tmp ? $(tmp) : undefined;
833
834         this.widget_parent = parent;
835         this.widget_children = [];
836         if(parent && parent.widget_children) {
837             parent.widget_children.push(this);
838         }
839         // useful to know if the widget was destroyed and should not be used anymore
840         this.widget_is_stopped = false;
841     },
842     /**
843      * Render the current widget and appends it to the given jQuery object or Widget.
844      *
845      * @param target A jQuery object or a Widget instance.
846      */
847     appendTo: function(target) {
848         var self = this;
849         return this._render_and_insert(function(t) {
850             self.$element.appendTo(t);
851         }, target);
852     },
853     /**
854      * Render the current widget and prepends it to the given jQuery object or Widget.
855      *
856      * @param target A jQuery object or a Widget instance.
857      */
858     prependTo: function(target) {
859         var self = this;
860         return this._render_and_insert(function(t) {
861             self.$element.prependTo(t);
862         }, target);
863     },
864     /**
865      * Render the current widget and inserts it after to the given jQuery object or Widget.
866      *
867      * @param target A jQuery object or a Widget instance.
868      */
869     insertAfter: function(target) {
870         var self = this;
871         return this._render_and_insert(function(t) {
872             self.$element.insertAfter(t);
873         }, target);
874     },
875     /**
876      * Render the current widget and inserts it before to the given jQuery object or Widget.
877      *
878      * @param target A jQuery object or a Widget instance.
879      */
880     insertBefore: function(target) {
881         var self = this;
882         return this._render_and_insert(function(t) {
883             self.$element.insertBefore(t);
884         }, target);
885     },
886     _render_and_insert: function(insertion, target) {
887         var rendered = this.render();
888         this.$element = $(rendered);
889         if (target instanceof openerp.web.Widget)
890             target = target.$element;
891         insertion(target);
892         this.on_inserted(this.$element, this);
893         return this.start();
894     },
895     on_inserted: function(element, widget) {},
896     /**
897      * Renders the widget using QWeb, `this.template` must be defined.
898      * The context given to QWeb contains the "widget" key that references `this`.
899      *
900      * @param {Object} additional Additional context arguments to pass to the template.
901      */
902     render: function (additional) {
903         return openerp.web.qweb.render(this.template, _.extend({widget: this}, additional || {}));
904     },
905     /**
906      * Method called after rendering. Mostly used to bind actions, perform asynchronous
907      * calls, etc...
908      *
909      * By convention, the method should return a promise to inform the caller when
910      * this widget has been initialized.
911      *
912      * @returns {jQuery.Deferred}
913      */
914     start: function() {
915         /* The default implementation is only useful for retro-compatibility, it is
916         not necessary to call it using _super() when using Widget for new components. */
917         if (!this.$element) {
918             var tmp = document.getElementById(this.element_id);
919             this.$element = tmp ? $(tmp) : undefined;
920         }
921         return $.Deferred().done().promise();
922     },
923     /**
924      * Destroys the current widget, also destroy all its children before destroying itself.
925      */
926     stop: function() {
927         _.each(_.clone(this.widget_children), function(el) {
928             el.stop();
929         });
930         if(this.$element != null) {
931             this.$element.remove();
932         }
933         if (this.widget_parent && this.widget_parent.widget_children) {
934             this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
935         }
936         this.widget_parent = null;
937         this.widget_is_stopped = true;
938     },
939     /**
940      * Inform the action manager to do an action. Of course, this suppose that
941      * the action manager can be found amongst the ancestors of the current widget.
942      * If that's not the case this method will simply return `false`.
943      */
944     do_action: function(action, on_finished) {
945         if (this.widget_parent) {
946             return this.widget_parent.do_action(action, on_finished);
947         }
948         return false;
949     },
950     do_notify: function() {
951         if (this.widget_parent) {
952             return this.widget_parent.do_notify.apply(this,arguments);
953         }
954         return false;
955     },
956     do_warn: function() {
957         if (this.widget_parent) {
958             return this.widget_parent.do_warn.apply(this,arguments);
959         }
960         return false;
961     },
962     rpc: function(url, data, success, error) {
963         var def = $.Deferred().then(success, error);
964         var self = this;
965         this._super(url, data). then(function() {
966             if (!self.widget_is_stopped)
967                 def.resolve.apply(def, arguments);
968         }, function() {
969             if (!self.widget_is_stopped)
970                 def.reject.apply(def, arguments);
971         });
972         return def.promise();
973     }
974 });
975
976 /**
977  * @class
978  * @extends openerp.web.Widget
979  * @deprecated
980  * For retro compatibility only, the only difference with is that render() uses
981  * directly ``this`` instead of context with a ``widget`` key.
982  */
983 openerp.web.OldWidget = openerp.web.Widget.extend(/** @lends openerp.web.OldWidget# */{
984     render: function (additional) {
985         return openerp.web.qweb.render(this.template, _.extend(_.extend({}, this), additional || {}));
986     }
987 });
988
989 openerp.web.TranslationDataBase = openerp.web.Class.extend(/** @lends openerp.web.TranslationDataBase# */{
990     /**
991      * @constructs openerp.web.TranslationDataBase
992      * @extends openerp.web.Class
993      */
994     init: function() {
995         this.db = {};
996         this.parameters = {"direction": 'ltr',
997                         "date_format": '%m/%d/%Y',
998                         "time_format": '%H:%M:%S',
999                         "grouping": "[]",
1000                         "decimal_point": ".",
1001                         "thousands_sep": ","};
1002     },
1003     set_bundle: function(translation_bundle) {
1004         var self = this;
1005         this.db = {};
1006         var modules = _.keys(translation_bundle.modules).sort();
1007         if (_.include(modules, "web")) {
1008             modules = ["web"].concat(_.without(modules, "web"));
1009         }
1010         _.each(modules, function(name) {
1011             self.add_module_translation(translation_bundle.modules[name]);
1012         });
1013         if (translation_bundle.lang_parameters) {
1014             this.parameters = translation_bundle.lang_parameters;
1015         }
1016     },
1017     add_module_translation: function(mod) {
1018         var self = this;
1019         _.each(mod.messages, function(message) {
1020             if (self.db[message.id] === undefined) {
1021                 self.db[message.id] = message.string;
1022             }
1023         });
1024     },
1025     build_translation_function: function() {
1026         var self = this;
1027         var fcnt = function(str) {
1028             var tmp = self.get(str);
1029             return tmp === undefined ? str : tmp;
1030         };
1031         fcnt.database = this;
1032         return fcnt;
1033     },
1034     get: function(key) {
1035         if (this.db[key])
1036             return this.db[key];
1037         return undefined;
1038     }
1039 });
1040
1041 openerp.web._t = new openerp.web.TranslationDataBase().build_translation_function();
1042
1043 };
1044
1045 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: