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