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