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