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
353 init: function(server, port) {
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;
361 this.username = false;
362 this.user_context= {};
364 this.module_list = [];
365 this.module_loaded = {"web": true};
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']);
376 this.session_restore();
379 * Executes an RPC call, registering the provided callbacks.
381 * Registers a default error callback if none is provided, and handles
382 * setting the correct session id and session context in the parameter
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
391 rpc: function(url, params, success_callback, error_callback) {
393 // Construct a JSON-RPC2 request, method is currently unused
394 params.session_id = this.session_id;
398 // Call using the rpc_mode
399 var deferred = $.Deferred();
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);
413 }).then(success_callback, error_callback).promise();
418 * @returns {jQuery.Deferred} ajax-webd deferred object
420 rpc_ajax: function(url, payload) {
422 this.on_rpc_request();
423 // url can be an $.ajax option object
424 if (_.isString(url)) {
429 var ajax = _.extend({
433 contentType: 'application/json',
434 data: JSON.stringify(payload),
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);
444 if (response.error.data.type !== "session_invalid") {
445 deferred.reject(response.error);
449 self.on_session_invalid(function() {
450 self.rpc(url, payload.params,
452 deferred.resolve.apply(deferred, arguments);
454 function(error, event) {
455 event.preventDefault();
456 deferred.reject.apply(deferred, arguments);
459 }).fail(function(jqXHR, textStatus, errorThrown) {
460 self.on_rpc_response();
463 message: "XmlHttpRequestError " + errorThrown,
464 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
466 deferred.reject(error);
468 return deferred.promise();
470 on_rpc_request: function() {
472 on_rpc_response: function() {
474 on_rpc_error: function(error) {
477 * The session is validated either by login or by restoration of a previous session
479 on_session_valid: function() {
480 if(!openerp._modules_loaded)
483 on_session_invalid: function(contination) {
485 session_is_valid: function() {
488 session_login: function(db, login, password, success_callback) {
490 var params = { db: db, login: login, password: password };
491 return this.rpc("/web/session/login", params, function(result) {
493 session_id: result.session_id,
495 user_context: result.context,
497 username: result.login
500 self.on_session_valid();
502 }).then(success_callback);
504 login: function() { this.session_login.apply(this, arguments); },
506 * Reloads uid and session_id from local storage, if they exist
508 session_restore: function () {
510 this.session_id = this.get_cookie('session_id');
511 return this.rpc("/web/session/get_session_info", {}).then(function(result) {
514 user_context: result.context,
516 username: result.login
519 self.on_session_valid();
521 self.on_session_invalid();
523 self.on_session_invalid();
527 * Saves the session id and uid locally
529 session_save: function () {
530 this.set_cookie('session_id', this.session_id);
533 this.set_cookie('session_id', '');
534 this.reload_client();
536 reload_client: function() {
537 window.location.reload();
540 * Fetches a cookie stored by an openerp session
543 * @param name the cookie's name
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)));
558 * Create a new cookie with the provided name and value
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
565 set_cookie: function (name, value, ttl) {
566 if (!this.name) { return; }
567 ttl = ttl || 24*60*60*365;
569 this.name + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
572 'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
576 * Load additional web addons of that instance and init them
578 load_modules: function() {
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"
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));
595 self.rpc('/web/webclient/qweblist', {"mods": modules}, self.do_load_qweb);
596 openerp._modules_loaded = true;
600 do_load_css: function (files) {
602 _.each(files, function (file) {
603 $('head').append($('<link>', {
610 do_load_js: function(files) {
612 if(files.length != 0) {
613 var file = files.shift();
614 var tag = document.createElement('script');
615 tag.type = 'text/javascript';
617 tag.onload = tag.onreadystatechange = function() {
618 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
620 tag.onload_done = true;
621 self.do_load_js(files);
623 var head = document.head || document.getElementsByTagName('head')[0];
624 head.appendChild(tag);
626 this.on_modules_loaded();
629 do_load_qweb: function(files) {
631 _.each(files, function(file) {
632 openerp.web.qweb.add_template(file);
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])
642 if(openerp._openerp[mod] != undefined) {
643 openerp._openerp[mod](openerp);
644 this.module_loaded[mod] = true;
649 * Cooperative file download implementation, for ajaxy APIs.
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
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
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
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'),
679 var $form, $form_data = $('<div>');
681 var complete = function () {
682 if (options.complete) { options.complete(); }
686 if (remove_form && $form) { $form.remove(); }
688 var $target = $('<iframe style="display: none;">')
689 .attr({id: id, name: id})
690 .appendTo(document.body)
692 if (options.error) { options.error(this.contentDocument.body); }
697 $form = $(options.form);
700 $form = $('<form>', {
703 }).appendTo(document.body);
706 _(_.extend({}, options.data || {},
707 {session_id: this.session_id, token: token}))
708 .each(function (value, key) {
709 $('<input type="hidden" name="' + key + '">')
711 .appendTo($form_data);
719 var waitLoop = function () {
720 var cookies = document.cookie.split(';');
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; }
730 document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
731 cookie_name, new Date().toGMTString());
732 if (options.success) { options.success(); }
737 timer = setTimeout(waitLoop, CHECK_INTERVAL);
742 * Base class for all visual components. Provides a lot of functionalities helpful
743 * for the management of a part of the DOM.
746 * - Rendering with QWeb.
747 * - Life-cycle management and parenting (when a parent is destroyed, all its children are
749 * - Insertion in DOM.
751 * Guide to create implementations of the Widget class:
752 * ==============================================
754 * Here is a sample child class:
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-',
762 * init: function(parent) {
763 * this._super(parent);
764 * // stuff that you want to init before the rendering
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 * /);
770 * // if you have some asynchronous operations, it's a good idea to return
771 * // a promise in start()
772 * var promise = this.rpc(...);
777 * Now this class can simply be used with the following syntax:
779 * var my_widget = new MyWidget(this);
780 * my_widget.appendTo($(".some-div"));
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.
785 * And of course, when you don't need that widget anymore, just do:
789 * That will kill the widget in a clean way and erase its content from the dom.
791 openerp.web.Widget = openerp.web.CallbackEnabled.extend(/** @lends openerp.web.Widget# */{
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.
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.
805 identifier_prefix: 'generic-identifier-',
807 * Tag name when creating a default $element.
812 * Construct the widget and set its parent if a parent is given.
814 * @constructs openerp.web.Widget
815 * @extends openerp.web.CallbackEnabled
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.
825 init: function(parent, /** @deprecated */ element_id) {
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));
835 this.widget_parent = parent;
836 this.widget_children = [];
837 if(parent && parent.widget_children) {
838 parent.widget_children.push(this);
840 // useful to know if the widget was destroyed and should not be used anymore
841 this.widget_is_stopped = false;
844 * Render the current widget and appends it to the given jQuery object or Widget.
846 * @param target A jQuery object or a Widget instance.
848 appendTo: function(target) {
850 return this._render_and_insert(function(t) {
851 self.$element.appendTo(t);
855 * Render the current widget and prepends it to the given jQuery object or Widget.
857 * @param target A jQuery object or a Widget instance.
859 prependTo: function(target) {
861 return this._render_and_insert(function(t) {
862 self.$element.prependTo(t);
866 * Render the current widget and inserts it after to the given jQuery object or Widget.
868 * @param target A jQuery object or a Widget instance.
870 insertAfter: function(target) {
872 return this._render_and_insert(function(t) {
873 self.$element.insertAfter(t);
877 * Render the current widget and inserts it before to the given jQuery object or Widget.
879 * @param target A jQuery object or a Widget instance.
881 insertBefore: function(target) {
883 return this._render_and_insert(function(t) {
884 self.$element.insertBefore(t);
887 _render_and_insert: function(insertion, target) {
888 this.render_element();
889 if (target instanceof openerp.web.Widget)
890 target = target.$element;
892 this.on_inserted(this.$element, this);
895 on_inserted: function(element, widget) {},
897 * Renders the element and insert the result of the render() method in this.$element.
899 render_element: function() {
900 var rendered = this.render();
902 var elem = $(rendered);
903 this.$element.replaceWith(elem);
904 this.$element = elem;
909 * Renders the widget using QWeb, `this.template` must be defined.
910 * The context given to QWeb contains the "widget" key that references `this`.
912 * @param {Object} additional Additional context arguments to pass to the template.
914 render: function (additional) {
916 return openerp.web.qweb.render(this.template, _.extend({widget: this}, additional || {}));
920 * Method called after rendering. Mostly used to bind actions, perform asynchronous
923 * By convention, the method should return a promise to inform the caller when
924 * this widget has been initialized.
926 * @returns {jQuery.Deferred}
929 return $.Deferred().done().promise();
932 * Destroys the current widget, also destroy all its children before destroying itself.
935 _.each(_.clone(this.widget_children), function(el) {
938 if(this.$element != null) {
939 this.$element.remove();
941 if (this.widget_parent && this.widget_parent.widget_children) {
942 this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
944 this.widget_parent = null;
945 this.widget_is_stopped = true;
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`.
952 do_action: function(action, on_finished) {
953 if (this.widget_parent) {
954 return this.widget_parent.do_action(action, on_finished);
958 do_notify: function() {
959 if (this.widget_parent) {
960 return this.widget_parent.do_notify.apply(this,arguments);
964 do_warn: function() {
965 if (this.widget_parent) {
966 return this.widget_parent.do_warn.apply(this,arguments);
970 rpc: function(url, data, success, error) {
971 var def = $.Deferred().then(success, error);
973 openerp.connection.rpc(url, data). then(function() {
974 if (!self.widget_is_stopped)
975 def.resolve.apply(def, arguments);
977 if (!self.widget_is_stopped)
978 def.reject.apply(def, arguments);
980 return def.promise();
986 * @extends openerp.web.Widget
988 * For retro compatibility only, the only difference with is that render() uses
989 * directly ``this`` instead of context with a ``widget`` key.
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 || {}));
997 openerp.web.TranslationDataBase = openerp.web.Class.extend(/** @lends openerp.web.TranslationDataBase# */{
999 * @constructs openerp.web.TranslationDataBase
1000 * @extends openerp.web.Class
1004 this.parameters = {"direction": 'ltr',
1005 "date_format": '%m/%d/%Y',
1006 "time_format": '%H:%M:%S',
1008 "decimal_point": ".",
1009 "thousands_sep": ","};
1011 set_bundle: function(translation_bundle) {
1014 var modules = _.keys(translation_bundle.modules).sort();
1015 if (_.include(modules, "web")) {
1016 modules = ["web"].concat(_.without(modules, "web"));
1018 _.each(modules, function(name) {
1019 self.add_module_translation(translation_bundle.modules[name]);
1021 if (translation_bundle.lang_parameters) {
1022 this.parameters = translation_bundle.lang_parameters;
1023 this.parameters.grouping = py.eval(
1024 this.parameters.grouping).toJSON();
1027 add_module_translation: function(mod) {
1029 _.each(mod.messages, function(message) {
1030 if (self.db[message.id] === undefined) {
1031 self.db[message.id] = message.string;
1035 build_translation_function: function() {
1037 var fcnt = function(str) {
1038 var tmp = self.get(str);
1039 return tmp === undefined ? str : tmp;
1041 fcnt.database = this;
1044 get: function(key) {
1046 return this.db[key];
1052 $.blockUI.defaults.baseZ = 1100;
1053 $.blockUI.defaults.message = '<img src="/web/static/src/img/throbber2.gif">';
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 = {
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') {
1069 var ts = _.str.trim(s);
1070 if (ts.length === 0) {
1073 var tr = openerp.web._t(ts);
1074 return tr === ts ? s : tr;
1077 /** Setup default connection */
1078 openerp.connection = new openerp.web.Connection();
1082 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: