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