[FIX] load modules when all css/qweb/js files are loaded
[odoo/odoo.git] / addons / web / static / src / js / core.js
1 /*---------------------------------------------------------
2  * OpenERP Web core
3  *--------------------------------------------------------*/
4 var console;
5 if (!console) {
6     console = {log: function () {}};
7 }
8 if (!console.debug) {
9     console.debug = console.log;
10 }
11
12 openerp.web.core = function(openerp) {
13 /**
14  * John Resig Class with factory improvement
15  */
16 (function() {
17     var initializing = false,
18         fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
19     // The web Class implementation (does nothing)
20     /**
21      * Extended version of John Resig's Class pattern
22      *
23      * @class
24      */
25     openerp.web.Class = function(){};
26
27     /**
28      * Subclass an existing class
29      *
30      * @param {Object} prop class-level properties (class attributes and instance methods) to set on the new class
31      */
32     openerp.web.Class.extend = function(prop) {
33         var _super = this.prototype;
34
35         // Instantiate a web class (but only create the instance,
36         // don't run the init constructor)
37         initializing = true;
38         var prototype = new this();
39         initializing = false;
40
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]) ?
47                     (function(name, fn) {
48                         return function() {
49                             var tmp = this._super;
50
51                             // Add a new ._super() method that is the same
52                             // method but on the super-class
53                             this._super = _super[name];
54
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);
58                             this._super = tmp;
59
60                             return ret;
61                         };
62                     })(name, prop[name]) :
63                     prop[name];
64         }
65
66         // The dummy class constructor
67         function Class() {
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; }
72             }
73             return this;
74         }
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) {
83                         return function () {
84                             var tmp = this._super;
85                             this._super = previous;
86                             var ret = fn.apply(this, arguments);
87                             this._super = tmp;
88                             return ret;
89                         }
90                     })(name, properties[name], prototype[name]);
91                 } else if (typeof _super[name] === 'function') {
92                     prototype[name] = (function (name, fn) {
93                         return function () {
94                             var tmp = this._super;
95                             this._super = _super[name];
96                             var ret = fn.apply(this, arguments);
97                             this._super = tmp;
98                             return ret;
99                         }
100                     })(name, properties[name]);
101                 }
102             }
103         };
104
105         // Populate our constructed prototype object
106         Class.prototype = prototype;
107
108         // Enforce the constructor to be what we expect
109         Class.constructor = Class;
110
111         // And make this class extendable
112         Class.extend = arguments.callee;
113
114         return Class;
115     };
116 })();
117
118 openerp.web.callback = function(obj, method) {
119     var callback = function() {
120         var args = Array.prototype.slice.call(arguments);
121         var r;
122         for(var i = 0; i < callback.callback_chain.length; i++)  {
123             var c = callback.callback_chain[i];
124             if(c.unique) {
125                 callback.callback_chain.splice(i, 1);
126                 i -= 1;
127             }
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
131                 r = result;
132             }
133             // TODO special value to stop the chain
134             // openerp.web.callback_stop
135         }
136         return r;
137     };
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) };
142         }
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);
148         } else {
149             callback.callback_chain.unshift(f);
150         }
151         return callback;
152     };
153     callback.add_first = function(f) {
154         return callback.add.apply(null,arguments);
155     };
156     callback.add_last = function(f) {
157         return callback.add({
158             callback: f,
159             args: Array.prototype.slice.call(arguments, 1),
160             position: "last"
161         });
162     };
163     callback.remove = function(f) {
164         callback.callback_chain = _.difference(callback.callback_chain, _.filter(callback.callback_chain, function(el) {
165             return el.callback === f;
166         }));
167         return callback;
168     };
169
170     return callback.add({
171         callback: method,
172         self:obj,
173         args:Array.prototype.slice.call(arguments, 2)
174     });
175 };
176
177 /**
178  * Generates an inherited class that replaces all the methods by null methods (methods
179  * that does nothing and always return undefined).
180  *
181  * @param {Class} claz
182  * @param {Object} add Additional functions to override.
183  * @return {Class}
184  */
185 openerp.web.generate_null_object_class = function(claz, add) {
186     var newer = {};
187     var copy_proto = function(prototype) {
188         for (var name in prototype) {
189             if(typeof prototype[name] == "function") {
190                 newer[name] = function() {};
191             }
192         }
193         if (prototype.prototype)
194             copy_proto(prototype.prototype);
195     };
196     copy_proto(claz.prototype);
197     newer.init = openerp.web.Widget.prototype.init;
198     var tmpclass = claz.extend(newer);
199     return tmpclass.extend(add || {});
200 };
201
202 /**
203  * web error for lookup failure
204  *
205  * @class
206  */
207 openerp.web.NotFound = openerp.web.Class.extend( /** @lends openerp.web.NotFound# */ {
208 });
209 openerp.web.KeyNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.KeyNotFound# */ {
210     /**
211      * Thrown when a key could not be found in a mapping
212      *
213      * @constructs openerp.web.KeyNotFound
214      * @extends openerp.web.NotFound
215      * @param {String} key the key which could not be found
216      */
217     init: function (key) {
218         this.key = key;
219     },
220     toString: function () {
221         return "The key " + this.key + " was not found";
222     }
223 });
224 openerp.web.ObjectNotFound = openerp.web.NotFound.extend( /** @lends openerp.web.ObjectNotFound# */ {
225     /**
226      * Thrown when an object path does not designate a valid class or object
227      * in the openerp hierarchy.
228      *
229      * @constructs openerp.web.ObjectNotFound
230      * @extends openerp.web.NotFound
231      * @param {String} path the invalid object path
232      */
233     init: function (path) {
234         this.path = path;
235     },
236     toString: function () {
237         return "Could not find any object of path " + this.path;
238     }
239 });
240 openerp.web.Registry = openerp.web.Class.extend( /** @lends openerp.web.Registry# */ {
241     /**
242      * Stores a mapping of arbitrary key (strings) to object paths (as strings
243      * as well).
244      *
245      * Resolves those paths at query time in order to always fetch the correct
246      * object, even if those objects have been overloaded/replaced after the
247      * registry was created.
248      *
249      * An object path is simply a dotted name from the openerp root to the
250      * object pointed to (e.g. ``"openerp.web.Connection"`` for an OpenERP
251      * connection object).
252      *
253      * @constructs openerp.web.Registry
254      * @param {Object} mapping a mapping of keys to object-paths
255      */
256     init: function (mapping) {
257         this.map = mapping || {};
258     },
259     /**
260      * Retrieves the object matching the provided key string.
261      *
262      * @param {String} key the key to fetch the object for
263      * @param {Boolean} [silent_error=false] returns undefined if the key or object is not found, rather than throwing an exception
264      * @returns {Class} the stored class, to initialize
265      *
266      * @throws {openerp.web.KeyNotFound} if the object was not in the mapping
267      * @throws {openerp.web.ObjectNotFound} if the object path was invalid
268      */
269     get_object: function (key, silent_error) {
270         var path_string = this.map[key];
271         if (path_string === undefined) {
272             if (silent_error) { return void 'nooo'; }
273             throw new openerp.web.KeyNotFound(key);
274         }
275
276         var object_match = openerp;
277         var path = path_string.split('.');
278         // ignore first section
279         for(var i=1; i<path.length; ++i) {
280             object_match = object_match[path[i]];
281
282             if (object_match === undefined) {
283                 if (silent_error) { return void 'noooooo'; }
284                 throw new openerp.web.ObjectNotFound(path_string);
285             }
286         }
287         return object_match;
288     },
289     /**
290      * Tries a number of keys, and returns the first object matching one of
291      * the keys.
292      *
293      * @param {Array} keys a sequence of keys to fetch the object for
294      * @returns {Class} the first class found matching an object
295      *
296      * @throws {openerp.web.KeyNotFound} if none of the keys was in the mapping
297      * @trows {openerp.web.ObjectNotFound} if a found object path was invalid
298      */
299     get_any: function (keys) {
300         for (var i=0; i<keys.length; ++i) {
301             var key = keys[i];
302             if (key === undefined || !(key in this.map)) {
303                 continue;
304             }
305
306             return this.get_object(key);
307         }
308         throw new openerp.web.KeyNotFound(keys.join(','));
309     },
310     /**
311      * Adds a new key and value to the registry.
312      *
313      * This method can be chained.
314      *
315      * @param {String} key
316      * @param {String} object_path fully qualified dotted object path
317      * @returns {openerp.web.Registry} itself
318      */
319     add: function (key, object_path) {
320         this.map[key] = object_path;
321         return this;
322     },
323     /**
324      * Creates and returns a copy of the current mapping, with the provided
325      * mapping argument added in (replacing existing keys if needed)
326      *
327      * @param {Object} [mapping={}] a mapping of keys to object-paths
328      */
329     clone: function (mapping) {
330         return new openerp.web.Registry(
331             _.extend({}, this.map, mapping || {}));
332     }
333 });
334
335 openerp.web.CallbackEnabled = openerp.web.Class.extend(/** @lends openerp.web.CallbackEnabled# */{
336     /**
337      * @constructs openerp.web.CallbackEnabled
338      * @extends openerp.web.Class
339      */
340     init: function() {
341         // Transform on_* method into openerp.web.callbacks
342         for (var name in this) {
343             if(typeof(this[name]) == "function") {
344                 this[name].debug_name = name;
345                 // bind ALL function to this not only on_and _do ?
346                 if((/^on_|^do_/).test(name)) {
347                     this[name] = openerp.web.callback(this, this[name]);
348                 }
349             }
350         }
351     },
352     /**
353      * Proxies a method of the object, in order to keep the right ``this`` on
354      * method invocations.
355      *
356      * This method is similar to ``Function.prototype.bind`` or ``_.bind``, and
357      * even more so to ``jQuery.proxy`` with a fundamental difference: its
358      * resolution of the method being called is lazy, meaning it will use the
359      * method as it is when the proxy is called, not when the proxy is created.
360      *
361      * Other methods will fix the bound method to what it is when creating the
362      * binding/proxy, which is fine in most javascript code but problematic in
363      * OpenERP Web where developers may want to replace existing callbacks with
364      * theirs.
365      *
366      * The semantics of this precisely replace closing over the method call.
367      *
368      * @param {String} method_name name of the method to invoke
369      * @returns {Function} proxied method
370      */
371     proxy: function (method_name) {
372         var self = this;
373         return function () {
374             return self[method_name].apply(self, arguments);
375         }
376     }
377 });
378
379 openerp.web.Connection = openerp.web.CallbackEnabled.extend( /** @lends openerp.web.Connection# */{
380     /**
381      * @constructs openerp.web.Connection
382      * @extends openerp.web.CallbackEnabled
383      *
384      * @param {String} [server] JSON-RPC endpoint hostname
385      * @param {String} [port] JSON-RPC endpoint port
386      */
387     init: function() {
388         this._super();
389         this.server = null;
390         this.debug = ($.deparam($.param.querystring()).debug != undefined);
391         // TODO: session store in cookie should be optional
392         this.name = openerp._session_id;
393         this.qweb_mutex = new $.Mutex();
394     },
395     bind: function(origin) {
396         var window_origin = location.protocol+"//"+location.host;
397         this.origin = origin ? _.str.rtrim(origin,'/') : window_origin;
398         this.prefix = this.origin;
399         this.server = this.origin; // keep chs happy
400         openerp.web.qweb.default_dict['_s'] = this.origin;
401         this.rpc_function = (this.origin == window_origin) ? this.rpc_json : this.rpc_jsonp;
402         this.session_id = false;
403         this.uid = false;
404         this.username = false;
405         this.user_context= {};
406         this.db = false;
407         this.openerp_entreprise = false;
408         this.module_list = [];
409         this.module_loaded = {"web": true};
410         this.context = {};
411         this.shortcuts = [];
412         this.active_id = null;
413         return this.session_init();
414     },
415     /**
416      * Executes an RPC call, registering the provided callbacks.
417      *
418      * Registers a default error callback if none is provided, and handles
419      * setting the correct session id and session context in the parameter
420      * objects
421      *
422      * @param {String} url RPC endpoint
423      * @param {Object} params call parameters
424      * @param {Function} success_callback function to execute on RPC call success
425      * @param {Function} error_callback function to execute on RPC call failure
426      * @returns {jQuery.Deferred} jquery-provided ajax deferred
427      */
428     rpc: function(url, params, success_callback, error_callback) {
429         var self = this;
430         // url can be an $.ajax option object
431         if (_.isString(url)) {
432             url = { url: url };
433         }
434         // Construct a JSON-RPC2 request, method is currently unused
435         params.session_id = this.session_id;
436         if (this.debug)
437             params.debug = 1;
438         var payload = {
439             jsonrpc: '2.0',
440             method: 'call',
441             params: params,
442             id: _.uniqueId('r')
443         };
444         var deferred = $.Deferred();
445         this.on_rpc_request();
446         this.rpc_function(url, payload).then(
447             function (response, textStatus, jqXHR) {
448                 self.on_rpc_response();
449                 if (!response.error) {
450                     deferred.resolve(response["result"], textStatus, jqXHR);
451                 } else if (response.error.data.type === "session_invalid") {
452                     self.uid = false;
453                     // TODO deprecate or use a deferred on login.do_ask_login()
454                     self.on_session_invalid(function() {
455                         self.rpc(url, payload.params,
456                             function() { deferred.resolve.apply(deferred, arguments); },
457                             function() { deferred.reject.apply(deferred, arguments); });
458                     });
459                 } else {
460                     deferred.reject(response.error, $.Event());
461                 }
462             },
463             function(jqXHR, textStatus, errorThrown) {
464                 self.on_rpc_response();
465                 var error = {
466                     code: -32098,
467                     message: "XmlHttpRequestError " + errorThrown,
468                     data: {type: "xhr"+textStatus, debug: jqXHR.responseText, objects: [jqXHR, errorThrown] }
469                 };
470                 deferred.reject(error, $.Event());
471             });
472         // Allow deferred user to disable on_rpc_error in fail
473         deferred.fail(function() {
474             deferred.fail(function(error, event) {
475                 if (!event.isDefaultPrevented()) {
476                     self.on_rpc_error(error, event);
477                 }
478             });
479         }).then(success_callback, error_callback).promise();
480         return deferred;
481     },
482     /**
483      * Raw JSON-RPC call
484      *
485      * @returns {jQuery.Deferred} ajax-webd deferred object
486      */
487     rpc_json: function(url, payload) {
488         var self = this;
489         var ajax = _.extend({
490             type: "POST",
491             dataType: 'json',
492             contentType: 'application/json',
493             data: JSON.stringify(payload),
494             processData: false,
495         }, url);
496         if (this.synch)
497                 ajax.async = false;
498         return $.ajax(ajax);
499     },
500     rpc_jsonp: function(url, payload) {
501         var self = this;
502         // extracted from payload to set on the url
503         var data = {
504             session_id: this.session_id,
505             id: payload.id,
506         };
507         url.url = this.get_url(url.url);
508         var ajax = _.extend({
509             type: "GET",
510             dataType: 'jsonp', 
511             jsonp: 'jsonp',
512             cache: false,
513             data: data
514         }, url);
515         if (this.synch)
516                 ajax.async = false;
517         var payload_str = JSON.stringify(payload);
518         var payload_url = $.param({r:payload_str});
519         if(payload_url.length < 2000) {
520             // Direct jsonp request
521             ajax.data.r = payload_str;
522             return $.ajax(ajax);
523         } else {
524             // Indirect jsonp request
525             var ifid = _.uniqueId('oe_rpc_iframe');
526             var display = options.openerp.debug ? 'block' : 'none';
527             var $iframe = $(_.str.sprintf("<iframe src='javascript:false;' name='%s' id='%s' style='display:%s'></iframe>", ifid, ifid, display));
528             var $form = $('<form>')
529                         .attr('method', 'POST')
530                         .attr('target', ifid)
531                         .attr('enctype', "multipart/form-data")
532                         .attr('action', ajax.url + '?' + $.param(data))
533                         .append($('<input type="hidden" name="r" />').attr('value', payload_str))
534                         .hide()
535                         .appendTo($('body'));
536             var cleanUp = function() {
537                 if ($iframe) {
538                     $iframe.unbind("load").attr("src", "javascript:false;").remove();
539                 }
540                 $form.remove();
541             };
542             var deferred = $.Deferred();
543             // the first bind is fired up when the iframe is added to the DOM
544             $iframe.bind('load', function() {
545                 // the second bind is fired up when the result of the form submission is received
546                 $iframe.unbind('load').bind('load', function() {
547                     $.ajax(ajax).always(function() {
548                         cleanUp();
549                     }).then(
550                         function() { deferred.resolve.apply(deferred, arguments); },
551                         function() { deferred.reject.apply(deferred, arguments); }
552                     );
553                 });
554                 // now that the iframe can receive data, we fill and submit the form
555                 $form.submit();
556             });
557             // append the iframe to the DOM (will trigger the first load)
558             $form.after($iframe);
559             return deferred;
560         }
561     },
562     on_rpc_request: function() {
563     },
564     on_rpc_response: function() {
565     },
566     on_rpc_error: function(error) {
567     },
568     /**
569      * Init a session, reloads from cookie, if it exists
570      */
571     session_init: function () {
572         var self = this;
573         // TODO: session store in cookie should be optional
574         this.session_id = this.get_cookie('session_id');
575         return this.session_reload().pipe(function(result) {
576             var modules = openerp._modules.join(',');
577             var deferred = self.rpc('/web/webclient/qweblist', {mods: modules}).pipe(self.do_load_qweb);
578             if(self.session_is_valid()) {
579                 return deferred.pipe(function() { return self.load_modules(); });
580             }
581             return deferred;
582         });
583     },
584     /**
585      * (re)loads the content of a session: db name, username, user id, session
586      * context and status of the support contract
587      *
588      * @returns {$.Deferred} deferred indicating the session is done reloading
589      */
590     session_reload: function () {
591         var self = this;
592         return this.rpc("/web/session/get_session_info", {}).then(function(result) {
593             // If immediately follows a login (triggered by trying to restore
594             // an invalid session or no session at all), refresh session data
595             // (should not change, but just in case...)
596             _.extend(self, {
597                 db: result.db,
598                 username: result.login,
599                 uid: result.uid,
600                 user_context: result.context,
601                 openerp_entreprise: result.openerp_entreprise
602             });
603         });
604     },
605     session_is_valid: function() {
606         return !!this.uid;
607     },
608     /**
609      * The session is validated either by login or by restoration of a previous session
610      */
611     session_authenticate: function(db, login, password, _volatile) {
612         var self = this;
613         var base_location = document.location.protocol + '//' + document.location.host;
614         var params = { db: db, login: login, password: password, base_location: base_location };
615         return this.rpc("/web/session/authenticate", params).pipe(function(result) {
616             _.extend(self, {
617                 session_id: result.session_id,
618                 db: result.db,
619                 username: result.login,
620                 uid: result.uid,
621                 user_context: result.context,
622                 openerp_entreprise: result.openerp_entreprise
623             });
624             if (!_volatile) {
625                 self.set_cookie('session_id', self.session_id);
626             }
627             return self.load_modules();
628         });
629     },
630     session_logout: function() {
631         this.set_cookie('session_id', '');
632     },
633     on_session_valid: function() {
634     },
635     /**
636      * Called when a rpc call fail due to an invalid session.
637      * By default, it's a noop
638      */
639     on_session_invalid: function(retry_callback) {
640     },
641     /**
642      * Fetches a cookie stored by an openerp session
643      *
644      * @private
645      * @param name the cookie's name
646      */
647     get_cookie: function (name) {
648         if (!this.name) { return null; }
649         var nameEQ = this.name + '|' + name + '=';
650         var cookies = document.cookie.split(';');
651         for(var i=0; i<cookies.length; ++i) {
652             var cookie = cookies[i].replace(/^\s*/, '');
653             if(cookie.indexOf(nameEQ) === 0) {
654                 return JSON.parse(decodeURIComponent(cookie.substring(nameEQ.length)));
655             }
656         }
657         return null;
658     },
659     /**
660      * Create a new cookie with the provided name and value
661      *
662      * @private
663      * @param name the cookie's name
664      * @param value the cookie's value
665      * @param ttl the cookie's time to live, 1 year by default, set to -1 to delete
666      */
667     set_cookie: function (name, value, ttl) {
668         if (!this.name) { return; }
669         ttl = ttl || 24*60*60*365;
670         document.cookie = [
671             this.name + '|' + name + '=' + encodeURIComponent(JSON.stringify(value)),
672             'path=/',
673             'max-age=' + ttl,
674             'expires=' + new Date(new Date().getTime() + ttl*1000).toGMTString()
675         ].join(';');
676     },
677     /**
678      * Load additional web addons of that instance and init them
679      */
680     load_modules: function() {
681         var self = this;
682         return this.rpc('/web/session/modules', {}).pipe(function(result) {
683             self.module_list = result;
684             var lang = self.user_context.lang;
685             var params = { mods: ["web"].concat(result), lang: lang};
686             var modules = self.module_list.join(',');
687             return $.when(
688                 self.rpc('/web/webclient/csslist', {mods: modules}, self.do_load_css),
689                 self.rpc('/web/webclient/qweblist', {mods: modules}).pipe(self.do_load_qweb),
690                 self.rpc('/web/webclient/translations', params).pipe(function(trans) {
691                     openerp.web._t.database.set_bundle(trans);
692                     var file_list = ["/web/static/lib/datejs/globalization/" + lang.replace("_", "-") + ".js"];
693                     return self.rpc('/web/webclient/jslist', {mods: modules}).pipe(function(files) {
694                         return self.do_load_js(file_list.concat(files)); 
695                     });
696                 })
697             ).then(function() {
698                 self.on_modules_loaded();
699                 self.on_session_valid();
700             });
701         });
702     },
703     do_load_css: function (files) {
704         var self = this;
705         _.each(files, function (file) {
706             $('head').append($('<link>', {
707                 'href': self.get_url(file),
708                 'rel': 'stylesheet',
709                 'type': 'text/css'
710             }));
711         });
712     },
713     do_load_js: function(files) {
714         var self = this;
715         var d = $.Deferred();
716         if(files.length != 0) {
717             var file = files.shift();
718             var tag = document.createElement('script');
719             tag.type = 'text/javascript';
720             tag.src = self.get_url(file);
721             tag.onload = tag.onreadystatechange = function() {
722                 if ( (tag.readyState && tag.readyState != "loaded" && tag.readyState != "complete") || tag.onload_done )
723                     return;
724                 tag.onload_done = true;
725                 self.do_load_js(files).then(function () {
726                     d.resolve();
727                 });
728             };
729             var head = document.head || document.getElementsByTagName('head')[0];
730             head.appendChild(tag);
731         } else {
732             d.resolve();
733         }
734         return d;
735     },
736     do_load_qweb: function(files) {
737         var self = this;
738         _.each(files, function(file) {
739             self.qweb_mutex.exec(function() {
740                 return self.rpc('/web/proxy/load', {path: file}).pipe(function(xml) {
741                     openerp.web.qweb.add_template(_.str.trim(xml));
742                 });
743             });
744         });
745         return self.qweb_mutex.def;
746     },
747     on_modules_loaded: function() {
748         for(var j=0; j<this.module_list.length; j++) {
749             var mod = this.module_list[j];
750             if(this.module_loaded[mod])
751                 continue;
752             openerp[mod] = {};
753             // init module mod
754             if(openerp._openerp[mod] != undefined) {
755                 openerp._openerp[mod](openerp);
756                 this.module_loaded[mod] = true;
757             }
758         }
759     },
760     get_url: function (file) {
761         return this.prefix + file;
762     },
763     /**
764      * Cooperative file download implementation, for ajaxy APIs.
765      *
766      * Requires that the server side implements an httprequest correctly
767      * setting the `fileToken` cookie to the value provided as the `token`
768      * parameter. The cookie *must* be set on the `/` path and *must not* be
769      * `httpOnly`.
770      *
771      * It would probably also be a good idea for the response to use a
772      * `Content-Disposition: attachment` header, especially if the MIME is a
773      * "known" type (e.g. text/plain, or for some browsers application/json
774      *
775      * @param {Object} options
776      * @param {String} [options.url] used to dynamically create a form
777      * @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
778      * @param {HTMLFormElement} [options.form] the form to submit in order to fetch the file
779      * @param {Function} [options.success] callback in case of download success
780      * @param {Function} [options.error] callback in case of request error, provided with the error body
781      * @param {Function} [options.complete] called after both ``success`` and ``error` callbacks have executed
782      */
783     get_file: function (options) {
784         // need to detect when the file is done downloading (not used
785         // yet, but we'll need it to fix the UI e.g. with a throbber
786         // while dump is being generated), iframe load event only fires
787         // when the iframe content loads, so we need to go smarter:
788         // http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
789         var timer, token = new Date().getTime(),
790             cookie_name = 'fileToken', cookie_length = cookie_name.length,
791             CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
792             remove_form = false;
793
794         var $form, $form_data = $('<div>');
795
796         var complete = function () {
797             if (options.complete) { options.complete(); }
798             clearTimeout(timer);
799             $form_data.remove();
800             $target.remove();
801             if (remove_form && $form) { $form.remove(); }
802         };
803         var $target = $('<iframe style="display: none;">')
804             .attr({id: id, name: id})
805             .appendTo(document.body)
806             .load(function () {
807                 if (options.error) { options.error(this.contentDocument.body); }
808                 complete();
809             });
810
811         if (options.form) {
812             $form = $(options.form);
813         } else {
814             remove_form = true;
815             $form = $('<form>', {
816                 action: options.url,
817                 method: 'POST'
818             }).appendTo(document.body);
819         }
820
821         _(_.extend({}, options.data || {},
822                    {session_id: this.session_id, token: token}))
823             .each(function (value, key) {
824                 $('<input type="hidden" name="' + key + '">')
825                     .val(value)
826                     .appendTo($form_data);
827             });
828
829         $form
830             .append($form_data)
831             .attr('target', id)
832             .get(0).submit();
833
834         var waitLoop = function () {
835             var cookies = document.cookie.split(';');
836             // setup next check
837             timer = setTimeout(waitLoop, CHECK_INTERVAL);
838             for (var i=0; i<cookies.length; ++i) {
839                 var cookie = cookies[i].replace(/^\s*/, '');
840                 if (!cookie.indexOf(cookie_name === 0)) { continue; }
841                 var cookie_val = cookie.substring(cookie_length + 1);
842                 if (parseInt(cookie_val, 10) !== token) { continue; }
843
844                 // clear cookie
845                 document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
846                     cookie_name, new Date().toGMTString());
847                 if (options.success) { options.success(); }
848                 complete();
849                 return;
850             }
851         };
852         timer = setTimeout(waitLoop, CHECK_INTERVAL);
853     },
854     synchronized_mode: function(to_execute) {
855         var synch = this.synch;
856         this.synch = true;
857         try {
858                 return to_execute();
859         } finally {
860                 this.synch = synch;
861         }
862     },
863 });
864
865 /**
866  * Base class for all visual components. Provides a lot of functionalities helpful
867  * for the management of a part of the DOM.
868  *
869  * Widget handles:
870  * - Rendering with QWeb.
871  * - Life-cycle management and parenting (when a parent is destroyed, all its children are
872  *     destroyed too).
873  * - Insertion in DOM.
874  *
875  * Guide to create implementations of the Widget class:
876  * ==============================================
877  *
878  * Here is a sample child class:
879  *
880  * MyWidget = openerp.base.Widget.extend({
881  *     // the name of the QWeb template to use for rendering
882  *     template: "MyQWebTemplate",
883  *     // identifier prefix, it is useful to put an obvious one for debugging
884  *     identifier_prefix: 'my-id-prefix-',
885  *
886  *     init: function(parent) {
887  *         this._super(parent);
888  *         // stuff that you want to init before the rendering
889  *     },
890  *     start: function() {
891  *         // stuff you want to make after the rendering, `this.$element` holds a correct value
892  *         this.$element.find(".my_button").click(/* an example of event binding * /);
893  *
894  *         // if you have some asynchronous operations, it's a good idea to return
895  *         // a promise in start()
896  *         var promise = this.rpc(...);
897  *         return promise;
898  *     }
899  * });
900  *
901  * Now this class can simply be used with the following syntax:
902  *
903  * var my_widget = new MyWidget(this);
904  * my_widget.appendTo($(".some-div"));
905  *
906  * With these two lines, the MyWidget instance was inited, rendered, it was inserted into the
907  * DOM inside the ".some-div" div and its events were binded.
908  *
909  * And of course, when you don't need that widget anymore, just do:
910  *
911  * my_widget.stop();
912  *
913  * That will kill the widget in a clean way and erase its content from the dom.
914  */
915 openerp.web.Widget = openerp.web.CallbackEnabled.extend(/** @lends openerp.web.Widget# */{
916     /**
917      * The name of the QWeb template that will be used for rendering. Must be
918      * redefined in subclasses or the default render() method can not be used.
919      *
920      * @type string
921      */
922     template: null,
923     /**
924      * The prefix used to generate an id automatically. Should be redefined in
925      * subclasses. If it is not defined, a generic identifier will be used.
926      *
927      * @type string
928      */
929     identifier_prefix: 'generic-identifier-',
930     /**
931      * Tag name when creating a default $element.
932      * @type string
933      */
934     tag_name: 'div',
935     /**
936      * Constructs the widget and sets its parent if a parent is given.
937      *
938      * @constructs openerp.web.Widget
939      * @extends openerp.web.CallbackEnabled
940      *
941      * @param {openerp.web.Widget} parent Binds the current instance to the given Widget instance.
942      * When that widget is destroyed by calling stop(), the current instance will be
943      * destroyed too. Can be null.
944      * @param {String} element_id Deprecated. Sets the element_id. Only useful when you want
945      * to bind the current Widget to an already existing part of the DOM, which is not compatible
946      * with the DOM insertion methods provided by the current implementation of Widget. So
947      * for new components this argument should not be provided any more.
948      */
949     init: function(parent, /** @deprecated */ element_id) {
950         this._super();
951         this.session = openerp.connection;
952         // if given an element_id, try to get the associated DOM element and save
953         // a reference in this.$element. Else just generate a unique identifier.
954         this.element_id = element_id;
955         this.element_id = this.element_id || _.uniqueId(this.identifier_prefix);
956         var tmp = document.getElementById(this.element_id);
957         this.$element = tmp ? $(tmp) : $(document.createElement(this.tag_name));
958
959         this.widget_parent = parent;
960         this.widget_children = [];
961         if(parent && parent.widget_children) {
962             parent.widget_children.push(this);
963         }
964         // useful to know if the widget was destroyed and should not be used anymore
965         this.widget_is_stopped = false;
966     },
967     /**
968      * Renders the current widget and appends it to the given jQuery object or Widget.
969      *
970      * @param target A jQuery object or a Widget instance.
971      */
972     appendTo: function(target) {
973         var self = this;
974         return this._render_and_insert(function(t) {
975             self.$element.appendTo(t);
976         }, target);
977     },
978     /**
979      * Renders the current widget and prepends it to the given jQuery object or Widget.
980      *
981      * @param target A jQuery object or a Widget instance.
982      */
983     prependTo: function(target) {
984         var self = this;
985         return this._render_and_insert(function(t) {
986             self.$element.prependTo(t);
987         }, target);
988     },
989     /**
990      * Renders the current widget and inserts it after to the given jQuery object or Widget.
991      *
992      * @param target A jQuery object or a Widget instance.
993      */
994     insertAfter: function(target) {
995         var self = this;
996         return this._render_and_insert(function(t) {
997             self.$element.insertAfter(t);
998         }, target);
999     },
1000     /**
1001      * Renders the current widget and inserts it before to the given jQuery object or Widget.
1002      *
1003      * @param target A jQuery object or a Widget instance.
1004      */
1005     insertBefore: function(target) {
1006         var self = this;
1007         return this._render_and_insert(function(t) {
1008             self.$element.insertBefore(t);
1009         }, target);
1010     },
1011     /**
1012      * Renders the current widget and replaces the given jQuery object.
1013      *
1014      * @param target A jQuery object or a Widget instance.
1015      */
1016     replace: function(target) {
1017         return this._render_and_insert(_.bind(function(t) {
1018             this.$element.replaceAll(t);
1019         }, this), target);
1020     },
1021     _render_and_insert: function(insertion, target) {
1022         this.render_element();
1023         if (target instanceof openerp.web.Widget)
1024             target = target.$element;
1025         insertion(target);
1026         this.on_inserted(this.$element, this);
1027         return this.start();
1028     },
1029     on_inserted: function(element, widget) {},
1030     /**
1031      * Renders the element and insert the result of the render() method in this.$element.
1032      */
1033     render_element: function() {
1034         var rendered = this.render();
1035         if (rendered) {
1036             var elem = $(rendered);
1037             this.$element.replaceWith(elem);
1038             this.$element = elem;
1039         }
1040         return this;
1041     },
1042     /**
1043      * Renders the widget using QWeb, `this.template` must be defined.
1044      * The context given to QWeb contains the "widget" key that references `this`.
1045      *
1046      * @param {Object} additional Additional context arguments to pass to the template.
1047      */
1048     render: function (additional) {
1049         if (this.template)
1050             return openerp.web.qweb.render(this.template, _.extend({widget: this}, additional || {}));
1051         return null;
1052     },
1053     /**
1054      * Method called after rendering. Mostly used to bind actions, perform asynchronous
1055      * calls, etc...
1056      *
1057      * By convention, the method should return a promise to inform the caller when
1058      * this widget has been initialized.
1059      *
1060      * @returns {jQuery.Deferred}
1061      */
1062     start: function() {
1063         return $.Deferred().done().promise();
1064     },
1065     /**
1066      * Destroys the current widget, also destroys all its children before destroying itself.
1067      */
1068     stop: function() {
1069         _.each(_.clone(this.widget_children), function(el) {
1070             el.stop();
1071         });
1072         if(this.$element != null) {
1073             this.$element.remove();
1074         }
1075         if (this.widget_parent && this.widget_parent.widget_children) {
1076             this.widget_parent.widget_children = _.without(this.widget_parent.widget_children, this);
1077         }
1078         this.widget_parent = null;
1079         this.widget_is_stopped = true;
1080     },
1081     /**
1082      * Informs the action manager to do an action. This supposes that
1083      * the action manager can be found amongst the ancestors of the current widget.
1084      * If that's not the case this method will simply return `false`.
1085      */
1086     do_action: function(action, on_finished) {
1087         if (this.widget_parent) {
1088             return this.widget_parent.do_action(action, on_finished);
1089         }
1090         return false;
1091     },
1092     do_notify: function() {
1093         if (this.widget_parent) {
1094             return this.widget_parent.do_notify.apply(this,arguments);
1095         }
1096         return false;
1097     },
1098     do_warn: function() {
1099         if (this.widget_parent) {
1100             return this.widget_parent.do_warn.apply(this,arguments);
1101         }
1102         return false;
1103     },
1104
1105     rpc: function(url, data, success, error) {
1106         var def = $.Deferred().then(success, error);
1107         var self = this;
1108         openerp.connection.rpc(url, data). then(function() {
1109             if (!self.widget_is_stopped)
1110                 def.resolve.apply(def, arguments);
1111         }, function() {
1112             if (!self.widget_is_stopped)
1113                 def.reject.apply(def, arguments);
1114         });
1115         return def.promise();
1116     }
1117 });
1118
1119 /**
1120  * @class
1121  * @extends openerp.web.Widget
1122  * @deprecated
1123  * For retro compatibility only, the only difference with is that render() uses
1124  * directly ``this`` instead of context with a ``widget`` key.
1125  */
1126 openerp.web.OldWidget = openerp.web.Widget.extend(/** @lends openerp.web.OldWidget# */{
1127     render: function (additional) {
1128         return openerp.web.qweb.render(this.template, _.extend(_.extend({}, this), additional || {}));
1129     }
1130 });
1131
1132 openerp.web.TranslationDataBase = openerp.web.Class.extend(/** @lends openerp.web.TranslationDataBase# */{
1133     /**
1134      * @constructs openerp.web.TranslationDataBase
1135      * @extends openerp.web.Class
1136      */
1137     init: function() {
1138         this.db = {};
1139         this.parameters = {"direction": 'ltr',
1140                         "date_format": '%m/%d/%Y',
1141                         "time_format": '%H:%M:%S',
1142                         "grouping": [],
1143                         "decimal_point": ".",
1144                         "thousands_sep": ","};
1145     },
1146     set_bundle: function(translation_bundle) {
1147         var self = this;
1148         this.db = {};
1149         var modules = _.keys(translation_bundle.modules);
1150         modules.sort();
1151         if (_.include(modules, "web")) {
1152             modules = ["web"].concat(_.without(modules, "web"));
1153         }
1154         _.each(modules, function(name) {
1155             self.add_module_translation(translation_bundle.modules[name]);
1156         });
1157         if (translation_bundle.lang_parameters) {
1158             this.parameters = translation_bundle.lang_parameters;
1159             this.parameters.grouping = py.eval(
1160                     this.parameters.grouping).toJSON();
1161         }
1162     },
1163     add_module_translation: function(mod) {
1164         var self = this;
1165         _.each(mod.messages, function(message) {
1166             if (self.db[message.id] === undefined) {
1167                 self.db[message.id] = message.string;
1168             }
1169         });
1170     },
1171     build_translation_function: function() {
1172         var self = this;
1173         var fcnt = function(str) {
1174             var tmp = self.get(str);
1175             return tmp === undefined ? str : tmp;
1176         };
1177         fcnt.database = this;
1178         return fcnt;
1179     },
1180     get: function(key) {
1181         if (this.db[key])
1182             return this.db[key];
1183         return undefined;
1184     }
1185 });
1186
1187 /** Configure blockui */
1188 if ($.blockUI) {
1189     $.blockUI.defaults.baseZ = 1100;
1190     $.blockUI.defaults.message = '<img src="/web/static/src/img/throbber2.gif">';
1191 }
1192
1193 /** Configure default qweb */
1194 openerp.web._t = new openerp.web.TranslationDataBase().build_translation_function();
1195 /**
1196  * Lazy translation function, only performs the translation when actually
1197  * printed (e.g. inserted into a template)
1198  *
1199  * Useful when defining translatable strings in code evaluated before the
1200  * translation database is loaded, as class attributes or at the top-level of
1201  * an OpenERP Web module
1202  *
1203  * @param {String} s string to translate
1204  * @returns {Object} lazy translation object
1205  */
1206 openerp.web._lt = function (s) {
1207     return {toString: function () { return openerp.web._t(s); }}
1208 };
1209 openerp.web.qweb = new QWeb2.Engine();
1210 openerp.web.qweb.debug = (window.location.search.indexOf('?debug') !== -1);
1211 openerp.web.qweb.default_dict = {
1212     '_' : _,
1213     '_t' : openerp.web._t
1214 };
1215 openerp.web.qweb.format_text_node = function(s) {
1216     // Note that 'this' is the Qweb Node of the text
1217     var translation = this.node.parentNode.attributes['t-translation'];
1218     if (translation && translation.value === 'off') {
1219         return s;
1220     }
1221     var ts = _.str.trim(s);
1222     if (ts.length === 0) {
1223         return s;
1224     }
1225     var tr = openerp.web._t(ts);
1226     return tr === ts ? s : tr;
1227 }
1228
1229 /** Jquery extentions */
1230 $.Mutex = (function() {
1231     function Mutex() {
1232         this.def = $.Deferred().resolve();
1233     };
1234     Mutex.prototype.exec = function(action) {
1235         var current = this.def;
1236         var next = this.def = $.Deferred();
1237         return current.pipe(function() {
1238             return $.when(action()).always(function() {
1239                 next.resolve();
1240             });
1241         });
1242     };
1243     return Mutex;
1244 })();
1245
1246 /** Setup default connection */
1247 openerp.connection = new openerp.web.Connection();
1248 openerp.web.qweb.default_dict['__debug__'] = openerp.connection.debug;
1249
1250
1251 $.async_when = function() {
1252     var async = false;
1253     var def = $.Deferred();
1254     $.when.apply($, arguments).then(function() {
1255         var args = arguments;
1256         var action = function() {
1257             def.resolve.apply(def, args);
1258         };
1259         if (async)
1260             action();
1261         else
1262             setTimeout(action, 0);
1263     }, function() {
1264         var args = arguments;
1265         var action = function() {
1266             def.reject.apply(def, args);
1267         };
1268         if (async)
1269             action();
1270         else
1271             setTimeout(action, 0);
1272     });
1273     async = true;
1274     return def;
1275 };
1276
1277 // special tweak for the web client
1278 var old_async_when = $.async_when;
1279 $.async_when = function() {
1280         if (openerp.connection.synch)
1281                 return $.when.apply(this, arguments);
1282         else
1283                 return old_async_when.apply(this, arguments);
1284 };
1285
1286 };
1287
1288 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: