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