1 /*---------------------------------------------------------
3 *--------------------------------------------------------*/
5 openerp.base.core = function(openerp) {
7 * John Resig Class with factory improvement
10 var initializing = false,
11 fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
12 // The base Class implementation (does nothing)
13 openerp.base.Class = function(){};
15 // Create a new Class that inherits from this class
16 openerp.base.Class.extend = function(prop) {
17 var _super = this.prototype;
19 // Instantiate a base class (but only create the instance,
20 // don't run the init constructor)
22 var prototype = new this();
25 // Copy the properties over onto the new prototype
26 for (var name in prop) {
27 // Check if we're overwriting an existing function
28 prototype[name] = typeof prop[name] == "function" &&
29 typeof _super[name] == "function" &&
30 fnTest.test(prop[name]) ?
33 var tmp = this._super;
35 // Add a new ._super() method that is the same
36 // method but on the super-class
37 this._super = _super[name];
39 // The method only need to be bound temporarily, so
40 // we remove it when we're done executing
41 var ret = fn.apply(this, arguments);
46 })(name, prop[name]) :
50 // The dummy class constructor
52 // All construction is actually done in the init method
53 if (!initializing && this.init) {
54 var ret = this.init.apply(this, arguments);
55 if (ret) { return ret; }
59 Class.include = function (properties) {
60 for (var name in properties) {
61 if (typeof properties[name] !== 'function'
62 || !fnTest.test(properties[name])) {
63 prototype[name] = properties[name];
64 } else if (typeof prototype[name] === 'function'
65 && prototype.hasOwnProperty(name)) {
66 prototype[name] = (function (name, fn, previous) {
68 var tmp = this._super;
69 this._super = previous;
70 var ret = fn.apply(this, arguments);
74 })(name, properties[name], prototype[name]);
75 } else if (typeof _super[name] === 'function') {
76 prototype[name] = (function (name, fn) {
78 var tmp = this._super;
79 this._super = _super[name];
80 var ret = fn.apply(this, arguments);
84 })(name, properties[name]);
89 // Populate our constructed prototype object
90 Class.prototype = prototype;
92 // Enforce the constructor to be what we expect
93 Class.constructor = Class;
95 // And make this class extendable
96 Class.extend = arguments.callee;
102 openerp.base.callback = function(obj, method) {
103 var callback = function() {
104 var args = Array.prototype.slice.call(arguments);
106 for(var i = 0; i < callback.callback_chain.length; i++) {
107 var c = callback.callback_chain[i];
109 callback.callback_chain.splice(i, 1);
112 r = c.callback.apply(c.self, c.args.concat(args));
113 // TODO special value to stop the chain
114 // openerp.base.callback_stop
118 callback.callback_chain = [];
119 callback.add = function(f) {
120 if(typeof(f) == 'function') {
121 f = { callback: f, args: Array.prototype.slice.call(arguments, 1) };
123 f.self = f.self || null;
124 f.args = f.args || [];
125 f.unique = !!f.unique;
126 if(f.position == 'last') {
127 callback.callback_chain.push(f);
129 callback.callback_chain.unshift(f);
133 callback.add_first = function(f) {
134 return callback.add.apply(null,arguments);
136 callback.add_last = function(f) {
137 return callback.add({
139 args: Array.prototype.slice.call(arguments, 1),
144 return callback.add({
147 args:Array.prototype.slice.call(arguments, 2)
152 * Generates an inherited class that replaces all the methods by null methods (methods
153 * that does nothing and always return undefined).
155 * @param {Class} claz
156 * @param {dict} add Additional functions to override.
159 openerp.base.generate_null_object_class = function(claz, add) {
161 var copy_proto = function(prototype) {
162 for (var name in prototype) {
163 if(typeof prototype[name] == "function") {
164 newer[name] = function() {};
167 if (prototype.prototype)
168 copy_proto(prototype.prototype);
170 copy_proto(claz.prototype);
171 newer.init = openerp.base.Widget.prototype.init;
172 var tmpclass = claz.extend(newer);
173 return tmpclass.extend(add || {});
177 * Base error for lookup failure
181 openerp.base.NotFound = openerp.base.Class.extend( /** @lends openerp.base.NotFound# */ {
183 openerp.base.KeyNotFound = openerp.base.NotFound.extend( /** @lends openerp.base.KeyNotFound# */ {
185 * Thrown when a key could not be found in a mapping
188 * @extends openerp.base.NotFound
189 * @param {String} key the key which could not be found
191 init: function (key) {
194 toString: function () {
195 return "The key " + this.key + " was not found";
198 openerp.base.ObjectNotFound = openerp.base.NotFound.extend( /** @lends openerp.base.ObjectNotFound# */ {
200 * Thrown when an object path does not designate a valid class or object
201 * in the openerp hierarchy.
204 * @extends openerp.base.NotFound
205 * @param {String} path the invalid object path
207 init: function (path) {
210 toString: function () {
211 return "Could not find any object of path " + this.path;
214 openerp.base.Registry = openerp.base.Class.extend( /** @lends openerp.base.Registry# */ {
216 * Stores a mapping of arbitrary key (strings) to object paths (as strings
219 * Resolves those paths at query time in order to always fetch the correct
220 * object, even if those objects have been overloaded/replaced after the
221 * registry was created.
223 * An object path is simply a dotted name from the openerp root to the
224 * object pointed to (e.g. ``"openerp.base.Session"`` for an OpenERP
228 * @param {Object} mapping a mapping of keys to object-paths
230 init: function (mapping) {
231 this.map = mapping || {};
234 * Retrieves the object matching the provided key string.
236 * @param {String} key the key to fetch the object for
237 * @returns {Class} the stored class, to initialize
239 * @throws {openerp.base.KeyNotFound} if the object was not in the mapping
240 * @throws {openerp.base.ObjectNotFound} if the object path was invalid
242 get_object: function (key) {
243 var path_string = this.map[key];
244 if (path_string === undefined) {
245 throw new openerp.base.KeyNotFound(key);
248 var object_match = openerp;
249 var path = path_string.split('.');
250 // ignore first section
251 for(var i=1; i<path.length; ++i) {
252 object_match = object_match[path[i]];
254 if (object_match === undefined) {
255 throw new openerp.base.ObjectNotFound(path_string);
261 * Tries a number of keys, and returns the first object matching one of
264 * @param {Array} keys a sequence of keys to fetch the object for
265 * @returns {Class} the first class found matching an object
267 * @throws {openerp.base.KeyNotFound} if none of the keys was in the mapping
268 * @trows {openerp.base.ObjectNotFound} if a found object path was invalid
270 get_any: function (keys) {
271 for (var i=0; i<keys.length; ++i) {
273 return this.get_object(keys[i]);
275 if (e instanceof openerp.base.KeyNotFound) {
281 throw new openerp.base.KeyNotFound(keys.join(','));
284 * Adds a new key and value to the registry.
286 * This method can be chained.
288 * @param {String} key
289 * @param {String} object_path fully qualified dotted object path
290 * @returns {openerp.base.Registry} itself
292 add: function (key, object_path) {
293 this.map[key] = object_path;
297 * Creates and returns a copy of the current mapping, with the provided
298 * mapping argument added in (replacing existing keys if needed)
300 * @param {Object} [mapping={}] a mapping of keys to object-paths
302 clone: function (mapping) {
303 return new openerp.base.Registry(
304 _.extend({}, this.map, mapping || {}));
308 openerp.base.CallbackEnabled = openerp.base.Class.extend({
310 // Transform on_* method into openerp.base.callbacks
311 for (var name in this) {
312 if(typeof(this[name]) == "function") {
313 this[name].debug_name = name;
314 // bind ALL function to this not only on_and _do ?
315 if((/^on_|^do_/).test(name)) {
316 this[name] = openerp.base.callback(this, this[name]);
324 * Utility class that any class is allowed to extend to easy common manipulations.
326 * It provides rpc calls, callback on all methods preceded by "on_" or "do_" and a
329 openerp.base.SessionAware = openerp.base.CallbackEnabled.extend({
330 init: function(session) {
332 this.session = session;
335 * Performs a JSON-RPC call
337 * @param {String} url endpoint url
338 * @param {Object} data RPC parameters
339 * @param {Function} success RPC call success callback
340 * @param {Function} error RPC call error callback
341 * @returns {jQuery.Deferred} deferred object for the RPC call
343 rpc: function(url, data, success, error) {
344 return this.session.rpc(url, data, success, error);
347 var args = Array.prototype.slice.call(arguments);
348 var caller = arguments.callee.caller;
349 // TODO add support for line number using
350 // https://github.com/emwendelin/javascript-stacktrace/blob/master/stacktrace.js
351 // args.unshift("" + caller.debug_name);
352 this.on_log.apply(this,args);
355 if(window.openerp.debug || (window.location.search.indexOf('?debug') !== -1)) {
359 console.log(arguments);
363 var a = Array.prototype.slice.call(arguments, 0);
364 for(var i = 0; i < a.length; i++) {
365 var v = a[i]==null ? "null" : a[i].toString();
367 notify = v.match(/^not/);
368 body = v.match(/^bod/);
371 $('<pre></pre>').text(v).appendTo($('body'));
373 if(notify && this.notification) {
374 this.notification.notify("Logging:",v);
381 openerp.base.Widget = openerp.base.SessionAware.extend({
383 * The name of the QWeb template that will be used for rendering. Must be
384 * redefined in subclasses or the default render() method can not be used.
390 * The prefix used to generate an id automatically. Should be redefined in
391 * subclasses. If it is not defined, a generic identifier will be used.
395 identifier_prefix: 'generic-identifier-',
397 * Construct the widget and set its parent if a parent is given.
400 * @param {openerp.base.Widget} parent Binds the current instance to the given Widget instance.
401 * When that widget is destroyed by calling stop(), the current instance will be
402 * destroyed too. Can be null.
403 * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
404 * to bind the current Widget to an already existing part of the DOM, which is not compatible
405 * with the DOM insertion methods provided by the current implementation of Widget. So
406 * for new components this argument should not be provided any more.
408 init: function(parent, /** @deprecated */ element_id) {
409 this._super((parent || {}).session);
410 // if given an element_id, try to get the associated DOM element and save
411 // a reference in this.$element. Else just generate a unique identifier.
412 this.element_id = element_id;
413 this.element_id = this.element_id || _.uniqueId(this.identifier_prefix);
414 var tmp = document.getElementById(this.element_id);
415 this.$element = tmp ? $(tmp) : undefined;
417 this.widget_parent = parent;
418 this.widget_children = [];
419 if(parent && parent.widget_children) {
420 parent.widget_children.push(this);
422 // useful to know if the widget was destroyed and should not be used anymore
423 this.widget_is_stopped = false;
426 * Render the current widget and appends it to the given jQuery object or Widget.
428 * @param target A jQuery object or a Widget instance.
430 appendTo: function(target) {
432 return this._render_and_insert(function(t) {
433 self.$element.appendTo(t);
437 * Render the current widget and prepends it to the given jQuery object or Widget.
439 * @param target A jQuery object or a Widget instance.
441 prependTo: function(target) {
443 return this._render_and_insert(function(t) {
444 self.$element.prependTo(t);
448 * Render the current widget and inserts it after to the given jQuery object or Widget.
450 * @param target A jQuery object or a Widget instance.
452 insertAfter: function(target) {
454 return this._render_and_insert(function(t) {
455 self.$element.insertAfter(t);
459 * Render the current widget and inserts it before to the given jQuery object or Widget.
461 * @param target A jQuery object or a Widget instance.
463 insertBefore: function(target) {
465 return this._render_and_insert(function(t) {
466 self.$element.insertBefore(t);
469 _render_and_insert: function(insertion, target) {
470 var rendered = this.render();
471 this.$element = $(rendered);
472 if (target instanceof openerp.base.Widget)
473 target = target.$element;
478 * Renders the widget using QWeb, `this.template` must be defined.
479 * The context given to QWeb contains the "widget" key that references `this`.
481 * @param {Object} additional Additional context arguments to pass to the template.
483 render: function (additional) {
484 return QWeb.render(this.template, _.extend({widget: this}, additional || {}));
487 * Method called after rendering. Mostly used to bind actions, perform asynchronous
490 * By convention, the method should return a promise to inform the caller when
491 * this widget has been initialized.
493 * @returns {jQuery.Deferred}
496 if (!this.$element) {
497 var tmp = document.getElementById(this.element_id);
498 this.$element = tmp ? $(tmp) : undefined;
500 return $.Deferred().done().promise();
503 * Destroys the current widget, also destory all its children before destroying itself.
506 _.each(_.clone(this.widget_children), function(el) {
509 if(this.$element != null) {
510 this.$element.remove();
512 if (this.widget_parent && this.widget_parent.widget_children) {
513 this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
515 this.widget_parent = null;
516 this.widget_is_stopped = true;
519 * Inform the action manager to do an action. Of course, this suppose that
520 * the action manager can be found amongst the ancestors of the current widget.
521 * If that's not the case this method will simply return `false`.
523 do_action: function(action, on_finished) {
524 if (this.widget_parent) {
525 return this.widget_parent.do_action(action, on_finished);
529 do_notify: function() {
530 if (this.widget_parent) {
531 return this.widget_parent.do_notify.apply(this,arguments);
535 do_warn: function() {
536 if (this.widget_parent) {
537 return this.widget_parent.do_warn.apply(this,arguments);
541 rpc: function(url, data, success, error) {
542 var def = $.Deferred().then(success, error);
544 this._super(url, data). then(function() {
545 if (!self.widget_is_stopped)
546 def.resolve.apply(def, arguments);
548 if (!self.widget_is_stopped)
549 def.reject.apply(def, arguments);
551 return def.promise();
557 * For retro compatibility only, the only difference with is that render() uses
558 * directly `this` instead of context with a "widget" key.
560 openerp.base.OldWidget = openerp.base.Widget.extend({
561 render: function (additional) {
562 return QWeb.render(this.template, _.extend(_.extend({}, this), additional || {}));
566 openerp.base.TranslationDataBase = openerp.base.Class.extend({
570 set_bundle: function(translation_bundle) {
573 var modules = _.keys(translation_bundle.modules);
574 if (_.include(modules, "base")) {
575 modules = _.without(modules, "base").concat(["base"]);
577 _.each(modules, function(name) {
578 var mod = translation_bundle.modules[name];
579 _.each(mod.messages, function(message) {
580 self.db[message.id] = message.string;
584 build_translation_function: function() {
586 var fcnt = function(str) {
587 var tmp = self.get(str);
588 return tmp === undefined ? str : tmp;
590 fcnt.database = this;
600 openerp.base._t = new openerp.base.TranslationDataBase().build_translation_function();
602 openerp.base.Session = openerp.base.CallbackEnabled.extend( /** @lends openerp.base.Session# */{
605 * @param element_id to use for exception reporting
609 init: function(server, port) {
611 this.server = (server == undefined) ? location.hostname : server;
612 this.port = (port == undefined) ? location.port : port;
613 this.rpc_mode = (server == location.hostname) ? "ajax" : "jsonp";
618 this.user_context= {};
620 this.session_id = false;
621 this.module_list = [];
622 this.module_loaded = {"base": true};
626 this.session_restore();
629 * Executes an RPC call, registering the provided callbacks.
631 * Registers a default error callback if none is provided, and handles
632 * setting the correct session id and session context in the parameter
635 * @param {String} url RPC endpoint
636 * @param {Object} params call parameters
637 * @param {Function} success_callback function to execute on RPC call success
638 * @param {Function} error_callback function to execute on RPC call failure
639 * @returns {jQuery.Deferred} jquery-provided ajax deferred
641 rpc: function(url, params, success_callback, error_callback) {
643 // Construct a JSON-RPC2 request, method is currently unused
644 params.session_id = this.session_id;
646 // Call using the rpc_mode
647 var deferred = $.Deferred();
653 }).then(function () {deferred.resolve.apply(deferred, arguments);},
654 function(error) {deferred.reject(error, $.Event());});
655 return deferred.fail(function() {
656 deferred.fail(function(error, event) {
657 if (!event.isDefaultPrevented()) {
658 self.on_rpc_error(error, event);
661 }).then(success_callback, error_callback).promise();
666 * @returns {jQuery.Deferred} ajax-based deferred object
668 rpc_ajax: function(url, payload) {
670 this.on_rpc_request();
671 // url can be an $.ajax option object
672 if (_.isString(url)) {
677 var ajax = _.extend({
681 contentType: 'application/json',
682 data: JSON.stringify(payload),
685 var deferred = $.Deferred();
686 $.ajax(ajax).done(function(response, textStatus, jqXHR) {
687 self.on_rpc_response();
688 if (!response.error) {
689 deferred.resolve(response["result"], textStatus, jqXHR);
692 if (response.error.data.type !== "session_invalid") {
693 deferred.reject(response.error);
697 self.on_session_invalid(function() {
698 self.rpc(url, payload.params,
700 deferred.resolve.apply(deferred, arguments);
702 function(error, event) {
703 event.preventDefault();
704 deferred.reject.apply(deferred, arguments);
707 }).fail(function(jqXHR, textStatus, errorThrown) {
708 self.on_rpc_response();
711 message: "XmlHttpRequestError " + errorThrown,
712 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
714 deferred.reject(error);
716 return deferred.promise();
718 on_rpc_request: function() {
720 on_rpc_response: function() {
722 on_rpc_error: function(error) {
725 * The session is validated either by login or by restoration of a previous session
727 on_session_valid: function() {
728 if(!openerp._modules_loaded)
731 on_session_invalid: function(contination) {
733 session_is_valid: function() {
736 session_login: function(db, login, password, success_callback) {
740 this.password = password;
741 var params = { db: this.db, login: this.login, password: this.password };
742 this.rpc("/base/session/login", params, function(result) {
743 self.session_id = result.session_id;
744 self.uid = result.uid;
745 self.user_context = result.context;
747 self.on_session_valid();
748 if (success_callback)
752 session_logout: function() {
756 * Reloads uid and session_id from local storage, if they exist
758 session_restore: function () {
759 this.uid = this.get_cookie('uid');
760 this.session_id = this.get_cookie('session_id');
761 this.db = this.get_cookie('db');
762 this.login = this.get_cookie('login');
763 this.user_context = this.get_cookie("user_context");
764 // we should do an rpc to confirm that this session_id is valid and if it is retrieve the information about db and login
765 // then call on_session_valid
766 this.on_session_valid();
769 * Saves the session id and uid locally
771 session_save: function () {
772 this.set_cookie('uid', this.uid);
773 this.set_cookie('session_id', this.session_id);
774 this.set_cookie('db', this.db);
775 this.set_cookie('login', this.login);
776 this.set_cookie('user_context', this.user_context);
780 delete this.session_id;
783 this.set_cookie('uid', '');
784 this.set_cookie('session_id', '');
785 this.set_cookie('db', '');
786 this.set_cookie('login', '');
787 this.on_session_invalid(function() {});
790 * Fetches a cookie stored by an openerp session
793 * @param name the cookie's name
795 get_cookie: function (name) {
796 var nameEQ = this.element_id + '|' + name + '=';
797 var cookies = document.cookie.split(';');
798 for(var i=0; i<cookies.length; ++i) {
799 var cookie = cookies[i].replace(/^\s*/, '');
800 if(cookie.indexOf(nameEQ) === 0) {
801 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
807 * Create a new cookie with the provided name and value
810 * @param name the cookie's name
811 * @param value the cookie's value
812 * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
814 set_cookie: function (name, value, ttl) {
815 ttl = ttl || 24*60*60*365;
817 this.element_id + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
819 'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
823 * Load additional web addons of that instance and init them
825 load_modules: function() {
827 this.rpc('/base/session/modules', {}, function(result) {
828 self.module_list = result;
829 self.rpc('/base/webclient/translations',{
830 mods: ["base"].concat(result),
831 lang: self.user_context.lang})
832 .then(function(transs) {
833 openerp.base._t.database.set_bundle(transs);
834 var modules = self.module_list.join(',');
835 if(self.debug || true) {
836 self.rpc('/base/webclient/csslist', {"mods": modules}, self.do_load_css);
837 self.rpc('/base/webclient/jslist', {"mods": modules}, self.do_load_js);
839 self.do_load_css(["/base/webclient/css?mods="+modules]);
840 self.do_load_js(["/base/webclient/js?mods="+modules]);
842 openerp._modules_loaded = true;
846 do_load_css: function (files) {
847 _.each(files, function (file) {
848 $('head').append($('<link>', {
855 do_load_js: function(files) {
857 if(files.length != 0) {
858 var file = files.shift();
859 var tag = document.createElement('script');
860 tag.type = 'text/javascript';
862 tag.onload = tag.onreadystatechange = function() {
863 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
865 tag.onload_done = true;
866 self.do_load_js(files);
868 document.head.appendChild(tag);
870 this.on_modules_loaded();
873 on_modules_loaded: function() {
874 for(var j=0; j<this.module_list.length; j++) {
875 var mod = this.module_list[j];
876 if(this.module_loaded[mod])
880 if(openerp._openerp[mod] != undefined) {
881 openerp._openerp[mod]._T = openerp.base._t.database.build_translation_function();
882 openerp._openerp[mod](openerp);
883 this.module_loaded[mod] = true;
891 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: