1 /*---------------------------------------------------------
3 *--------------------------------------------------------*/
6 console = {log: function () {}};
9 console.debug = console.log;
12 openerp.web.core = function(openerp) {
14 openerp.web.Class = nova.Class;
16 openerp.web.callback = function(obj, method) {
17 var callback = function() {
18 var args = Array.prototype.slice.call(arguments);
20 for(var i = 0; i < callback.callback_chain.length; i++) {
21 var c = callback.callback_chain[i];
23 callback.callback_chain.splice(i, 1);
26 var result = c.callback.apply(c.self, c.args.concat(args));
27 if (c.callback === method) {
28 // return the result of the original method
31 // TODO special value to stop the chain
32 // openerp.web.callback_stop
36 callback.callback_chain = [];
37 callback.add = function(f) {
38 if(typeof(f) == 'function') {
39 f = { callback: f, args: Array.prototype.slice.call(arguments, 1) };
41 f.self = f.self || null;
42 f.args = f.args || [];
43 f.unique = !!f.unique;
44 if(f.position == 'last') {
45 callback.callback_chain.push(f);
47 callback.callback_chain.unshift(f);
51 callback.add_first = function(f) {
52 return callback.add.apply(null,arguments);
54 callback.add_last = function(f) {
57 args: Array.prototype.slice.call(arguments, 1),
61 callback.remove = function(f) {
62 callback.callback_chain = _.difference(callback.callback_chain, _.filter(callback.callback_chain, function(el) {
63 return el.callback === f;
71 args:Array.prototype.slice.call(arguments, 2)
76 * web error for lookup failure
80 openerp.web.NotFound = openerp.web.Class.extend( /** @lends openerp.web.NotFound# */ {
82 openerp.web.KeyNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.KeyNotFound# */ {
84 * Thrown when a key could not be found in a mapping
86 * @constructs openerp.web.KeyNotFound
87 * @extends openerp.web.NotFound
88 * @param {String} key the key which could not be found
90 init: function (key) {
93 toString: function () {
94 return "The key " + this.key + " was not found";
97 openerp.web.ObjectNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.ObjectNotFound# */ {
99 * Thrown when an object path does not designate a valid class or object
100 * in the openerp hierarchy.
102 * @constructs openerp.web.ObjectNotFound
103 * @extends openerp.web.NotFound
104 * @param {String} path the invalid object path
106 init: function (path) {
109 toString: function () {
110 return "Could not find any object of path " + this.path;
113 openerp.web.Registry = openerp.web.Class.extend( /** @lends openerp.web.Registry# */ {
115 * Stores a mapping of arbitrary key (strings) to object paths (as strings
118 * Resolves those paths at query time in order to always fetch the correct
119 * object, even if those objects have been overloaded/replaced after the
120 * registry was created.
122 * An object path is simply a dotted name from the openerp root to the
123 * object pointed to (e.g. ``"openerp.web.Connection"`` for an OpenERP
124 * connection object).
126 * @constructs openerp.web.Registry
127 * @param {Object} mapping a mapping of keys to object-paths
129 init: function (mapping) {
131 this.map = mapping || {};
134 * Retrieves the object matching the provided key string.
136 * @param {String} key the key to fetch the object for
137 * @param {Boolean} [silent_error=false] returns undefined if the key or object is not found, rather than throwing an exception
138 * @returns {Class} the stored class, to initialize
140 * @throws {openerp.web.KeyNotFound} if the object was not in the mapping
141 * @throws {openerp.web.ObjectNotFound} if the object path was invalid
143 get_object: function (key, silent_error) {
144 var path_string = this.map[key];
145 if (path_string === undefined) {
147 return this.parent.get_object(key, silent_error);
149 if (silent_error) { return void 'nooo'; }
150 throw new openerp.web.KeyNotFound(key);
153 var object_match = openerp;
154 var path = path_string.split('.');
155 // ignore first section
156 for(var i=1; i<path.length; ++i) {
157 object_match = object_match[path[i]];
159 if (object_match === undefined) {
160 if (silent_error) { return void 'noooooo'; }
161 throw new openerp.web.ObjectNotFound(path_string);
167 * Checks if the registry contains an object mapping for this key.
169 * @param {String} key key to look for
171 contains: function (key) {
172 if (key === undefined) { return false; }
173 if (key in this.map) {
177 return this.parent.contains(key);
182 * Tries a number of keys, and returns the first object matching one of
185 * @param {Array} keys a sequence of keys to fetch the object for
186 * @returns {Class} the first class found matching an object
188 * @throws {openerp.web.KeyNotFound} if none of the keys was in the mapping
189 * @trows {openerp.web.ObjectNotFound} if a found object path was invalid
191 get_any: function (keys) {
192 for (var i=0; i<keys.length; ++i) {
194 if (!this.contains(key)) {
198 return this.get_object(key);
200 throw new openerp.web.KeyNotFound(keys.join(','));
203 * Adds a new key and value to the registry.
205 * This method can be chained.
207 * @param {String} key
208 * @param {String} object_path fully qualified dotted object path
209 * @returns {openerp.web.Registry} itself
211 add: function (key, object_path) {
212 this.map[key] = object_path;
216 * Creates and returns a copy of the current mapping, with the provided
217 * mapping argument added in (replacing existing keys if needed)
219 * Parent and child remain linked, a new key in the parent (which is not
220 * overwritten by the child) will appear in the child.
222 * @param {Object} [mapping={}] a mapping of keys to object-paths
224 extend: function (mapping) {
225 var child = new openerp.web.Registry(mapping);
230 * @deprecated use Registry#extend
232 clone: function (mapping) {
233 console.warn('Registry#clone is deprecated, use Registry#extend');
234 return this.extend(mapping);
238 openerp.web.CallbackEnabledMixin = {
240 // Transform on_* method into openerp.web.callbacks
241 for (var name in this) {
242 if(typeof(this[name]) == "function") {
243 this[name].debug_name = name;
244 // bind ALL function to this not only on_and _do ?
245 if((/^on_|^do_/).test(name)) {
246 this[name] = openerp.web.callback(this, this[name]);
252 * Proxies a method of the object, in order to keep the right ``this`` on
253 * method invocations.
255 * This method is similar to ``Function.prototype.bind`` or ``_.bind``, and
256 * even more so to ``jQuery.proxy`` with a fundamental difference: its
257 * resolution of the method being called is lazy, meaning it will use the
258 * method as it is when the proxy is called, not when the proxy is created.
260 * Other methods will fix the bound method to what it is when creating the
261 * binding/proxy, which is fine in most javascript code but problematic in
262 * OpenERP Web where developers may want to replace existing callbacks with
265 * The semantics of this precisely replace closing over the method call.
267 * @param {String} method_name name of the method to invoke
268 * @returns {Function} proxied method
270 proxy: function (method_name) {
273 return self[method_name].apply(self, arguments);
278 openerp.web.CallbackEnabled = openerp.web.Class.extend(_.extend({}, nova.GetterSetterMixin, openerp.web.CallbackEnabledMixin, {
280 nova.GetterSetterMixin.init.call(this);
281 openerp.web.CallbackEnabledMixin.init.call(this);
285 openerp.web.Connection = openerp.web.CallbackEnabled.extend( /** @lends openerp.web.Connection# */{
287 * @constructs openerp.web.Connection
288 * @extends openerp.web.CallbackEnabled
290 * @param {String} [server] JSON-RPC endpoint hostname
291 * @param {String} [port] JSON-RPC endpoint port
296 this.debug = ($.deparam($.param.querystring()).debug != undefined);
297 // TODO: session store in cookie should be optional
298 this.name = openerp._session_id;
299 this.qweb_mutex = new $.Mutex();
301 bind_session: function(origin) {
302 var window_origin = location.protocol+"//"+location.host, self=this;
303 this.origin = origin ? _.str.rtrim(origin,'/') : window_origin;
304 this.prefix = this.origin;
305 this.server = this.origin; // keep chs happy
306 openerp.web.qweb.default_dict['_s'] = this.origin;
307 this.rpc_function = (this.origin == window_origin) ? this.rpc_json : this.rpc_jsonp;
308 this.session_id = false;
310 this.username = false;
311 this.user_context= {};
313 this.openerp_entreprise = false;
314 this.module_list = openerp._modules.slice();
315 this.module_loaded = {};
316 _(this.module_list).each(function (mod) {
317 self.module_loaded[mod] = true;
321 this.active_id = null;
322 return this.session_init();
324 test_eval_get_context: function () {
325 var asJS = function (arg) {
326 if (arg instanceof py.object) {
332 var datetime = new py.object();
333 datetime.datetime = new py.type(function datetime() {
334 throw new Error('datetime.datetime not implemented');
336 var date = datetime.date = new py.type(function date(y, m, d) {
337 if (y instanceof Array) {
343 this.month = asJS(m);
346 strftime: function (args) {
347 var f = asJS(args[0]), self = this;
348 return new py.str(f.replace(/%([A-Za-z])/g, function (m, c) {
350 case 'Y': return self.year;
351 case 'm': return _.str.sprintf('%02d', self.month);
352 case 'd': return _.str.sprintf('%02d', self.day);
354 throw new Error('ValueError: No known conversion for ' + m);
358 date.__getattribute__ = function (name) {
359 if (name === 'today') {
362 throw new Error("AttributeError: object 'date' has no attribute '" + name +"'");
364 date.today = new py.def(function () {
366 return new date(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate());
368 datetime.time = new py.type(function time() {
369 throw new Error('datetime.time not implemented');
372 var time = new py.object();
373 time.strftime = new py.def(function (args) {
374 return date.today.__call__().strftime(args);
377 var relativedelta = new py.type(function relativedelta(args, kwargs) {
378 if (!_.isEmpty(args)) {
379 throw new Error('Extraction of relative deltas from existing datetimes not supported');
383 __add__: function (other) {
384 if (!(other instanceof datetime.date)) {
385 return py.NotImplemented;
387 // TODO: test this whole mess
388 var year = asJS(this.ops.year) || asJS(other.year);
389 if (asJS(this.ops.years)) {
390 year += asJS(this.ops.years);
393 var month = asJS(this.ops.month) || asJS(other.month);
394 if (asJS(this.ops.months)) {
395 month += asJS(this.ops.months);
396 // FIXME: no divmod in JS?
407 var lastMonthDay = new Date(year, month, 0).getDate();
408 var day = asJS(this.ops.day) || asJS(other.day);
409 if (day > lastMonthDay) { day = lastMonthDay; }
410 var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
412 day = new Date(year, month-1, day + days_offset).getDate();
415 // TODO: hours, minutes, seconds? Not used in XML domains
417 return new datetime.date(year, month, day);
419 __radd__: function (other) {
420 return this.__add__(other);
423 __sub__: function (other) {
424 if (!(other instanceof datetime.date)) {
425 return py.NotImplemented;
427 // TODO: test this whole mess
428 var year = asJS(this.ops.year) || asJS(other.year);
429 if (asJS(this.ops.years)) {
430 year -= asJS(this.ops.years);
433 var month = asJS(this.ops.month) || asJS(other.month);
434 if (asJS(this.ops.months)) {
435 month -= asJS(this.ops.months);
436 // FIXME: no divmod in JS?
447 var lastMonthDay = new Date(year, month, 0).getDate();
448 var day = asJS(this.ops.day) || asJS(other.day);
449 if (day > lastMonthDay) { day = lastMonthDay; }
450 var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);
452 day = new Date(year, month-1, day - days_offset).getDate();
455 // TODO: hours, minutes, seconds? Not used in XML domains
457 return new datetime.date(year, month, day);
459 __rsub__: function (other) {
460 return this.__sub__(other);
465 uid: new py.float(this.uid),
468 relativedelta: relativedelta
472 * FIXME: Huge testing hack, especially the evaluation context, rewrite + test for real before switching
474 test_eval: function (source, expected) {
476 var ctx = this.test_eval_contexts(source.contexts);
477 if (!_.isEqual(ctx, expected.context)) {
478 console.group('Local context does not match remote, nothing is broken but please report to R&D (xmo)');
479 console.warn('source', source.contexts);
480 console.warn('local', ctx);
481 console.warn('remote', expected.context);
485 console.group('Failed to evaluate contexts, nothing is broken but please report to R&D (xmo)');
487 console.log('source', source.contexts);
492 var dom = this.test_eval_domains(source.domains, this.test_eval_get_context());
493 if (!_.isEqual(dom, expected.domain)) {
494 console.group('Local domain does not match remote, nothing is broken but please report to R&D (xmo)');
495 console.warn('source', source.domains);
496 console.warn('local', dom);
497 console.warn('remote', expected.domain);
501 console.group('Failed to evaluate domains, nothing is broken but please report to R&D (xmo)');
503 console.log('source', source.domains);
508 var groups = this.test_eval_groupby(source.group_by_seq);
509 if (!_.isEqual(groups, expected.group_by)) {
510 console.group('Local groupby does not match remote, nothing is broken but please report to R&D (xmo)');
511 console.warn('source', source.group_by_seq);
512 console.warn('local', groups);
513 console.warn('remote', expected.group_by);
517 console.group('Failed to evaluate groupby, nothing is broken but please report to R&D (xmo)');
519 console.log('source', source.group_by_seq);
523 test_eval_contexts: function (contexts) {
524 var result_context = _.extend({}, this.user_context),
526 _(contexts).each(function (ctx) {
529 _.extend(result_context, py.eval(ctx.__debug));
531 case 'compound_context':
533 result_context, self.test_eval_contexts(ctx.__contexts));
536 _.extend(result_context, ctx);
539 return result_context;
541 test_eval_domains: function (domains, eval_context) {
542 var result_domain = [], self = this;
543 _(domains).each(function (dom) {
546 result_domain.push.apply(
547 result_domain, py.eval(dom.__debug, eval_context));
549 case 'compound_domain':
550 result_domain.push.apply(
551 result_domain, self.test_eval_domains(
552 dom.__domains, eval_context));
555 result_domain.push.apply(
559 return result_domain;
561 test_eval_groupby: function (contexts) {
562 var result_group = [], self = this;
563 _(contexts).each(function (ctx) {
567 group = py.eval(ctx.__debug).group_by;
569 case 'compound_context':
570 group = self.test_eval_contexts(ctx.__contexts).group_by;
575 if (!group) { return; }
576 if (typeof group === 'string') {
577 result_group.push(group);
578 } else if (group instanceof Array) {
579 result_group.push.apply(result_group, group);
581 throw new Error('Got invalid groupby {{'
582 + JSON.stringify(group) + '}}');
588 * Executes an RPC call, registering the provided callbacks.
590 * Registers a default error callback if none is provided, and handles
591 * setting the correct session id and session context in the parameter
594 * @param {String} url RPC endpoint
595 * @param {Object} params call parameters
596 * @param {Function} success_callback function to execute on RPC call success
597 * @param {Function} error_callback function to execute on RPC call failure
598 * @returns {jQuery.Deferred} jquery-provided ajax deferred
600 rpc: function(url, params, success_callback, error_callback) {
602 // url can be an $.ajax option object
603 if (_.isString(url)) {
606 // Construct a JSON-RPC2 request, method is currently unused
607 params.session_id = this.session_id;
616 var deferred = $.Deferred();
617 this.on_rpc_request();
618 var aborter = params.aborter;
619 delete params.aborter;
620 var request = this.rpc_function(url, payload).then(
621 function (response, textStatus, jqXHR) {
622 self.on_rpc_response();
623 if (!response.error) {
624 if (url.url === '/web/session/eval_domain_and_context') {
625 self.test_eval(params, response.result);
627 deferred.resolve(response["result"], textStatus, jqXHR);
628 } else if (response.error.data.type === "session_invalid") {
630 // TODO deprecate or use a deferred on login.do_ask_login()
631 self.on_session_invalid(function() {
632 self.rpc(url, payload.params,
633 function() { deferred.resolve.apply(deferred, arguments); },
634 function() { deferred.reject.apply(deferred, arguments); });
637 deferred.reject(response.error, $.Event());
640 function(jqXHR, textStatus, errorThrown) {
641 self.on_rpc_response();
644 message: "XmlHttpRequestError " + errorThrown,
645 data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
647 deferred.reject(error, $.Event());
650 aborter.abort_last = function () {
651 if (!(request.isResolved() || request.isRejected())) {
652 deferred.fail(function (error, event) {
653 event.preventDefault();
659 // Allow deferred user to disable on_rpc_error in fail
660 deferred.fail(function() {
661 deferred.fail(function(error, event) {
662 if (!event.isDefaultPrevented()) {
663 self.on_rpc_error(error, event);
666 }).then(success_callback, error_callback).promise();
672 * @returns {jQuery.Deferred} ajax-webd deferred object
674 rpc_json: function(url, payload) {
676 var ajax = _.extend({
679 contentType: 'application/json',
680 data: JSON.stringify(payload),
687 rpc_jsonp: function(url, payload) {
689 // extracted from payload to set on the url
691 session_id: this.session_id,
694 url.url = this.get_url(url.url);
695 var ajax = _.extend({
704 var payload_str = JSON.stringify(payload);
705 var payload_url = $.param({r:payload_str});
706 if(payload_url.length < 2000) {
707 // Direct jsonp request
708 ajax.data.r = payload_str;
711 // Indirect jsonp request
712 var ifid = _.uniqueId('oe_rpc_iframe');
713 var display = options.openerp.debug ? 'block' : 'none';
714 var $iframe = $(_.str.sprintf("<iframe src='javascript:false;' name='%s' id='%s' style='display:%s'></iframe>", ifid, ifid, display));
715 var $form = $('<form>')
716 .attr('method', 'POST')
717 .attr('target', ifid)
718 .attr('enctype', "multipart/form-data")
719 .attr('action', ajax.url + '?' + $.param(data))
720 .append($('<input type="hidden" name="r" />').attr('value', payload_str))
722 .appendTo($('body'));
723 var cleanUp = function() {
725 $iframe.unbind("load").attr("src", "javascript:false;").remove();
729 var deferred = $.Deferred();
730 // the first bind is fired up when the iframe is added to the DOM
731 $iframe.bind('load', function() {
732 // the second bind is fired up when the result of the form submission is received
733 $iframe.unbind('load').bind('load', function() {
734 $.ajax(ajax).always(function() {
737 function() { deferred.resolve.apply(deferred, arguments); },
738 function() { deferred.reject.apply(deferred, arguments); }
741 // now that the iframe can receive data, we fill and submit the form
744 // append the iframe to the DOM (will trigger the first load)
745 $form.after($iframe);
749 on_rpc_request: function() {
751 on_rpc_response: function() {
753 on_rpc_error: function(error) {
756 * Init a session, reloads from cookie, if it exists
758 session_init: function () {
760 // TODO: session store in cookie should be optional
761 this.session_id = this.get_cookie('session_id');
762 return this.session_reload().pipe(function(result) {
763 var modules = openerp._modules.join(',');
764 var deferred = self.rpc('/web/webclient/qweblist', {mods: modules}).pipe(self.do_load_qweb);
765 if(self.session_is_valid()) {
766 return deferred.pipe(function() { return self.load_modules(); });
772 * (re)loads the content of a session: db name, username, user id, session
773 * context and status of the support contract
775 * @returns {$.Deferred} deferred indicating the session is done reloading
777 session_reload: function () {
779 return this.rpc("/web/session/get_session_info", {}).then(function(result) {
780 // If immediately follows a login (triggered by trying to restore
781 // an invalid session or no session at all), refresh session data
782 // (should not change, but just in case...)
785 username: result.login,
787 user_context: result.context,
788 openerp_entreprise: result.openerp_entreprise
792 session_is_valid: function() {
796 * The session is validated either by login or by restoration of a previous session
798 session_authenticate: function(db, login, password, _volatile) {
800 var base_location = document.location.protocol + '//' + document.location.host;
801 var params = { db: db, login: login, password: password, base_location: base_location };
802 return this.rpc("/web/session/authenticate", params).pipe(function(result) {
804 session_id: result.session_id,
806 username: result.login,
808 user_context: result.context,
809 openerp_entreprise: result.openerp_entreprise
812 self.set_cookie('session_id', self.session_id);
814 return self.load_modules();
817 session_logout: function() {
818 this.set_cookie('session_id', '');
819 return this.rpc("/web/session/destroy", {});
821 on_session_valid: function() {
824 * Called when a rpc call fail due to an invalid session.
825 * By default, it's a noop
827 on_session_invalid: function(retry_callback) {
830 * Fetches a cookie stored by an openerp session
833 * @param name the cookie's name
835 get_cookie: function (name) {
836 if (!this.name) { return null; }
837 var nameEQ = this.name + '|' + name + '=';
838 var cookies = document.cookie.split(';');
839 for(var i=0; i<cookies.length; ++i) {
840 var cookie = cookies[i].replace(/^\s*/, '');
841 if(cookie.indexOf(nameEQ) === 0) {
842 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
848 * Create a new cookie with the provided name and value
851 * @param name the cookie's name
852 * @param value the cookie's value
853 * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
855 set_cookie: function (name, value, ttl) {
856 if (!this.name) { return; }
857 ttl = ttl || 24*60*60*365;
859 this.name + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
862 'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
866 * Load additional web addons of that instance and init them
868 * @param {Boolean} [no_session_valid_signal=false] prevents load_module from triggering ``on_session_valid``.
870 load_modules: function(no_session_valid_signal) {
872 return this.rpc('/web/session/modules', {}).pipe(function(result) {
873 var lang = self.user_context.lang,
874 all_modules = _.uniq(self.module_list.concat(result));
875 var params = { mods: all_modules, lang: lang};
876 var to_load = _.difference(result, self.module_list).join(',');
877 self.module_list = all_modules;
879 var loaded = $.Deferred().resolve().promise();
880 if (to_load.length) {
882 self.rpc('/web/webclient/csslist', {mods: to_load}, self.do_load_css),
883 self.rpc('/web/webclient/qweblist', {mods: to_load}).pipe(self.do_load_qweb),
884 self.rpc('/web/webclient/translations', params).pipe(function(trans) {
885 openerp.web._t.database.set_bundle(trans);
886 var file_list = ["/web/static/lib/datejs/globalization/" + lang.replace("_", "-") + ".js"];
887 return self.rpc('/web/webclient/jslist', {mods: to_load}).pipe(function(files) {
888 return self.do_load_js(file_list.concat(files));
889 }).then(function () {
890 if (!Date.CultureInfo.pmDesignator) {
891 // If no am/pm designator is specified but the openerp
892 // datetime format uses %i, date.js won't be able to
893 // correctly format a date. See bug#938497.
894 Date.CultureInfo.amDesignator = 'AM';
895 Date.CultureInfo.pmDesignator = 'PM';
900 return loaded.then(function() {
901 self.on_modules_loaded();
902 if (!no_session_valid_signal) {
903 self.on_session_valid();
908 do_load_css: function (files) {
910 _.each(files, function (file) {
911 $('head').append($('<link>', {
912 'href': self.get_url(file),
918 do_load_js: function(files) {
920 var d = $.Deferred();
921 if(files.length != 0) {
922 var file = files.shift();
923 var tag = document.createElement('script');
924 tag.type = 'text/javascript';
925 tag.src = self.get_url(file);
926 tag.onload = tag.onreadystatechange = function() {
927 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
929 tag.onload_done = true;
930 self.do_load_js(files).then(function () {
934 var head = document.head || document.getElementsByTagName('head')[0];
935 head.appendChild(tag);
941 do_load_qweb: function(files) {
943 _.each(files, function(file) {
944 self.qweb_mutex.exec(function() {
945 return self.rpc('/web/proxy/load', {path: file}).pipe(function(xml) {
946 if (!xml) { return; }
947 openerp.web.qweb.add_template(_.str.trim(xml));
951 return self.qweb_mutex.def;
953 on_modules_loaded: function() {
954 for(var j=0; j<this.module_list.length; j++) {
955 var mod = this.module_list[j];
956 if(this.module_loaded[mod])
960 if(openerp._openerp[mod] != undefined) {
961 openerp._openerp[mod](openerp);
962 this.module_loaded[mod] = true;
966 get_url: function (file) {
967 return this.prefix + file;
970 * Cooperative file download implementation, for ajaxy APIs.
972 * Requires that the server side implements an httprequest correctly
973 * setting the `fileToken` cookie to the value provided as the `token`
974 * parameter. The cookie *must* be set on the `/` path and *must not* be
977 * It would probably also be a good idea for the response to use a
978 * `Content-Disposition: attachment` header, especially if the MIME is a
979 * "known" type (e.g. text/plain, or for some browsers application/json
981 * @param {Object} options
982 * @param {String} [options.url] used to dynamically create a form
983 * @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
984 * @param {HTMLFormElement} [options.form] the form to submit in order to fetch the file
985 * @param {Function} [options.success] callback in case of download success
986 * @param {Function} [options.error] callback in case of request error, provided with the error body
987 * @param {Function} [options.complete] called after both ``success`` and ``error` callbacks have executed
989 get_file: function (options) {
990 // need to detect when the file is done downloading (not used
991 // yet, but we'll need it to fix the UI e.g. with a throbber
992 // while dump is being generated), iframe load event only fires
993 // when the iframe content loads, so we need to go smarter:
994 // http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
995 var timer, token = new Date().getTime(),
996 cookie_name = 'fileToken', cookie_length = cookie_name.length,
997 CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
1000 var $form, $form_data = $('<div>');
1002 var complete = function () {
1003 if (options.complete) { options.complete(); }
1004 clearTimeout(timer);
1005 $form_data.remove();
1007 if (remove_form && $form) { $form.remove(); }
1009 var $target = $('<iframe style="display: none;">')
1010 .attr({id: id, name: id})
1011 .appendTo(document.body)
1014 if (options.error) {
1015 options.error(JSON.parse(
1016 this.contentDocument.body.childNodes[1].textContent
1025 $form = $(options.form);
1028 $form = $('<form>', {
1029 action: options.url,
1031 }).appendTo(document.body);
1034 _(_.extend({}, options.data || {},
1035 {session_id: this.session_id, token: token}))
1036 .each(function (value, key) {
1037 var $input = $form.find('[name=' + key +']');
1038 if (!$input.length) {
1039 $input = $('<input type="hidden" name="' + key + '">')
1040 .appendTo($form_data);
1050 var waitLoop = function () {
1051 var cookies = document.cookie.split(';');
1053 timer = setTimeout(waitLoop, CHECK_INTERVAL);
1054 for (var i=0; i<cookies.length; ++i) {
1055 var cookie = cookies[i].replace(/^\s*/, '');
1056 if (!cookie.indexOf(cookie_name === 0)) { continue; }
1057 var cookie_val = cookie.substring(cookie_length + 1);
1058 if (parseInt(cookie_val, 10) !== token) { continue; }
1061 document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
1062 cookie_name, new Date().toGMTString());
1063 if (options.success) { options.success(); }
1068 timer = setTimeout(waitLoop, CHECK_INTERVAL);
1070 synchronized_mode: function(to_execute) {
1071 var synch = this.synch;
1074 return to_execute();
1082 * Base class for all visual components. Provides a lot of functionalities helpful
1083 * for the management of a part of the DOM.
1086 * - Rendering with QWeb.
1087 * - Life-cycle management and parenting (when a parent is destroyed, all its children are
1089 * - Insertion in DOM.
1091 * Guide to create implementations of the Widget class:
1092 * ==============================================
1094 * Here is a sample child class:
1096 * MyWidget = openerp.base.Widget.extend({
1097 * // the name of the QWeb template to use for rendering
1098 * template: "MyQWebTemplate",
1100 * init: function(parent) {
1101 * this._super(parent);
1102 * // stuff that you want to init before the rendering
1104 * start: function() {
1105 * // stuff you want to make after the rendering, `this.$element` holds a correct value
1106 * this.$element.find(".my_button").click(/* an example of event binding * /);
1108 * // if you have some asynchronous operations, it's a good idea to return
1109 * // a promise in start()
1110 * var promise = this.rpc(...);
1115 * Now this class can simply be used with the following syntax:
1117 * var my_widget = new MyWidget(this);
1118 * my_widget.appendTo($(".some-div"));
1120 * With these two lines, the MyWidget instance was inited, rendered, it was inserted into the
1121 * DOM inside the ".some-div" div and its events were binded.
1123 * And of course, when you don't need that widget anymore, just do:
1125 * my_widget.destroy();
1127 * That will kill the widget in a clean way and erase its content from the dom.
1129 openerp.web.Widget = nova.Widget.extend(_.extend({}, openerp.web.CallbackEnabledMixin, {
1131 * The name of the QWeb template that will be used for rendering. Must be
1132 * redefined in subclasses or the default render() method can not be used.
1138 * Constructs the widget and sets its parent if a parent is given.
1140 * @constructs openerp.web.Widget
1141 * @extends openerp.web.CallbackEnabled
1143 * @param {openerp.web.Widget} parent Binds the current instance to the given Widget instance.
1144 * When that widget is destroyed by calling destroy(), the current instance will be
1145 * destroyed too. Can be null.
1146 * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
1147 * to bind the current Widget to an already existing part of the DOM, which is not compatible
1148 * with the DOM insertion methods provided by the current implementation of Widget. So
1149 * for new components this argument should not be provided any more.
1151 init: function(parent) {
1152 this._super(parent);
1153 openerp.web.CallbackEnabledMixin.init.call(this);
1154 this.session = openerp.connection;
1157 * Renders the element. The default implementation renders the widget using QWeb,
1158 * `this.template` must be defined. The context given to QWeb contains the "widget"
1159 * key that references `this`.
1161 renderElement: function() {
1162 var rendered = null;
1164 rendered = openerp.web.qweb.render(this.template, {widget: this});
1165 if (_.str.trim(rendered)) {
1166 var elem = $(rendered);
1167 this.$element.replaceWith(elem);
1168 this.$element = elem;
1172 * Informs the action manager to do an action. This supposes that
1173 * the action manager can be found amongst the ancestors of the current widget.
1174 * If that's not the case this method will simply return `false`.
1176 do_action: function(action, on_finished) {
1177 if (this.getParent()) {
1178 return this.getParent().do_action(action, on_finished);
1182 do_notify: function() {
1183 if (this.getParent()) {
1184 return this.getParent().do_notify.apply(this,arguments);
1188 do_warn: function() {
1189 if (this.getParent()) {
1190 return this.getParent().do_warn.apply(this,arguments);
1194 rpc: function(url, data, success, error) {
1195 var def = $.Deferred().then(success, error);
1197 openerp.connection.rpc(url, data). then(function() {
1198 if (!self.isDestroyed())
1199 def.resolve.apply(def, arguments);
1201 if (!self.isDestroyed())
1202 def.reject.apply(def, arguments);
1204 return def.promise();
1209 * @deprecated use :class:`openerp.web.Widget`
1211 openerp.web.OldWidget = openerp.web.Widget.extend({
1212 init: function(parent, element_id) {
1213 this._super(parent);
1214 this.element_id = element_id;
1215 this.element_id = this.element_id || _.uniqueId('widget-');
1216 var tmp = document.getElementById(this.element_id);
1217 this.$element = tmp ? $(tmp) : $(document.createElement(this.tagName));
1219 renderElement: function() {
1220 var rendered = this.render();
1222 var elem = $(rendered);
1223 this.$element.replaceWith(elem);
1224 this.$element = elem;
1228 render: function (additional) {
1230 return openerp.web.qweb.render(this.template, _.extend({widget: this}, additional || {}));
1235 openerp.web.TranslationDataBase = openerp.web.Class.extend(/** @lends openerp.web.TranslationDataBase# */{
1237 * @constructs openerp.web.TranslationDataBase
1238 * @extends openerp.web.Class
1242 this.parameters = {"direction": 'ltr',
1243 "date_format": '%m/%d/%Y',
1244 "time_format": '%H:%M:%S',
1246 "decimal_point": ".",
1247 "thousands_sep": ","};
1249 set_bundle: function(translation_bundle) {
1252 var modules = _.keys(translation_bundle.modules);
1254 if (_.include(modules, "web")) {
1255 modules = ["web"].concat(_.without(modules, "web"));
1257 _.each(modules, function(name) {
1258 self.add_module_translation(translation_bundle.modules[name]);
1260 if (translation_bundle.lang_parameters) {
1261 this.parameters = translation_bundle.lang_parameters;
1262 this.parameters.grouping = py.eval(
1263 this.parameters.grouping);
1266 add_module_translation: function(mod) {
1268 _.each(mod.messages, function(message) {
1269 self.db[message.id] = message.string;
1272 build_translation_function: function() {
1274 var fcnt = function(str) {
1275 var tmp = self.get(str);
1276 return tmp === undefined ? str : tmp;
1278 fcnt.database = this;
1281 get: function(key) {
1283 return this.db[key];
1288 /** Configure blockui */
1290 $.blockUI.defaults.baseZ = 1100;
1291 $.blockUI.defaults.message = '<img src="/web/static/src/img/throbber2.gif">';
1294 /** Custom jQuery plugins */
1295 $.fn.getAttributes = function() {
1298 for (var attr, i = 0, attrs = this[0].attributes, l = attrs.length; i < l; i++) {
1299 attr = attrs.item(i)
1300 o[attr.nodeName] = attr.nodeValue;
1306 /** Configure default qweb */
1307 openerp.web._t = new openerp.web.TranslationDataBase().build_translation_function();
1309 * Lazy translation function, only performs the translation when actually
1310 * printed (e.g. inserted into a template)
1312 * Useful when defining translatable strings in code evaluated before the
1313 * translation database is loaded, as class attributes or at the top-level of
1314 * an OpenERP Web module
1316 * @param {String} s string to translate
1317 * @returns {Object} lazy translation object
1319 openerp.web._lt = function (s) {
1320 return {toString: function () { return openerp.web._t(s); }}
1322 openerp.web.qweb = new QWeb2.Engine();
1323 openerp.web.qweb.debug = ($.deparam($.param.querystring()).debug != undefined);
1324 openerp.web.qweb.default_dict = {
1326 '_t' : openerp.web._t
1328 openerp.web.qweb.preprocess_node = function() {
1329 // Note that 'this' is the Qweb Node
1330 switch (this.node.nodeType) {
1334 var translation = this.node.parentNode.attributes['t-translation'];
1335 if (translation && translation.value === 'off') {
1338 var ts = _.str.trim(this.node.data);
1339 if (ts.length === 0) {
1342 var tr = openerp.web._t(ts);
1344 this.node.data = tr;
1349 var attr, attrs = ['label', 'title', 'alt'];
1350 while (attr = attrs.pop()) {
1351 if (this.attributes[attr]) {
1352 this.attributes[attr] = openerp.web._t(this.attributes[attr]);
1359 * A small utility function to check if a class implements correctly an interface, assuming that
1360 * interface is simply specified using a dictionary containing methods and attributes with the
1361 * correct type. It only performs the check when in debug mode and the only effect of an invalid
1362 * check is messages in the console.
1364 openerp.web.check_interface = function(_class, _interface) {
1365 if (! openerp.web.check_interface.debug)
1367 for (var member in _interface) {
1368 if ( (typeof _class.prototype[member] != typeof _interface[member]) ) {
1369 console.error("class failed to implement interface member '" + member + "'");
1373 openerp.web.check_interface.debug = ($.deparam($.param.querystring()).debug != undefined);
1375 /** Jquery extentions */
1376 $.Mutex = (function() {
1378 this.def = $.Deferred().resolve();
1380 Mutex.prototype.exec = function(action) {
1381 var current = this.def;
1382 var next = this.def = $.Deferred();
1383 return current.pipe(function() {
1384 return $.when(action()).always(function() {
1392 /** Setup default connection */
1393 openerp.connection = new openerp.web.Connection();
1394 openerp.web.qweb.default_dict['__debug__'] = openerp.connection.debug;
1397 $.async_when = function() {
1399 var def = $.Deferred();
1400 $.when.apply($, arguments).then(function() {
1401 var args = arguments;
1402 var action = function() {
1403 def.resolve.apply(def, args);
1408 setTimeout(action, 0);
1410 var args = arguments;
1411 var action = function() {
1412 def.reject.apply(def, args);
1417 setTimeout(action, 0);
1423 // special tweak for the web client
1424 var old_async_when = $.async_when;
1425 $.async_when = function() {
1426 if (openerp.connection.synch)
1427 return $.when.apply(this, arguments);
1429 return old_async_when.apply(this, arguments);
1434 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: