1 /*---------------------------------------------------------
3 *--------------------------------------------------------*/
6 console = {log: function () {}};
9 console.debug = console.log;
12 openerp.web.core = function(openerp) {
14 * John Resig Class with factory improvement
17 var initializing = false,
18 fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
19 // The web Class implementation (does nothing)
21 * Extended version of John Resig's Class pattern
25 openerp.web.Class = function(){};
28 * Subclass an existing class
30 * @param {Object} prop class-level properties (class attributes and instance methods) to set on the new class
32 openerp.web.Class.extend = function(prop) {
33 var _super = this.prototype;
35 // Instantiate a web class (but only create the instance,
36 // don't run the init constructor)
38 var prototype = new this();
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]) ?
49 var tmp = this._super;
51 // Add a new ._super() method that is the same
52 // method but on the super-class
53 this._super = _super[name];
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);
62 })(name, prop[name]) :
66 // The dummy class constructor
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; }
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) {
84 var tmp = this._super;
85 this._super = previous;
86 var ret = fn.apply(this, arguments);
90 })(name, properties[name], prototype[name]);
91 } else if (typeof _super[name] === 'function') {
92 prototype[name] = (function (name, fn) {
94 var tmp = this._super;
95 this._super = _super[name];
96 var ret = fn.apply(this, arguments);
100 })(name, properties[name]);
105 // Populate our constructed prototype object
106 Class.prototype = prototype;
108 // Enforce the constructor to be what we expect
109 Class.constructor = Class;
111 // And make this class extendable
112 Class.extend = arguments.callee;
118 openerp.web.callback = function(obj, method) {
119 var callback = function() {
120 var args = Array.prototype.slice.call(arguments);
122 for(var i = 0; i < callback.callback_chain.length; i++) {
123 var c = callback.callback_chain[i];
125 callback.callback_chain.splice(i, 1);
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
133 // TODO special value to stop the chain
134 // openerp.web.callback_stop
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) };
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);
149 callback.callback_chain.unshift(f);
153 callback.add_first = function(f) {
154 return callback.add.apply(null,arguments);
156 callback.add_last = function(f) {
157 return callback.add({
159 args: Array.prototype.slice.call(arguments, 1),
164 return callback.add({
167 args:Array.prototype.slice.call(arguments, 2)
172 * Generates an inherited class that replaces all the methods by null methods (methods
173 * that does nothing and always return undefined).
175 * @param {Class} claz
176 * @param {Object} add Additional functions to override.
179 openerp.web.generate_null_object_class = function(claz, add) {
181 var copy_proto = function(prototype) {
182 for (var name in prototype) {
183 if(typeof prototype[name] == "function") {
184 newer[name] = function() {};
187 if (prototype.prototype)
188 copy_proto(prototype.prototype);
190 copy_proto(claz.prototype);
191 newer.init = openerp.web.Widget.prototype.init;
192 var tmpclass = claz.extend(newer);
193 return tmpclass.extend(add || {});
197 * web error for lookup failure
201 openerp.web.NotFound = openerp.web.Class.extend( /** @lends openerp.web.NotFound# */ {
203 openerp.web.KeyNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.KeyNotFound# */ {
205 * Thrown when a key could not be found in a mapping
207 * @constructs openerp.web.KeyNotFound
208 * @extends openerp.web.NotFound
209 * @param {String} key the key which could not be found
211 init: function (key) {
214 toString: function () {
215 return "The key " + this.key + " was not found";
218 openerp.web.ObjectNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.ObjectNotFound# */ {
220 * Thrown when an object path does not designate a valid class or object
221 * in the openerp hierarchy.
223 * @constructs openerp.web.ObjectNotFound
224 * @extends openerp.web.NotFound
225 * @param {String} path the invalid object path
227 init: function (path) {
230 toString: function () {
231 return "Could not find any object of path " + this.path;
234 openerp.web.Registry = openerp.web.Class.extend( /** @lends openerp.web.Registry# */ {
236 * Stores a mapping of arbitrary key (strings) to object paths (as strings
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.
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).
247 * @constructs openerp.web.Registry
248 * @param {Object} mapping a mapping of keys to object-paths
250 init: function (mapping) {
251 this.map = mapping || {};
254 * Retrieves the object matching the provided key string.
256 * @param {String} key the key to fetch the object for
257 * @returns {Class} the stored class, to initialize
259 * @throws {openerp.web.KeyNotFound} if the object was not in the mapping
260 * @throws {openerp.web.ObjectNotFound} if the object path was invalid
262 get_object: function (key) {
263 var path_string = this.map[key];
264 if (path_string === undefined) {
265 throw new openerp.web.KeyNotFound(key);
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]];
274 if (object_match === undefined) {
275 throw new openerp.web.ObjectNotFound(path_string);
281 * Tries a number of keys, and returns the first object matching one of
284 * @param {Array} keys a sequence of keys to fetch the object for
285 * @returns {Class} the first class found matching an object
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
290 get_any: function (keys) {
291 for (var i=0; i<keys.length; ++i) {
293 if (key === undefined || !(key in this.map)) {
297 return this.get_object(key);
299 throw new openerp.web.KeyNotFound(keys.join(','));
302 * Adds a new key and value to the registry.
304 * This method can be chained.
306 * @param {String} key
307 * @param {String} object_path fully qualified dotted object path
308 * @returns {openerp.web.Registry} itself
310 add: function (key, object_path) {
311 this.map[key] = object_path;
315 * Creates and returns a copy of the current mapping, with the provided
316 * mapping argument added in (replacing existing keys if needed)
318 * @param {Object} [mapping={}] a mapping of keys to object-paths
320 clone: function (mapping) {
321 return new openerp.web.Registry(
322 _.extend({}, this.map, mapping || {}));
326 openerp.web.CallbackEnabled = openerp.web.Class.extend(/** @lends openerp.web.CallbackEnabled# */{
328 * @constructs openerp.web.CallbackEnabled
329 * @extends openerp.web.Class
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]);
345 openerp.web.Connection = openerp.web.CallbackEnabled.extend( /** @lends openerp.web.Connection# */{
347 * @constructs openerp.web.Connection
348 * @extends openerp.web.CallbackEnabled
350 * @param {String} [server] JSON-RPC endpoint hostname
351 * @param {String} [port] JSON-RPC endpoint port
355 // TODO: session store in cookie should be optional
356 this.name = openerp._session_id;
358 bind: function(host, protocol) {
360 this.host = (host == undefined) ? location.host : host;
361 this.protocol = (protocol == undefined) ? location.protocol : protocol;
362 this.prefix = this.protocol + '//' + this.host;
363 openerp.web.qweb.default_dict['_s'] = this.prefix
364 this.rpc_mode = (host == location.host) ? "json" : "jsonp";
365 this.debug = (window.location.search.indexOf('?debug') !== -1);
366 this.session_id = false;
368 this.username = false;
369 this.user_context= {};
371 this.module_list = [];
372 this.module_loaded = {"web": true};
375 this.active_id = null;
376 this.ready = $.Deferred();
377 return this.session_restore();
380 * Executes an RPC call, registering the provided callbacks.
382 * Registers a default error callback if none is provided, and handles
383 * setting the correct session id and session context in the parameter
386 * @param {String} url RPC endpoint
387 * @param {Object} params call parameters
388 * @param {Function} success_callback function to execute on RPC call success
389 * @param {Function} error_callback function to execute on RPC call failure
390 * @returns {jQuery.Deferred} jquery-provided ajax deferred
392 rpc: function(url, params, success_callback, error_callback) {
394 // url can be an $.ajax option object
395 if (_.isString(url)) {
398 // Construct a JSON-RPC2 request, method is currently unused
399 params.session_id = this.session_id;
406 id: _.uniqueId('oe-')
408 // Call using the rpc_mode
409 var deferred = $.Deferred();
410 this.on_rpc_request();
411 this.rpc_json(url, payload).then(
412 function (response, textStatus, jqXHR) {
413 self.on_rpc_response();
414 if (!response.error) {
415 deferred.resolve(response["result"], textStatus, jqXHR);
416 } else if (response.error.data.type === "session_invalid") {
418 self.on_session_invalid(function() {
419 self.rpc(url, payload.params,
420 function() { deferred.resolve.apply(deferred, arguments); },
421 function() { deferred.reject.apply(deferred, arguments); });
424 deferred.reject(response.error, $.Event());
427 function(jqXHR, textStatus, errorThrown) {
428 self.on_rpc_response();
431 message: "XmlHttpRequestError " + errorThrown,
432 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
434 deferred.reject(error, $.Event());
436 // Allow deferred user to disable on_rpc_error in fail
437 deferred.fail(function() {
438 deferred.fail(function(error, event) {
439 if (!event.isDefaultPrevented()) {
440 self.on_rpc_error(error, event);
443 }).then(success_callback, error_callback).promise();
449 * @returns {jQuery.Deferred} ajax-webd deferred object
451 rpc_json: function(url, payload) {
453 var ajax = _.extend({
456 contentType: 'application/json',
457 data: JSON.stringify(payload),
462 rpc_jsonp: function(url, payload) {
464 var ajax = _.extend({
470 session_id: this.session_id,
474 var payload_str = JSON.stringify(payload);
475 var payload_url = $.param({r:payload_str});
476 if(playload_url.length < 2000) {
477 // Direct json request
478 ajax.data.r = payload_str;
481 // Indirect json request
482 var ifid = _.uniqueId('oe_rpc_iframe_');
483 var display = options.openerp.debug ? 'block' : 'none';
484 var $iframe = $(_.str.sprintf("<iframe src='javascript:false;' name='%s' id='%s' style='display:%s'></iframe>", ifid, ifid, display));
485 var $form = $('<form>')
486 .attr('method', 'POST')
487 .attr('target', ifid)
488 .attr('enctype', "multipart/form-data")
489 .attr('action', ajax.url)
490 .append($('<input type="hidden" name="r" />').attr('value', payload_str))
492 .appendTo($('body'));
493 var cleanUp = function() {
495 $iframe.unbind("load").attr("src", "javascript:false;").remove();
499 var deferred = $.Deferred();
500 // the first bind is fired up when the iframe is added to the DOM
501 $iframe.bind('load', function() {
502 // the second bind is fired up when the result of the form submission is received
503 $iframe.unbind('load').bind('load', function() {
504 $.ajax(ajax).always(function() {
507 function() { deferred.resolve.apply(deferred, arguments); },
508 function() { deferred.reject.apply(deferred, arguments); }
511 // now that the iframe can receive data, we fill and submit the form
514 // append the iframe to the DOM (will trigger the first load)
515 $form.after($iframe);
519 on_rpc_request: function() {
521 on_rpc_response: function() {
523 on_rpc_error: function(error) {
526 * Init a session, reloads from cookie, if it exists
528 session_restore: function () {
530 // TODO: session store in cookie should be optional
531 this.session_id = this.get_cookie('session_id');
532 return this.rpc("/web/session/get_session_info", {}).pipe(function(result) {
533 // If immediately follows a login (triggered by trying to restore
534 // an invalid session or no session at all), refresh session data
535 // (should not change, but just in case...)
538 username: result.login,
540 user_context: result.context
542 var deferred = self.do_load_qweb(['/web/webclient/qweb']);
544 return deferred.then(self.load_modules());
550 * The session is validated either by login or by restoration of a previous session
552 session_authenticate: function(db, login, password) {
554 var base_location = document.location.protocol + '//' + document.location.host;
555 var params = { db: db, login: login, password: password, base_location: base_location };
556 return this.rpc("/web/session/authenticate", params).pipe(function(result) {
558 session_id: result.session_id,
560 username: result.login,
562 user_context: result.context
564 // TODO: session store in cookie should be optional
565 self.set_cookie('session_id', this.session_id);
566 return self.load_modules();
569 session_logout: function() {
570 this.set_cookie('session_id', '');
571 window.location.reload();
574 * Fetches a cookie stored by an openerp session
577 * @param name the cookie's name
579 get_cookie: function (name) {
580 if (!this.name) { return null; }
581 var nameEQ = this.name + '|' + name + '=';
582 var cookies = document.cookie.split(';');
583 for(var i=0; i<cookies.length; ++i) {
584 var cookie = cookies[i].replace(/^\s*/, '');
585 if(cookie.indexOf(nameEQ) === 0) {
586 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
592 * Create a new cookie with the provided name and value
595 * @param name the cookie's name
596 * @param value the cookie's value
597 * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
599 set_cookie: function (name, value, ttl) {
600 if (!this.name) { return; }
601 ttl = ttl || 24*60*60*365;
603 this.name + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
606 'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
610 * Load additional web addons of that instance and init them
612 load_modules: function() {
614 if(openerp._modules_loaded) {
617 this.rpc('/web/session/modules', {}, function(result) {
618 self.module_list = result;
619 var lang = self.user_context.lang;
620 var params = { mods: ["web"].concat(result), lang: lang};
621 self.rpc('/web/webclient/translations',params).pipe(function(transs) {
622 openerp.web._t.database.set_bundle(transs);
623 var modules = self.module_list.join(',');
624 var file_list = ["/web/static/lib/datejs/globalization/" +
625 self.user_context.lang.replace("_", "-") + ".js"
628 self.rpc('/web/webclient/csslist', {mods: modules}, self.do_load_css),
629 self.rpc('/web/webclient/qweblist', {mods: modules}).pipe(self.do_load_qweb),
630 self.rpc('/web/webclient/jslist', {mods: modules}).pipe(function(files) {
631 self.do_load_js(file_list.concat(files));
634 self.ready.resolve();
639 do_load_css: function (files) {
641 _.each(files, function (file) {
642 $('head').append($('<link>', {
643 'href': self.get_url(file),
649 do_load_js: function(files) {
651 var d = $.Deferred();
652 if(files.length != 0) {
653 var file = files.shift();
654 var tag = document.createElement('script');
655 tag.type = 'text/javascript';
656 tag.src = self.get_url(file);
657 tag.onload = tag.onreadystatechange = function() {
658 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
660 tag.onload_done = true;
661 self.do_load_js(files).then(function () {
665 var head = document.head || document.getElementsByTagName('head')[0];
666 head.appendChild(tag);
668 self.on_modules_loaded();
673 do_load_qweb: function(files) {
675 if (files.length != 0) {
676 var file = files.shift();
677 return self.rpc('/web/proxy/load', {path: file}).pipe(function(xml) {
678 openerp.web.qweb.add_template(_.str.trim(xml));
679 return self.do_load_qweb(files);
685 on_modules_loaded: function() {
686 for(var j=0; j<this.module_list.length; j++) {
687 var mod = this.module_list[j];
688 if(this.module_loaded[mod])
692 if(openerp._openerp[mod] != undefined) {
693 openerp._openerp[mod](openerp);
694 this.module_loaded[mod] = true;
699 * Cooperative file download implementation, for ajaxy APIs.
701 * Requires that the server side implements an httprequest correctly
702 * setting the `fileToken` cookie to the value provided as the `token`
703 * parameter. The cookie *must* be set on the `/` path and *must not* be
706 * It would probably also be a good idea for the response to use a
707 * `Content-Disposition: attachment` header, especially if the MIME is a
708 * "known" type (e.g. text/plain, or for some browsers application/json
710 * @param {Object} options
711 * @param {String} [options.url] used to dynamically create a form
712 * @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
713 * @param {HTMLFormElement} [options.form] the form to submit in order to fetch the file
714 * @param {Function} [options.success] callback in case of download success
715 * @param {Function} [options.error] callback in case of request error, provided with the error body
716 * @param {Function} [options.complete] called after both ``success`` and ``error` callbacks have executed
718 get_url: function (file) {
719 return this.prefix + file;
721 get_file: function (options) {
722 // need to detect when the file is done downloading (not used
723 // yet, but we'll need it to fix the UI e.g. with a throbber
724 // while dump is being generated), iframe load event only fires
725 // when the iframe content loads, so we need to go smarter:
726 // http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
727 var timer, token = new Date().getTime(),
728 cookie_name = 'fileToken', cookie_length = cookie_name.length,
729 CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
732 var $form, $form_data = $('<div>');
734 var complete = function () {
735 if (options.complete) { options.complete(); }
739 if (remove_form && $form) { $form.remove(); }
741 var $target = $('<iframe style="display: none;">')
742 .attr({id: id, name: id})
743 .appendTo(document.body)
745 if (options.error) { options.error(this.contentDocument.body); }
750 $form = $(options.form);
753 $form = $('<form>', {
756 }).appendTo(document.body);
759 _(_.extend({}, options.data || {},
760 {session_id: this.session_id, token: token}))
761 .each(function (value, key) {
762 $('<input type="hidden" name="' + key + '">')
764 .appendTo($form_data);
772 var waitLoop = function () {
773 var cookies = document.cookie.split(';');
775 timer = setTimeout(waitLoop, CHECK_INTERVAL);
776 for (var i=0; i<cookies.length; ++i) {
777 var cookie = cookies[i].replace(/^\s*/, '');
778 if (!cookie.indexOf(cookie_name === 0)) { continue; }
779 var cookie_val = cookie.substring(cookie_length + 1);
780 if (parseInt(cookie_val, 10) !== token) { continue; }
783 document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
784 cookie_name, new Date().toGMTString());
785 if (options.success) { options.success(); }
790 timer = setTimeout(waitLoop, CHECK_INTERVAL);
795 * Base class for all visual components. Provides a lot of functionalities helpful
796 * for the management of a part of the DOM.
799 * - Rendering with QWeb.
800 * - Life-cycle management and parenting (when a parent is destroyed, all its children are
802 * - Insertion in DOM.
804 * Guide to create implementations of the Widget class:
805 * ==============================================
807 * Here is a sample child class:
809 * MyWidget = openerp.base.Widget.extend({
810 * // the name of the QWeb template to use for rendering
811 * template: "MyQWebTemplate",
812 * // identifier prefix, it is useful to put an obvious one for debugging
813 * identifier_prefix: 'my-id-prefix-',
815 * init: function(parent) {
816 * this._super(parent);
817 * // stuff that you want to init before the rendering
819 * start: function() {
820 * // stuff you want to make after the rendering, `this.$element` holds a correct value
821 * this.$element.find(".my_button").click(/* an example of event binding * /);
823 * // if you have some asynchronous operations, it's a good idea to return
824 * // a promise in start()
825 * var promise = this.rpc(...);
830 * Now this class can simply be used with the following syntax:
832 * var my_widget = new MyWidget(this);
833 * my_widget.appendTo($(".some-div"));
835 * With these two lines, the MyWidget instance was inited, rendered, it was inserted into the
836 * DOM inside the ".some-div" div and its events were binded.
838 * And of course, when you don't need that widget anymore, just do:
842 * That will kill the widget in a clean way and erase its content from the dom.
844 openerp.web.Widget = openerp.web.CallbackEnabled.extend(/** @lends openerp.web.Widget# */{
846 * The name of the QWeb template that will be used for rendering. Must be
847 * redefined in subclasses or the default render() method can not be used.
853 * The prefix used to generate an id automatically. Should be redefined in
854 * subclasses. If it is not defined, a generic identifier will be used.
858 identifier_prefix: 'generic-identifier-',
860 * Tag name when creating a default $element.
865 * Constructs the widget and sets its parent if a parent is given.
867 * @constructs openerp.web.Widget
868 * @extends openerp.web.CallbackEnabled
870 * @param {openerp.web.Widget} parent Binds the current instance to the given Widget instance.
871 * When that widget is destroyed by calling stop(), the current instance will be
872 * destroyed too. Can be null.
873 * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
874 * to bind the current Widget to an already existing part of the DOM, which is not compatible
875 * with the DOM insertion methods provided by the current implementation of Widget. So
876 * for new components this argument should not be provided any more.
878 init: function(parent, /** @deprecated */ element_id) {
880 this.session = openerp.connection;
881 // if given an element_id, try to get the associated DOM element and save
882 // a reference in this.$element. Else just generate a unique identifier.
883 this.element_id = element_id;
884 this.element_id = this.element_id || _.uniqueId(this.identifier_prefix);
885 var tmp = document.getElementById(this.element_id);
886 this.$element = tmp ? $(tmp) : $(document.createElement(this.tag_name));
888 this.widget_parent = parent;
889 this.widget_children = [];
890 if(parent && parent.widget_children) {
891 parent.widget_children.push(this);
893 // useful to know if the widget was destroyed and should not be used anymore
894 this.widget_is_stopped = false;
897 * Renders the current widget and appends it to the given jQuery object or Widget.
899 * @param target A jQuery object or a Widget instance.
901 appendTo: function(target) {
903 return this._render_and_insert(function(t) {
904 self.$element.appendTo(t);
908 * Renders the current widget and prepends it to the given jQuery object or Widget.
910 * @param target A jQuery object or a Widget instance.
912 prependTo: function(target) {
914 return this._render_and_insert(function(t) {
915 self.$element.prependTo(t);
919 * Renders the current widget and inserts it after to the given jQuery object or Widget.
921 * @param target A jQuery object or a Widget instance.
923 insertAfter: function(target) {
925 return this._render_and_insert(function(t) {
926 self.$element.insertAfter(t);
930 * Renders the current widget and inserts it before to the given jQuery object or Widget.
932 * @param target A jQuery object or a Widget instance.
934 insertBefore: function(target) {
936 return this._render_and_insert(function(t) {
937 self.$element.insertBefore(t);
941 * Renders the current widget and replaces the given jQuery object.
943 * @param target A jQuery object or a Widget instance.
945 replace: function(target) {
946 return this._render_and_insert(_.bind(function(t) {
947 this.$element.replaceAll(t);
950 _render_and_insert: function(insertion, target) {
951 this.render_element();
952 if (target instanceof openerp.web.Widget)
953 target = target.$element;
955 this.on_inserted(this.$element, this);
958 on_inserted: function(element, widget) {},
960 * Renders the element and insert the result of the render() method in this.$element.
962 render_element: function() {
963 var rendered = this.render();
965 var elem = $(rendered);
966 this.$element.replaceWith(elem);
967 this.$element = elem;
972 * Renders the widget using QWeb, `this.template` must be defined.
973 * The context given to QWeb contains the "widget" key that references `this`.
975 * @param {Object} additional Additional context arguments to pass to the template.
977 render: function (additional) {
979 return openerp.web.qweb.render(this.template, _.extend({widget: this}, additional || {}));
983 * Method called after rendering. Mostly used to bind actions, perform asynchronous
986 * By convention, the method should return a promise to inform the caller when
987 * this widget has been initialized.
989 * @returns {jQuery.Deferred}
992 return $.Deferred().done().promise();
995 * Destroys the current widget, also destroys all its children before destroying itself.
998 _.each(_.clone(this.widget_children), function(el) {
1001 if(this.$element != null) {
1002 this.$element.remove();
1004 if (this.widget_parent && this.widget_parent.widget_children) {
1005 this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
1007 this.widget_parent = null;
1008 this.widget_is_stopped = true;
1011 * Informs the action manager to do an action. This supposes that
1012 * the action manager can be found amongst the ancestors of the current widget.
1013 * If that's not the case this method will simply return `false`.
1015 do_action: function(action, on_finished) {
1016 if (this.widget_parent) {
1017 return this.widget_parent.do_action(action, on_finished);
1021 do_notify: function() {
1022 if (this.widget_parent) {
1023 return this.widget_parent.do_notify.apply(this,arguments);
1027 do_warn: function() {
1028 if (this.widget_parent) {
1029 return this.widget_parent.do_warn.apply(this,arguments);
1034 rpc: function(url, data, success, error) {
1035 var def = $.Deferred().then(success, error);
1037 openerp.connection.rpc(url, data). then(function() {
1038 if (!self.widget_is_stopped)
1039 def.resolve.apply(def, arguments);
1041 if (!self.widget_is_stopped)
1042 def.reject.apply(def, arguments);
1044 return def.promise();
1050 * @extends openerp.web.Widget
1052 * For retro compatibility only, the only difference with is that render() uses
1053 * directly ``this`` instead of context with a ``widget`` key.
1055 openerp.web.OldWidget = openerp.web.Widget.extend(/** @lends openerp.web.OldWidget# */{
1056 render: function (additional) {
1057 return openerp.web.qweb.render(this.template, _.extend(_.extend({}, this), additional || {}));
1061 openerp.web.TranslationDataBase = openerp.web.Class.extend(/** @lends openerp.web.TranslationDataBase# */{
1063 * @constructs openerp.web.TranslationDataBase
1064 * @extends openerp.web.Class
1068 this.parameters = {"direction": 'ltr',
1069 "date_format": '%m/%d/%Y',
1070 "time_format": '%H:%M:%S',
1072 "decimal_point": ".",
1073 "thousands_sep": ","};
1075 set_bundle: function(translation_bundle) {
1078 var modules = _.keys(translation_bundle.modules);
1080 if (_.include(modules, "web")) {
1081 modules = ["web"].concat(_.without(modules, "web"));
1083 _.each(modules, function(name) {
1084 self.add_module_translation(translation_bundle.modules[name]);
1086 if (translation_bundle.lang_parameters) {
1087 this.parameters = translation_bundle.lang_parameters;
1088 this.parameters.grouping = py.eval(
1089 this.parameters.grouping).toJSON();
1092 add_module_translation: function(mod) {
1094 _.each(mod.messages, function(message) {
1095 if (self.db[message.id] === undefined) {
1096 self.db[message.id] = message.string;
1100 build_translation_function: function() {
1102 var fcnt = function(str) {
1103 var tmp = self.get(str);
1104 return tmp === undefined ? str : tmp;
1106 fcnt.database = this;
1109 get: function(key) {
1111 return this.db[key];
1116 /** Configure blockui */
1118 $.blockUI.defaults.baseZ = 1100;
1119 $.blockUI.defaults.message = '<img src="/web/static/src/img/throbber2.gif">';
1122 /** Configure default qweb */
1123 openerp.web._t = new openerp.web.TranslationDataBase().build_translation_function();
1124 openerp.web.qweb = new QWeb2.Engine();
1125 openerp.web.qweb.debug = (window.location.search.indexOf('?debug') !== -1);
1126 openerp.web.qweb.default_dict = {
1128 '_t' : openerp.web._t
1130 openerp.web.qweb.format_text_node = function(s) {
1131 // Note that 'this' is the Qweb Node of the text
1132 var translation = this.node.parentNode.attributes['t-translation'];
1133 if (translation && translation.value === 'off') {
1136 var ts = _.str.trim(s);
1137 if (ts.length === 0) {
1140 var tr = openerp.web._t(ts);
1141 return tr === ts ? s : tr;
1144 /** Setup default connection */
1145 openerp.connection = new openerp.web.Connection();
1146 openerp.web.qweb.default_dict['__debug__'] = openerp.connection.debug;
1148 /** Jquery extentions */
1149 $.Mutex = (function() {
1151 this.def = $.Deferred().resolve();
1153 Mutex.prototype.exec = function(action) {
1154 var current = this.def;
1155 var next = this.def = $.Deferred();
1156 return current.pipe(function() {
1157 return $.when(action()).always(function() {
1165 $.async_when = function() {
1167 var def = $.Deferred();
1168 $.when.apply($, arguments).then(function() {
1169 var args = arguments;
1170 var action = function() {
1171 def.resolve.apply(def, args);
1176 setTimeout(action, 0);
1178 var args = arguments;
1179 var action = function() {
1180 def.reject.apply(def, args);
1185 setTimeout(action, 0);
1193 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: