[IMP] Major improvement to kitten mode
[odoo/odoo.git] / addons / web / static / src / js / chrome.js
1 /*---------------------------------------------------------
2  * OpenERP Web chrome
3  *---------------------------------------------------------*/
4 openerp.web.chrome = function(instance) {
5 var QWeb = instance.web.qweb,
6     _t = instance.web._t;
7
8 instance.web.Notification =  instance.web.Widget.extend({
9     template: 'Notification',
10     init: function() {
11         this._super.apply(this, arguments);
12         instance.web.notification = this;
13     },
14     start: function() {
15         this._super.apply(this, arguments);
16         this.$element.notify({
17             speed: 500,
18             expires: 2500
19         });
20     },
21     notify: function(title, text, sticky) {
22         sticky = !!sticky;
23         var opts = {};
24         if (sticky) {
25             opts.expires = false;
26         }
27         this.$element.notify('create', {
28             title: title,
29             text: text
30         }, opts);
31     },
32     warn: function(title, text, sticky) {
33         sticky = !!sticky;
34         var opts = {};
35         if (sticky) {
36             opts.expires = false;
37         }
38         this.$element.notify('create', 'oe_notification_alert', {
39             title: title,
40             text: text
41         }, opts);
42     }
43 });
44
45 /**
46  * The very minimal function everything should call to create a dialog
47  * in OpenERP Web Client.
48  */
49 instance.web.dialog = function(element) {
50     var result = element.dialog.apply(element, _.rest(_.toArray(arguments)));
51     result.dialog("widget").addClass("openerp");
52     return result;
53 };
54
55 instance.web.Dialog = instance.web.Widget.extend({
56     dialog_title: "",
57     init: function (parent, options, content) {
58         var self = this;
59         this._super(parent);
60         if (content) {
61             this.$element = content instanceof $ ? content : $(content);
62         }
63         this.dialog_options = {
64             modal: true,
65             destroy_on_close: true,
66             width: $(window).width() * (($(window).width() > 1024) ? 0.5 : 0.75),
67             min_width: 0,
68             max_width: '95%',
69             height: 'auto',
70             min_height: 0,
71             max_height: this.get_height('100%') - 140,
72             autoOpen: false,
73             position: [false, 50],
74             buttons: {},
75             beforeClose: function () { self.on_close(); },
76             resizeStop: this.on_resized
77         };
78         for (var f in this) {
79             if (f.substr(0, 10) == 'on_button_') {
80                 this.dialog_options.buttons[f.substr(10)] = this[f];
81             }
82         }
83         if (options) {
84             _.extend(this.dialog_options, options);
85         }
86         if (this.dialog_options.autoOpen) {
87             this.open();
88         } else {
89             instance.web.dialog(this.$element, this.get_options());
90         }
91     },
92     get_options: function(options) {
93         var self = this,
94             o = _.extend({}, this.dialog_options, options || {});
95         _.each(['width', 'height'], function(unit) {
96             o[unit] = self['get_' + unit](o[unit]);
97             o['min_' + unit] = self['get_' + unit](o['min_' + unit] || 0);
98             o['max_' + unit] = self['get_' + unit](o['max_' + unit] || 0);
99             if (o[unit] !== 'auto' && o['min_' + unit] && o[unit] < o['min_' + unit]) o[unit] = o['min_' + unit];
100             if (o[unit] !== 'auto' && o['max_' + unit] && o[unit] > o['max_' + unit]) o[unit] = o['max_' + unit];
101         });
102         if (!o.title && this.dialog_title) {
103             o.title = this.dialog_title;
104         }
105         return o;
106     },
107     get_width: function(val) {
108         return this.get_size(val.toString(), $(window.top).width());
109     },
110     get_height: function(val) {
111         return this.get_size(val.toString(), $(window.top).height());
112     },
113     get_size: function(val, available_size) {
114         if (val === 'auto') {
115             return val;
116         } else if (val.slice(-1) == "%") {
117             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
118         } else {
119             return parseInt(val, 10);
120         }
121     },
122     open: function(options) {
123         // TODO fme: bind window on resize
124         if (this.template) {
125             this.$element.html(this.renderElement());
126         }
127         var o = this.get_options(options);
128         instance.web.dialog(this.$element, o).dialog('open');
129         if (o.height === 'auto' && o.max_height) {
130             this.$element.css({ 'max-height': o.max_height, 'overflow-y': 'auto' });
131         }
132         return this;
133     },
134     close: function() {
135         this.$element.dialog('close');
136     },
137     on_close: function() {
138         if (this.dialog_options.destroy_on_close) {
139             this.$element.dialog('destroy');
140         }
141     },
142     on_resized: function() {
143     },
144     destroy: function () {
145         this.close();
146         this.$element.dialog('destroy');
147         this._super();
148     }
149 });
150
151 instance.web.CrashManager = instance.web.CallbackEnabled.extend({
152     on_rpc_error: function(error) {
153         if (error.data.fault_code) {
154             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
155             if (split.length > 1) {
156                 error.type = split.shift();
157                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
158             }
159         }
160         if (error.code === 200 && error.type) {
161             this.on_managed_error(error);
162         } else {
163             this.on_traceback(error);
164         }
165     },
166     on_managed_error: function(error) {
167         instance.web.dialog($('<div>' + QWeb.render('CrashManager.warning', {error: error}) + '</div>'), {
168             title: "OpenERP " + _.str.capitalize(error.type),
169             buttons: [
170                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
171             ]
172         });
173     },
174     on_traceback: function(error) {
175         var self = this;
176         var buttons = {};
177         if (instance.connection.openerp_entreprise) {
178             buttons[_t("Send OpenERP Enterprise Report")] = function() {
179                 var $this = $(this);
180                 var issuename = $('#issuename').val();
181                 var explanation = $('#explanation').val();
182                 var remark = $('#remark').val();
183                 // Call the send method from server to send mail with details
184                 new instance.web.DataSet(self, 'publisher_warranty.contract').call_and_eval('send', [error.data,explanation,remark,issuename]).then(function(result){
185                     if (result === false) {
186                         alert('There was a communication error.');
187                     } else {
188                         $this.dialog('close');
189                     }
190                 });
191             };
192             buttons[_t("Dont send")] = function() {
193                 $(this).dialog("close");
194             };
195         } else {
196             buttons[_t("Ok")] = function() {
197                 $(this).dialog("close");
198             };
199         }
200         var dialog = new instance.web.Dialog(this, {
201             title: "OpenERP " + _.str.capitalize(error.type),
202             width: '80%',
203             height: '50%',
204             min_width: '800px',
205             min_height: '600px',
206             buttons: buttons
207         }).open();
208         dialog.$element.html(QWeb.render('CrashManager.error', {session: instance.connection, error: error}));
209     },
210     on_javascript_exception: function(exception) {
211         this.on_traceback({
212             type: _t("Client Error"),
213             message: exception,
214             data: {debug: ""}
215         });
216     },
217 });
218
219 instance.web.Loading = instance.web.Widget.extend({
220     template: 'Loading',
221     init: function(parent) {
222         this._super(parent);
223         this.count = 0;
224         this.blocked_ui = false;
225         var self = this;
226         this.request_call = function() {
227             self.on_rpc_event(1);
228         };
229         this.response_call = function() {
230             self.on_rpc_event(-1);
231         };
232         this.session.on_rpc_request.add_first(this.request_call);
233         this.session.on_rpc_response.add_last(this.response_call);
234     },
235     destroy: function() {
236         this.session.on_rpc_request.remove(this.request_call);
237         this.session.on_rpc_response.remove(this.response_call);
238         this.on_rpc_event(-this.count);
239         this._super();
240     },
241     on_rpc_event : function(increment) {
242         var self = this;
243         if (!this.count && increment === 1) {
244             // Block UI after 3s
245             this.long_running_timer = setTimeout(function () {
246                 self.blocked_ui = true;
247                 $.blockUI();
248             }, 3000);
249         }
250
251         this.count += increment;
252         if (this.count > 0) {
253             this.$element.text(_.str.sprintf( _t("Loading (%d)"), this.count));
254             this.$element.show();
255             this.getParent().$element.addClass('oe_wait');
256         } else {
257             this.count = 0;
258             clearTimeout(this.long_running_timer);
259             // Don't unblock if blocked by somebody else
260             if (self.blocked_ui) {
261                 this.blocked_ui = false;
262                 $.unblockUI();
263             }
264             this.$element.fadeOut();
265             this.getParent().$element.removeClass('oe_wait');
266         }
267     }
268 });
269
270 instance.web.DatabaseManager = instance.web.Widget.extend({
271     init: function(parent) {
272         this._super(parent);
273         this.unblockUIFunction = $.unblockUI;
274         $.validator.addMethod('matches', function (s, _, re) {
275             return new RegExp(re).test(s);
276         }, _t("Invalid database name"));
277     },
278     start: function() {
279         var self = this;
280         var fetch_db = this.rpc("/web/database/get_list", {}).pipe(
281             function(result) {
282                 self.db_list = result.db_list;
283             },
284             function (_, ev) {
285                 ev.preventDefault();
286                 self.db_list = null;
287             });
288         var fetch_langs = this.rpc("/web/session/get_lang_list", {}).then(function(result) {
289             self.lang_list = result.lang_list;
290         });
291         return $.when(fetch_db, fetch_langs).then(self.do_render);
292     },
293     do_render: function() {
294         var self = this;
295         self.$element.html(QWeb.render("DatabaseManager", { widget : self }));
296         self.$element.find(".oe_database_manager_menu").tabs({
297             show: function(event, ui) {
298                 $('*[autofocus]:first', ui.panel).focus();
299             }
300         });
301         self.$element.find("form[name=create_db_form]").validate({ submitHandler: self.do_create });
302         self.$element.find("form[name=drop_db_form]").validate({ submitHandler: self.do_drop });
303         self.$element.find("form[name=backup_db_form]").validate({ submitHandler: self.do_backup });
304         self.$element.find("form[name=restore_db_form]").validate({ submitHandler: self.do_restore });
305         self.$element.find("form[name=change_pwd_form]").validate({
306             messages: {
307                 old_pwd: "Please enter your previous password",
308                 new_pwd: "Please enter your new password",
309                 confirm_pwd: {
310                     required: "Please confirm your new password",
311                     equalTo: "The confirmation does not match the password"
312                 }
313             },
314             submitHandler: self.do_change_password
315         });
316         self.$element.find("#back_to_login").click(self.do_exit);
317     },
318     destroy: function () {
319         this.$element.find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login').unbind('click').end().empty();
320         this._super();
321     },
322     /**
323      * Converts a .serializeArray() result into a dict. Does not bother folding
324      * multiple identical keys into an array, last key wins.
325      *
326      * @param {Array} array
327      */
328     to_object: function (array) {
329         var result = {};
330         _(array).each(function (record) {
331             result[record.name] = record.value;
332         });
333         return result;
334     },
335     /**
336      * Blocks UI and replaces $.unblockUI by a noop to prevent third parties
337      * from unblocking the UI
338      */
339     blockUI: function () {
340         $.blockUI();
341         $.unblockUI = function () {};
342     },
343     /**
344      * Reinstates $.unblockUI so third parties can play with blockUI, and
345      * unblocks the UI
346      */
347     unblockUI: function () {
348         $.unblockUI = this.unblockUIFunction;
349         $.unblockUI();
350     },
351     /**
352      * Displays an error dialog resulting from the various RPC communications
353      * failing over themselves
354      *
355      * @param {Object} error error description
356      * @param {String} error.title title of the error dialog
357      * @param {String} error.error message of the error dialog
358      */
359     display_error: function (error) {
360         return instance.web.dialog($('<div>'), {
361             modal: true,
362             title: error.title,
363             buttons: [
364                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
365             ]
366         }).html(error.error);
367     },
368     do_create: function(form) {
369         var self = this;
370         var fields = $(form).serializeArray();
371         self.rpc("/web/database/create", {'fields': fields}, function(result) {
372             var form_obj = self.to_object(fields);
373             self.getParent().do_login( form_obj['db_name'], 'admin', form_obj['create_admin_pwd']);
374             self.destroy();
375         });
376
377     },
378     do_drop: function(form) {
379         var self = this;
380         var $form = $(form),
381             fields = $form.serializeArray(),
382             $db_list = $form.find('[name=drop_db]'),
383             db = $db_list.val();
384         if (!db || !confirm("Do you really want to delete the database: " + db + " ?")) {
385             return;
386         }
387         self.rpc("/web/database/drop", {'fields': fields}, function(result) {
388             if (result.error) {
389                 self.display_error(result);
390                 return;
391             }
392             self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
393             self.start();
394         });
395     },
396     do_backup: function(form) {
397         var self = this;
398         self.blockUI();
399         self.session.get_file({
400             form: form,
401             success: function () {
402                 self.do_notify(_t("Backed"), _t("Database backed up successfully"));
403             },
404             error: instance.webclient.crashmanager.on_rpc_error,
405             complete: function() {
406                 self.unblockUI();
407             }
408         });
409     },
410     do_restore: function(form) {
411         var self = this;
412         self.blockUI();
413         $(form).ajaxSubmit({
414             url: '/web/database/restore',
415             type: 'POST',
416             resetForm: true,
417             success: function (body) {
418                 // If empty body, everything went fine
419                 if (!body) { return; }
420
421                 if (body.indexOf('403 Forbidden') !== -1) {
422                     self.display_error({
423                         title: 'Access Denied',
424                         error: 'Incorrect super-administrator password'
425                     });
426                 } else {
427                     self.display_error({
428                         title: 'Restore Database',
429                         error: 'Could not restore the database'
430                     });
431                 }
432             },
433             complete: function() {
434                 self.unblockUI();
435                 self.do_notify(_t("Restored"), _t("Database restored successfully"));
436             }
437         });
438     },
439     do_change_password: function(form) {
440         var self = this;
441         self.rpc("/web/database/change_password", {
442             'fields': $(form).serializeArray()
443         }, function(result) {
444             if (result.error) {
445                 self.display_error(result);
446                 return;
447             }
448             self.do_notify("Changed Password", "Password has been changed successfully");
449         });
450     },
451     do_exit: function () {
452     }
453 });
454
455 instance.web.Login =  instance.web.Widget.extend({
456     template: "Login",
457     remember_credentials: true,
458     _db_list: null,
459
460     init: function(parent) {
461         this._super(parent);
462         this.has_local_storage = typeof(localStorage) != 'undefined';
463         this.selected_db = null;
464         this.selected_login = null;
465
466         if (this.has_local_storage && this.remember_credentials) {
467             this.selected_db = localStorage.getItem('last_db_login_success');
468             this.selected_login = localStorage.getItem('last_login_login_success');
469             if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
470                 this.selected_password = localStorage.getItem('last_password_login_success');
471             }
472         }
473     },
474     start: function() {
475         var self = this;
476
477         self.$element.find("form").submit(self.on_submit);
478
479         self.$element.find('.oe_login_manage_db').click(function() {
480             self.$element.find('.oe_login_bottom').hide();
481             self.$element.find('.oe_login_pane').hide();
482             self.databasemanager = new instance.web.DatabaseManager(self);
483             self.databasemanager.appendTo(self.$element);
484             self.databasemanager.do_exit.add_last(function() {
485                 self.databasemanager.destroy();
486                 self.$element.find('.oe_login_bottom').show();
487                 self.$element.find('.oe_login_pane').show();
488                 self.load_db_list(true).then(self.proxy('_db_list_loaded'));
489             });
490         });
491         return self.load_db_list().then(self.proxy('_db_list_loaded'));
492     },
493     load_db_list: function (force) {
494         var d = $.when(), self = this;
495         if (_.isNull(this._db_list) || force) {
496             d = self.rpc("/web/database/get_list", {}, function(result) {
497                 self._db_list = _.clone(result.db_list);
498             }, function(error, event) {
499                 if (error.data.fault_code === 'AccessDenied') {
500                     event.preventDefault();
501                 }
502             });
503         }
504         return d;
505     },
506     _db_list_loaded: function () {
507         var list = this._db_list,
508             dbdiv = this.$element.find('div.oe_login_dbpane');
509         this.$element.find("[name=db]").replaceWith(instance.web.qweb.render('Login.dblist', { db_list: list, selected_db: this.selected_db}));
510         if(list && list.length === 1) {
511             dbdiv.hide();
512         } else {
513             dbdiv.show();
514         }
515     },
516     on_submit: function(ev) {
517         if(ev) {
518             ev.preventDefault();
519         }
520         var $e = this.$element;
521         var db = $e.find("form [name=db]").val();
522         if (!db) {
523             this.do_warn("Login", "No database selected !");
524             return false;
525         }
526         var login = $e.find("form input[name=login]").val();
527         var password = $e.find("form input[name=password]").val();
528
529         this.do_login(db, login, password);
530     },
531     /**
532      * Performs actual login operation, and UI-related stuff
533      *
534      * @param {String} db database to log in
535      * @param {String} login user login
536      * @param {String} password user password
537      */
538     do_login: function (db, login, password) {
539         var self = this;
540         this.$element.removeClass('oe_login_invalid');
541         return this.session.session_authenticate(db, login, password).pipe(function() {
542             if (self.has_local_storage) {
543                 if(self.remember_credentials) {
544                     localStorage.setItem('last_db_login_success', db);
545                     localStorage.setItem('last_login_login_success', login);
546                     if (jQuery.deparam(jQuery.param.querystring()).debug !== undefined) {
547                         localStorage.setItem('last_password_login_success', password);
548                     }
549                 } else {
550                     localStorage.setItem('last_db_login_success', '');
551                     localStorage.setItem('last_login_login_success', '');
552                     localStorage.setItem('last_password_login_success', '');
553                 }
554             }
555             self.$(".oe_login_pane").fadeOut("slow");
556             self.trigger("login");
557         },function () {
558             self.$element.addClass("oe_login_invalid");
559         });
560     }
561 });
562
563 instance.web.Menu =  instance.web.Widget.extend({
564     template: 'Menu',
565     init: function() {
566         this._super.apply(this, arguments);
567         this.has_been_loaded = $.Deferred();
568         this.maximum_visible_links = 'auto'; // # of menu to show. 0 = do not crop, 'auto' = algo
569         this.data = {data:{children:[]}};
570     },
571     start: function() {
572         this._super.apply(this, arguments);
573         this.$secondary_menus = this.getParent().$element.find('.oe_secondary_menus_container');
574         return this.do_reload();
575     },
576     do_reload: function() {
577         return this.rpc("/web/menu/load", {}).then(this.on_loaded);
578     },
579     on_loaded: function(data) {
580         var self = this;
581         this.data = data;
582         this.renderElement();
583         this.limit_entries();
584         this.$secondary_menus.html(QWeb.render("Menu.secondary", { widget : this }));
585         this.$element.on('click', 'a[data-menu]', this.on_menu_click);
586         this.$secondary_menus.on('click', 'a[data-menu]', this.on_menu_click);
587         // Hide second level submenus
588         this.$secondary_menus.find('.oe_menu_toggler').siblings('.oe_secondary_submenu').hide();
589         if (self.current_menu) {
590             self.open_menu(self.current_menu);
591         }
592         this.has_been_loaded.resolve();
593     },
594     limit_entries: function() {
595         var maximum_visible_links = this.maximum_visible_links;
596         if (maximum_visible_links === 'auto') {
597             maximum_visible_links = this.auto_limit_entries();
598         }
599         if (maximum_visible_links < this.data.data.children.length) {
600             var $more = $(QWeb.render('Menu.more')),
601                 $index = this.$element.find('li').eq(maximum_visible_links - 1);
602             $index.after($more);
603             $more.find('.oe_menu_more').append($index.next().nextAll());
604         }
605     },
606     auto_limit_entries: function() {
607         // TODO: auto detect overflow and bind window on resize
608         var width = $(window).width();
609         return Math.floor(width / 125);
610     },
611     /**
612      * Opens a given menu by id, as if a user had browsed to that menu by hand
613      * except does not trigger any event on the way
614      *
615      * @param {Number} id database id of the terminal menu to select
616      */
617     open_menu: function (id) {
618         var $clicked_menu, $sub_menu, $main_menu;
619         $clicked_menu = this.$element.add(this.$secondary_menus).find('a[data-menu=' + id + ']');
620         this.trigger('open_menu', id, $clicked_menu);
621
622         if (this.$secondary_menus.has($clicked_menu).length) {
623             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
624             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
625         } else {
626             $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
627             $main_menu = $clicked_menu;
628         }
629
630         // Activate current main menu
631         this.$element.find('.oe_active').removeClass('oe_active');
632         $main_menu.addClass('oe_active');
633
634         // Show current sub menu
635         this.$secondary_menus.find('.oe_secondary_menu').hide();
636         $sub_menu.show();
637
638         // Hide/Show the leftbar menu depending of the presence of sub-items
639         this.$secondary_menus.parent('.oe_leftbar').toggle(!!$sub_menu.children().length);
640
641         // Activate current menu item and show parents
642         this.$secondary_menus.find('.oe_active').removeClass('oe_active');
643         if ($main_menu !== $clicked_menu) {
644             $clicked_menu.parents().show();
645             if ($clicked_menu.is('.oe_menu_toggler')) {
646                 $clicked_menu.toggleClass('oe_menu_opened').siblings('.oe_secondary_submenu:first').toggle();
647             } else {
648                 $clicked_menu.parent().addClass('oe_active');
649             }
650         }
651     },
652     /**
653      * Call open_menu with the first menu_item matching an action_id
654      *
655      * @param {Number} id the action_id to match
656      */
657     open_action: function (id) {
658         var $menu = this.$element.add(this.$secondary_menus).find('a[data-action-id=' + id + ']');
659         var menu_id = $menu.data('menu');
660         if (menu_id) {
661             this.open_menu(menu_id);
662         }
663     },
664     /**
665      * Process a click on a menu item
666      *
667      * @param {Number} id the menu_id
668      */
669     menu_click: function(id) {
670         if (id) {
671             // find back the menuitem in dom to get the action
672             var $item = this.$element.find('a[data-menu=' + id + ']');
673             if (!$item.length) {
674                 $item = this.$secondary_menus.find('a[data-menu=' + id + ']');
675             }
676             var action_id = $item.data('action-id');
677             // If first level menu doesnt have action trigger first leaf
678             if (!action_id) {
679                 if(this.$element.has($item).length) {
680                     $sub_menu = this.$secondary_menus.find('.oe_secondary_menu[data-menu-parent=' + id + ']');
681                     $items = $sub_menu.find('a[data-action-id]').filter('[data-action-id!=""]');
682                     if($items.length) {
683                         action_id = $items.data('action-id');
684                         id = $items.data('menu');
685                     }
686                 }
687             }
688             this.open_menu(id);
689             this.current_menu = id;
690             this.session.active_id = id;
691             if (action_id) {
692                 this.trigger('menu_click', action_id, id, $item);
693             }
694         }
695     },
696     /**
697      * Jquery event handler for menu click
698      *
699      * @param {Event} ev the jquery event
700      */
701     on_menu_click: function(ev) {
702         ev.preventDefault();
703         this.menu_click($(ev.currentTarget).data('menu'));
704     },
705 });
706
707 instance.web.UserMenu =  instance.web.Widget.extend({
708     template: "UserMenu",
709     init: function(parent) {
710         this._super(parent);
711         this.update_promise = $.Deferred().resolve();
712     },
713     start: function() {
714         var self = this;
715         this._super.apply(this, arguments);
716         this.$element.on('click', '.oe_dropdown_menu li a[data-menu]', function(ev) {
717             ev.preventDefault();
718             var f = self['on_menu_' + $(this).data('menu')];
719             if (f) {
720                 f($(this));
721             }
722         });
723     },
724     change_password :function() {
725         var self = this;
726         this.dialog = new instance.web.Dialog(this, {
727             title: _t("Change Password"),
728             width : 'auto'
729         }).open();
730         this.dialog.$element.html(QWeb.render("UserMenu.password", self));
731         this.dialog.$element.find("form[name=change_password_form]").validate({
732             submitHandler: function (form) {
733                 self.rpc("/web/session/change_password",{
734                     'fields': $(form).serializeArray()
735                 }, function(result) {
736                     if (result.error) {
737                         self.display_error(result);
738                         return;
739                     } else {
740                         instance.webclient.on_logout();
741                     }
742                 });
743             }
744         });
745     },
746     display_error: function (error) {
747         return instance.web.dialog($('<div>'), {
748             modal: true,
749             title: error.title,
750             buttons: [
751                 {text: _("Ok"), click: function() { $(this).dialog("close"); }}
752             ]
753         }).html(error.error);
754     },
755     do_update: function () {
756         var self = this;
757         var fct = function() {
758             var $avatar = self.$element.find('.oe_topbar_avatar');
759             $avatar.attr('src', $avatar.data('default-src'));
760             if (!self.session.uid)
761                 return;
762             var func = new instance.web.Model("res.users").get_func("read");
763             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
764                 var topbar_name = res.name;
765                 if(instance.connection.debug)
766                     topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.connection.db);
767                 if(res.company_id[0] > 1)
768                     topbar_name = _.str.sprintf("%s (%s)", topbar_name, res.company_id[1]);
769                 self.$element.find('.oe_topbar_name').text(topbar_name);
770                 var avatar_src = _.str.sprintf('%s/web/binary/image?session_id=%s&model=res.users&field=avatar&id=%s', self.session.prefix, self.session.session_id, self.session.uid);
771                 $avatar.attr('src', avatar_src);
772             });
773         };
774         this.update_promise = this.update_promise.pipe(fct, fct);
775     },
776     on_action: function() {
777     },
778     on_menu_logout: function() {
779     },
780     on_menu_settings: function() {
781         var self = this;
782         var action_manager = new instance.web.ActionManager(this);
783         var dataset = new instance.web.DataSet (this,'res.users',this.context);
784         dataset.call ('action_get','',function (result){
785             self.rpc('/web/action/load', {action_id:result}, function(result){
786                 action_manager.do_action(_.extend(result['result'], {
787                     target: 'inline',
788                     res_id: self.session.uid,
789                     res_model: 'res.users',
790                     flags: {
791                         action_buttons: false,
792                         search_view: false,
793                         sidebar: false,
794                         views_switcher: false,
795                         pager: false
796                     }
797                 }));
798             });
799         });
800         this.dialog = new instance.web.Dialog(this,{
801             title: _t("Preferences"),
802             width: '700px',
803             buttons: [
804                 {text: _t("Change password"), click: function(){ self.change_password(); }},
805                 {text: _t("Cancel"), click: function(){ $(this).dialog('destroy'); }},
806                 {text: _t("Save"), click: function(){
807                         var inner_viewmanager = action_manager.inner_viewmanager;
808                         inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
809                         .then(function() {
810                             self.dialog.destroy();
811                             // needs to refresh interface in case language changed
812                             window.location.reload();
813                         });
814                     }
815                 }
816             ]
817         }).open();
818        action_manager.appendTo(this.dialog.$element);
819        action_manager.renderElement(this.dialog);
820     },
821     on_menu_about: function() {
822         var self = this;
823         self.rpc("/web/webclient/version_info", {}).then(function(res) {
824             var $help = $(QWeb.render("UserMenu.about", {version_info: res}));
825             $help.find('a.oe_activate_debug_mode').click(function (e) {
826                 e.preventDefault();
827                 window.location = $.param.querystring(
828                         window.location.href, 'debug');
829             });
830             instance.web.dialog($help, {autoOpen: true,
831                 modal: true, width: 960, title: _t("About")});
832         });
833     },
834 });
835
836 instance.web.WebClient = instance.web.Widget.extend({
837     init: function(parent) {
838         var self = this;
839         this._super(parent);
840         instance.webclient = this;
841         this.querystring = '?' + jQuery.param.querystring();
842         this._current_state = null;
843     },
844     _get_version_label: function() {
845         if (this.session.openerp_entreprise) {
846             return 'OpenERP';
847         } else {
848             return _t("OpenERP - Unsupported/Community Version");
849         }
850     },
851     set_title: function(title) {
852         title = _.str.clean(title);
853         var sep = _.isEmpty(title) ? '' : ' - ';
854         document.title = title + sep + 'OpenERP';
855     },
856     start: function() {
857         var self = this;
858         this.$element.addClass("openerp openerp_webclient_container");
859         if (jQuery.param !== undefined && jQuery.deparam(jQuery.param.querystring()).kitten !== undefined) {
860             $("body").addClass("kitten-mode-activated");
861             if ($.blockUI) {
862                 $.blockUI.defaults.message = '<img src="http://www.amigrave.com/kitten.gif">';
863             }
864         }
865         this.session.session_bind().then(function() {
866             self.destroy_content();
867             self.show_common();
868             if (!self.session.session_is_valid()) {
869                 self.show_login();
870             } else {
871                 self.show_application();
872             }
873         });
874         this.$element.on('mouseenter', '.oe_systray > div:not([data-tipsy=true])', function() {
875             $(this).attr('data-tipsy', 'true').tipsy().trigger('mouseenter');
876         });
877         this.$element.on('click', '.oe_dropdown_toggle', function(ev) {
878             ev.preventDefault();
879             var $menu = $(this).find('.oe_dropdown_menu');
880             var state = $menu.is('.oe_opened');
881             setTimeout(function() {
882                 // Do not alter propagation
883                 $menu.toggleClass('oe_opened', !state);
884                 if (!state) {
885                     // Move $menu if outside window's edge
886                     var doc_width = $(document).width();
887                     var offset = $menu.offset();
888                     var menu_width = $menu.width();
889                     var x = doc_width - offset.left - menu_width - 15;
890                     if (x < 0) {
891                         $menu.offset({ left: offset.left + x }).width(menu_width);
892                     }
893                 }
894             }, 0);
895         });
896         instance.web.bus.on('click', this, function() {
897             self.$element.find('.oe_dropdown_menu.oe_opened').removeClass('oe_opened');
898         });
899     },
900     show_common: function() {
901         var self = this;
902         this.crashmanager =  new instance.web.CrashManager();
903         instance.connection.on_rpc_error.add(this.crashmanager.on_rpc_error);
904         window.onerror = function (message, file, line) {
905             self.crashmanager.on_traceback({
906                 type: _t("Client Error"),
907                 message: message,
908                 data: {debug: file + ':' + line}
909             });
910         };
911         self.notification = new instance.web.Notification(this);
912         self.notification.appendTo(self.$element);
913         self.loading = new instance.web.Loading(self);
914         self.loading.appendTo(self.$element);
915         self.login = new instance.web.Login(self);
916         self.login.on("login",self,self.show_application);
917         self.$table = $(QWeb.render("WebClient", {}));
918         self.action_manager = new instance.web.ActionManager(self);
919         self.action_manager.appendTo(self.$table.find('.oe_application'));
920     },
921     show_login: function() {
922         var self = this;
923         self.login.appendTo(self.$element);
924     },
925     show_application: function() {
926         var self = this;
927         self.$element.append(self.$table);
928         self.login.$element.hide();
929         self.menu = new instance.web.Menu(self);
930         self.menu.replace(this.$element.find('.oe_menu_placeholder'));
931         self.menu.on('menu_click', this, this.on_menu_action);
932         self.user_menu = new instance.web.UserMenu(self);
933         self.user_menu.replace(this.$element.find('.oe_user_menu_placeholder'));
934         self.user_menu.on_menu_logout.add(this.proxy('on_logout'));
935         self.user_menu.on_action.add(this.proxy('on_menu_action'));
936         self.user_menu.do_update();
937         self.bind_hashchange();
938         if (!self.session.openerp_entreprise) {
939             var version_label = self._get_version_label();
940             self.$element.find('.oe_footer_powered').append(_.str.sprintf('<span> - <a href="http://www.openerp.com/support-or-publisher-warranty-contract" target="_blank">%s</a></span>', version_label));
941         }
942         self.set_title();
943     },
944     destroy_content: function() {
945         _.each(_.clone(this.getChildren()), function(el) {
946             el.destroy();
947         });
948         this.$element.children().remove();
949     },
950     do_reload: function() {
951         var self = this;
952         return this.session.session_reload().pipe(function () {
953             instance.connection.load_modules(true).pipe(
954                 self.menu.proxy('do_reload')); });
955
956     },
957     do_notify: function() {
958         var n = this.notification;
959         n.notify.apply(n, arguments);
960     },
961     do_warn: function() {
962         var n = this.notification;
963         n.warn.apply(n, arguments);
964     },
965     on_logout: function() {
966         var self = this;
967         this.session.session_logout().then(function () {
968             $(window).unbind('hashchange', self.on_hashchange);
969             self.do_push_state({});
970             //would be cool to be able to do this, but I think it will make addons do strange things
971             //this.show_login();
972             window.location.reload();
973         });
974     },
975     bind_hashchange: function() {
976         var self = this;
977         $(window).bind('hashchange', this.on_hashchange);
978
979         var state = $.bbq.getState(true);
980         if (! _.isEmpty(state)) {
981             $(window).trigger('hashchange');
982         } else {
983             self.menu.has_been_loaded.then(function() {
984                 var first_menu_id = self.menu.$element.find("a:first").data("menu");
985                 if(first_menu_id) {
986                     self.menu.menu_click(first_menu_id);
987                 }
988             });
989         }
990     },
991     on_hashchange: function(event) {
992         var self = this;
993         var state = event.getState(true);
994         if (!_.isEqual(this._current_state, state)) {
995             if(state.action_id === undefined && state.menu_id) {
996                 self.menu.has_been_loaded.then(function() {
997                     self.menu.do_reload().then(function() {
998                         self.menu.menu_click(state.menu_id)
999                     });
1000                 });
1001             } else {
1002                 this.action_manager.do_load_state(state, !!this._current_state);
1003             }
1004         }
1005         this._current_state = state;
1006     },
1007     do_push_state: function(state) {
1008         this.set_title(state.title);
1009         var url = '#' + $.param(state);
1010         this._current_state = _.clone(state);
1011         $.bbq.pushState(url);
1012     },
1013     on_menu_action: function(action) {
1014         this.action_manager.do_action(action);
1015     },
1016     do_action: function(action) {
1017         var self = this;
1018         // TODO replace by client action menuclick
1019         if(action.menu_id) {
1020             this.do_reload().then(function () {
1021                 self.menu.menu_click(action.menu_id);
1022             });
1023         }
1024     },
1025     set_content_full_screen: function(fullscreen) {
1026         if (fullscreen)
1027             $(".oe_webclient", this.$element).addClass("oe_content_full_screen");
1028         else
1029             $(".oe_webclient", this.$element).removeClass("oe_content_full_screen");
1030     }
1031 });
1032
1033 instance.web.EmbeddedClient = instance.web.Widget.extend({
1034     template: 'EmptyComponent',
1035     init: function(parent, action_id, options) {
1036         this._super(parent);
1037         // TODO take the xmlid of a action instead of its id
1038         this.action_id = action_id;
1039         this.options = options || {};
1040         this.am = new instance.web.ActionManager(this);
1041     },
1042     start: function() {
1043         var self = this;
1044         this.am.appendTo(this.$element.addClass('openerp'));
1045         return this.rpc("/web/action/load", { action_id: this.action_id }, function(result) {
1046             var action = result.result;
1047             action.flags = _.extend({
1048                 //views_switcher : false,
1049                 search_view : false,
1050                 action_buttons : false,
1051                 sidebar : false
1052                 //pager : false
1053             }, self.options, action.flags || {});
1054
1055             self.am.do_action(action);
1056         });
1057     }
1058 });
1059
1060 instance.web.embed = function (origin, dbname, login, key, action, options) {
1061     $('head').append($('<link>', {
1062         'rel': 'stylesheet',
1063         'type': 'text/css',
1064         'href': origin +'/web/webclient/css'
1065     }));
1066     var currentScript = document.currentScript;
1067     if (!currentScript) {
1068         var sc = document.getElementsByTagName('script');
1069         currentScript = sc[sc.length-1];
1070     }
1071     instance.connection.session_bind(origin).then(function () {
1072         instance.connection.session_authenticate(dbname, login, key, true).then(function () {
1073             var client = new instance.web.EmbeddedClient(null, action, options);
1074             client.insertAfter(currentScript);
1075         });
1076     });
1077
1078 };
1079
1080 };
1081
1082 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: