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