[IMP] change cursor when loading
[odoo/odoo.git] / addons / web / static / src / js / chrome.js
1 /*---------------------------------------------------------
2  * OpenERP Web chrome
3  *---------------------------------------------------------*/
4 openerp.web.chrome = function(openerp) {
5 var QWeb = openerp.web.qweb;
6
7 openerp.web.Notification =  openerp.web.Widget.extend(/** @lends openerp.web.Notification# */{
8     template: 'Notification',
9     identifier_prefix: 'notification-',
10
11     init: function() {
12         this._super.apply(this, arguments);
13         openerp.notification = this;
14     },
15
16     start: function() {
17         this._super.apply(this, arguments);
18         this.$element.notify({
19             speed: 500,
20             expires: 1500
21         });
22     },
23     notify: function(title, text) {
24         this.$element.notify('create', {
25             title: title,
26             text: text
27         });
28     },
29     warn: function(title, text) {
30         this.$element.notify('create', 'oe_notification_alert', {
31             title: title,
32             text: text,
33         }, {
34             expires: false,
35         });
36     },
37
38 });
39
40 openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
41     dialog_title: "",
42     identifier_prefix: 'dialog',
43     /**
44      * @constructs openerp.web.Dialog
45      * @extends openerp.web.OldWidget
46      *
47      * @param parent
48      * @param dialog_options
49      */
50     init: function (parent, dialog_options) {
51         var self = this;
52         this._super(parent);
53         this.dialog_options = {
54             modal: true,
55             width: 'auto',
56             min_width: 0,
57             max_width: '100%',
58             height: 'auto',
59             min_height: 0,
60             max_height: '100%',
61             autoOpen: false,
62             buttons: {},
63             beforeClose: function () { self.on_close(); }
64         };
65         for (var f in this) {
66             if (f.substr(0, 10) == 'on_button_') {
67                 this.dialog_options.buttons[f.substr(10)] = this[f];
68             }
69         }
70         if (dialog_options) {
71             this.set_options(dialog_options);
72         }
73     },
74     set_options: function(options) {
75         options = options || {};
76         options.width = this.get_width(options.width || this.dialog_options.width);
77         options.min_width = this.get_width(options.min_width || this.dialog_options.min_width);
78         options.max_width = this.get_width(options.max_width || this.dialog_options.max_width);
79         options.height = this.get_height(options.height || this.dialog_options.height);
80         options.min_height = this.get_height(options.min_height || this.dialog_options.min_height);
81         options.max_height = this.get_height(options.max_height || this.dialog_options.max_width);
82
83         if (options.width !== 'auto') {
84             if (options.width > options.max_width) options.width = options.max_width;
85             if (options.width < options.min_width) options.width = options.min_width;
86         }
87         if (options.height !== 'auto') {
88             if (options.height > options.max_height) options.height = options.max_height;
89             if (options.height < options.min_height) options.height = options.min_height;
90         }
91         if (!options.title && this.dialog_title) {
92             options.title = this.dialog_title;
93         }
94         _.extend(this.dialog_options, options);
95     },
96     get_width: function(val) {
97         return this.get_size(val.toString(), $(window.top).width());
98     },
99     get_height: function(val) {
100         return this.get_size(val.toString(), $(window.top).height());
101     },
102     get_size: function(val, available_size) {
103         if (val === 'auto') {
104             return val;
105         } else if (val.slice(-1) == "%") {
106             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
107         } else {
108             return parseInt(val, 10);
109         }
110     },
111     start: function () {
112         this.$dialog = $('<div id="' + this.element_id + '"></div>').dialog(this.dialog_options);
113         this._super();
114         return this;
115     },
116     open: function(dialog_options) {
117         // TODO fme: bind window on resize
118         if (this.template) {
119             this.$element.html(this.render());
120         }
121         this.set_options(dialog_options);
122         this.$dialog.dialog(this.dialog_options).dialog('open');
123         return this;
124     },
125     close: function() {
126         // Closes the dialog but leave it in a state where it could be opened again.
127         this.$dialog.dialog('close');
128     },
129     on_close: function() {
130     },
131     stop: function () {
132         // Destroy widget
133         this.close();
134         this.$dialog.dialog('destroy');
135         this._super();
136     }
137 });
138
139 openerp.web.CrashManager = openerp.web.SessionAware.extend({
140     init: function(parent) {
141         this._super((parent || {}).session);
142         this.session.on_rpc_error.add(this.on_rpc_error);
143     },
144     on_rpc_error: function(error) {
145         this.error = error;
146         if (error.data.fault_code) {
147             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
148             if (split.length > 1) {
149                 error.type = split.shift();
150                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
151             }
152         }
153         if (error.code === 200 && error.type) {
154             this.on_managed_error(error);
155         } else {
156             this.on_traceback(error);
157         }
158     },
159     on_managed_error: function(error) {
160         $('<div>' + QWeb.render('DialogWarning', {error: error}) + '</div>').dialog({
161             title: "OpenERP " + _.capitalize(error.type),
162             buttons: {
163                 Ok: function() {
164                     $(this).dialog("close");
165                 }
166             }
167         });
168     },
169     on_traceback: function(error) {
170         var dialog = new openerp.web.Dialog(this, {
171             title: "OpenERP " + _.capitalize(error.type),
172             autoOpen: true,
173             width: '90%',
174             height: '90%',
175             min_width: '800px',
176             min_height: '600px',
177             buttons: {
178                 Ok: function() {
179                     $(this).dialog("close");
180                 }
181             }
182         }).start();
183         dialog.$element.html(QWeb.render('DialogTraceback', {error: error}));
184     }
185 });
186
187 openerp.web.Loading =  openerp.web.Widget.extend(/** @lends openerp.web.Loading# */{
188     /**
189      * @constructs openerp.web.Loading
190      * @extends openerp.web.Widget
191      *
192      * @param parent
193      * @param element_id
194      */
195     init: function(parent, element_id) {
196         this._super(parent, element_id);
197         this.count = 0;
198         this.session.on_rpc_request.add_first(this.on_rpc_event, 1);
199         this.session.on_rpc_response.add_last(this.on_rpc_event, -1);
200     },
201     on_rpc_event : function(increment) {
202         this.count += increment;
203         if (this.count) {
204             //this.$element.html(QWeb.render("Loading", {}));
205             this.$element.html("Loading ("+this.count+")");
206             this.$element.show();
207             this.widget_parent.$element.addClass('loading');
208         } else {
209             this.$element.fadeOut();
210             this.widget_parent.$element.removeClass('loading');
211         }
212     }
213 });
214
215 openerp.web.Database = openerp.web.Widget.extend(/** @lends openerp.web.Database# */{
216     /**
217      * @constructs openerp.web.Database
218      * @extends openerp.web.Widget
219      *
220      * @param parent
221      * @param element_id
222      * @param option_id
223      */
224     init: function(parent, element_id, option_id) {
225         this._super(parent, element_id);
226         this.$option_id = $('#' + option_id);
227     },
228     start: function() {
229         this.$element.html(QWeb.render("Database", this));
230         this.$element.closest(".openerp")
231                 .removeClass("login-mode")
232                 .addClass("database_block");
233
234         var self = this;
235         var fetch_db = this.rpc("/web/database/get_list", {}, function(result) {
236             self.db_list = result.db_list;
237         });
238         var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
239             if (result.error) {
240                 self.display_error(result);
241                 return;
242             }
243             self.lang_list = result.lang_list;
244         });
245         $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
246
247         this.$element.find('#db-create').click(this.do_create);
248         this.$element.find('#db-drop').click(this.do_drop);
249         this.$element.find('#db-backup').click(this.do_backup);
250         this.$element.find('#db-restore').click(this.do_restore);
251         this.$element.find('#db-change-password').click(this.do_change_password);
252         this.$element.find('#back-to-login').click(function() {
253             self.stop();
254         });
255     },
256     stop: function () {
257         this.$option_id.empty();
258
259         this.$element
260             .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
261                 .unbind('click')
262             .end()
263             .closest(".openerp")
264                 .addClass("login-mode")
265                 .removeClass("database_block")
266             .end()
267             .empty();
268         this._super();
269     },
270     /**
271      * Converts a .serializeArray() result into a dict. Does not bother folding
272      * multiple identical keys into an array, last key wins.
273      *
274      * @param {Array} array
275      */
276     to_object: function (array) {
277         var result = {};
278         _(array).each(function (record) {
279             result[record.name] = record.value;
280         });
281         return result;
282     },
283     /**
284      * Waits until the new database is done creating, then unblocks the UI and
285      * logs the user in as admin
286      *
287      * @param {Number} db_creation_id identifier for the db-creation operation, used to fetch the current installation progress
288      * @param {Object} info info fields for this database creation
289      * @param {String} info.db name of the database being created
290      * @param {String} info.password super-admin password for the database
291      */
292     wait_for_newdb: function (db_creation_id, info) {
293         var self = this;
294         self.rpc('/web/database/progress', {
295             id: db_creation_id,
296             password: info.password
297         }, function (result) {
298             var progress = result[0];
299             // I'd display a progress bar, but turns out the progress status
300             // the server report kind-of blows goats: it's at 0 for ~75% of
301             // the installation, then jumps to 75%, then jumps down to either
302             // 0 or ~40%, then back up to 75%, then terminates. Let's keep that
303             // mess hidden behind a not-very-useful but not overly weird
304             // message instead.
305             if (progress < 1) {
306                 setTimeout(function () {
307                     self.wait_for_newdb(db_creation_id, info);
308                 }, 500);
309                 return;
310             }
311
312             var admin = result[1][0];
313             setTimeout(function () {
314                 self.widget_parent.do_login(
315                         info.db, admin.login, admin.password);
316                 self.stop();
317                 $.unblockUI();
318             });
319         });
320     },
321     /**
322      * Displays an error dialog resulting from the various RPC communications
323      * failing over themselves
324      *
325      * @param {Object} error error description
326      * @param {String} error.title title of the error dialog
327      * @param {String} error.error message of the error dialog
328      */
329     display_error: function (error) {
330         return $('<div>').dialog({
331             modal: true,
332             title: error.title,
333             buttons: {
334                 Ok: function() {
335                     $(this).dialog("close");
336                 }
337             }
338         }).html(error.error);
339     },
340     do_create: function() {
341         var self = this;
342         self.$option_id.html(QWeb.render("Database.CreateDB", self));
343         self.$option_id.find("form[name=create_db_form]").validate({
344             submitHandler: function (form) {
345                 var fields = $(form).serializeArray();
346                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
347                 self.rpc("/web/database/create", {'fields': fields}, function(result) {
348                     if (result.error) {
349                         $.unblockUI();
350                         self.display_error(result);
351                         return;
352                     }
353                     self.db_list.push(self.to_object(fields)['db_name']);
354                     self.db_list.sort();
355                     var form_obj = self.to_object(fields);
356                     self.wait_for_newdb(result, {
357                         password: form_obj['super_admin_pwd'],
358                         db: form_obj['db_name']
359                     });
360                 });
361             }
362         });
363     },
364     do_drop: function() {
365         var self = this;
366         self.$option_id.html(QWeb.render("DropDB", self));
367         self.$option_id.find("form[name=drop_db_form]").validate({
368             submitHandler: function (form) {
369                 var $form = $(form),
370                     fields = $form.serializeArray(),
371                     $db_list = $form.find('select[name=drop_db]'),
372                     db = $db_list.val();
373
374                 if (!confirm("Do you really want to delete the database: " + db + " ?")) {
375                     return;
376                 }
377                 self.rpc("/web/database/drop", {'fields': fields}, function(result) {
378                     if (result.error) {
379                         self.display_error(result);
380                         return;
381                     }
382                     $db_list.find(':selected').remove();
383                     self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
384                     self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
385                 });
386             }
387         });
388     },
389     do_backup: function() {
390         var self = this;
391         self.$option_id
392             .html(QWeb.render("BackupDB", self))
393             .find("form[name=backup_db_form]").validate({
394             submitHandler: function (form) {
395                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
396                 self.session.get_file({
397                     form: form,
398                     error: function (body) {
399                         var error = body.firstChild.data.split('|');
400                         self.display_error({
401                             title: error[0],
402                             error: error[1]
403                         });
404                     },
405                     complete: $.unblockUI
406                 });
407             }
408         });
409     },
410     do_restore: function() {
411         var self = this;
412         self.$option_id.html(QWeb.render("RestoreDB", self));
413
414         self.$option_id.find("form[name=restore_db_form]").validate({
415             submitHandler: function (form) {
416                 $.blockUI({message:'<img src="/web/static/src/img/throbber2.gif">'});
417                 $(form).ajaxSubmit({
418                     url: '/web/database/restore',
419                     type: 'POST',
420                     resetForm: true,
421                     success: function (body) {
422                         // TODO: ui manipulations
423                         // note: response objects don't work, but we have the
424                         // HTTP body of the response~~
425
426                         // If empty body, everything went fine
427                         if (!body) { return; }
428
429                         if (body.indexOf('403 Forbidden') !== -1) {
430                             self.display_error({
431                                 title: 'Access Denied',
432                                 error: 'Incorrect super-administrator password'
433                             })
434                         } else {
435                             self.display_error({
436                                 title: 'Restore Database',
437                                 error: 'Could not restore the database'
438                             })
439                         }
440                     },
441                     complete: function () {
442                         $.unblockUI();
443                     }
444                 });
445             }
446         });
447     },
448     do_change_password: function() {
449         var self = this;
450         self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
451
452         self.$option_id.find("form[name=change_pwd_form]").validate({
453             messages: {
454                 old_pwd: "Please enter your previous password",
455                 new_pwd: "Please enter your new password",
456                 confirm_pwd: {
457                     required: "Please confirm your new password",
458                     equalTo: "The confirmation does not match the password"
459                 }
460             },
461             submitHandler: function (form) {
462                 self.rpc("/web/database/change_password", {
463                     'fields': $(form).serializeArray()
464                 }, function(result) {
465                     if (result.error) {
466                         self.display_error(result);
467                         return;
468                     }
469                     self.do_notify("Changed Password", "Password has been changed successfully");
470                 });
471             }
472         });
473     }
474 });
475
476 openerp.web.Login =  openerp.web.Widget.extend(/** @lends openerp.web.Login# */{
477     remember_credentials: true,
478     
479     template: "Login",
480     identifier_prefix: 'oe-app-login-',
481     /**
482      * @constructs openerp.web.Login
483      * @extends openerp.web.Widget
484      *
485      * @param parent
486      * @param element_id
487      */
488
489     init: function(parent) {
490         this._super(parent);
491         this.has_local_storage = typeof(localStorage) != 'undefined';
492         this.selected_db = null;
493         this.selected_login = null;
494
495         if (this.has_local_storage && this.remember_credentials) {
496             this.selected_db = localStorage.getItem('last_db_login_success');
497             this.selected_login = localStorage.getItem('last_login_login_success');
498             if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
499                 this.selected_password = localStorage.getItem('last_password_login_success');
500             }
501         }
502         
503         var qs = jQuery.deparam(jQuery.param.querystring());
504         if (qs.db) {
505             this.selected_db = qs.db;
506         }
507         if (qs.login) {
508             this.selected_login = qs.login;
509         }
510
511     },
512     start: function() {
513         var self = this;
514         this.database = new openerp.web.Database(
515                 this, "oe_database", "oe_db_options");
516
517         this.$element.find('#oe-db-config').click(function() {
518             self.database.start();
519         });
520
521         this.$element.find("form").submit(this.on_submit);
522
523         this.rpc("/web/database/get_list", {}, function(result) {
524             var tpl = openerp.web.qweb.render('Login_dblist', {db_list: result.db_list, selected_db: self.selected_db});
525             self.$element.find("input[name=db]").replaceWith(tpl)
526         }, 
527         function(error, event) {
528             if (error.data.fault_code === 'AccessDenied') {
529                 event.preventDefault();
530             }
531         });
532
533     },
534     on_login_invalid: function() {
535         this.$element.closest(".openerp").addClass("login-mode");
536     },
537     on_login_valid: function() {
538         this.$element.closest(".openerp").removeClass("login-mode");
539     },
540     on_submit: function(ev) {
541         ev.preventDefault();
542         var $e = this.$element;
543         var db = $e.find("form [name=db]").val();
544         var login = $e.find("form input[name=login]").val();
545         var password = $e.find("form input[name=password]").val();
546
547         this.do_login(db, login, password);
548     },
549     /**
550      * Performs actual login operation, and UI-related stuff
551      *
552      * @param {String} db database to log in
553      * @param {String} login user login
554      * @param {String} password user password
555      */
556     do_login: function (db, login, password) {
557         var self = this;
558         this.session.session_login(db, login, password, function() {
559             if(self.session.session_is_valid()) {
560                 if (self.has_local_storage) {
561                     if(self.remember_credentials) {
562                         localStorage.setItem('last_db_login_success', db);
563                         localStorage.setItem('last_login_login_success', login);
564                         if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
565                             localStorage.setItem('last_password_login_success', password);
566                         }
567                     } else {
568                         localStorage.setItem('last_db_login_success', '');
569                         localStorage.setItem('last_login_login_success', '');
570                         localStorage.setItem('last_password_login_success', '');
571                     }
572                 }
573                 self.on_login_valid();
574             } else {
575                 self.$element.addClass("login_invalid");
576                 self.on_login_invalid();
577             }
578         });
579     },
580     do_ask_login: function(continuation) {
581         this.on_login_invalid();
582         this.$element
583             .removeClass("login_invalid");
584         this.on_login_valid.add({
585             position: "last",
586             unique: true,
587             callback: continuation || function() {}
588         });
589     },
590     on_logout: function() {
591         this.session.logout();
592     }
593 });
594
595 openerp.web.Header =  openerp.web.Widget.extend(/** @lends openerp.web.Header# */{
596     template: "Header",
597     identifier_prefix: 'oe-app-header-',
598     /**
599      * @constructs openerp.web.Header
600      * @extends openerp.web.Widget
601      *
602      * @param parent
603      */
604     init: function(parent) {
605         this._super(parent);
606         this.qs = "?" + jQuery.param.querystring();
607         this.$content = $();
608         this.update_promise = $.Deferred().resolve();
609     },
610     start: function() {
611         this._super();
612     },
613     do_update: function () {
614         var self = this;
615         var fct = function() {
616             self.$content.remove();
617             if (!self.session.uid)
618                 return;
619             var func = new openerp.web.Model(self.session, "res.users").get_func("read");
620             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
621                 self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
622                 self.$content.appendTo(self.$element);
623                 self.$element.find(".logout").click(self.on_logout);
624                 self.$element.find("a.preferences").click(self.on_preferences);
625                 self.$element.find(".about").click(self.on_about);
626                 return self.shortcut_load();
627             });
628         };
629         this.update_promise = this.update_promise.pipe(fct, fct);
630     },
631     on_about: function() {
632         var self = this;
633         self.rpc("/web/webclient/version_info", {}).then(function(res) {
634             var $help = $(QWeb.render("About-Page", {version_info: res}));
635             $help.dialog({autoOpen: true,
636                 modal: true, width: 960, title: "About"});
637         });
638     },
639     shortcut_load :function(){
640         var self = this,
641             sc = self.session.shortcuts,
642             shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
643         // TODO: better way to communicate between sections.
644         // sc.bindings, because jquery does not bind/trigger on arrays...
645         if (!sc.binding) {
646             sc.binding = {};
647             $(sc.binding).bind({
648                 'add': function (e, attrs) {
649                     shortcuts_ds.create(attrs, function (out) {
650                         $('<li>', {
651                             'data-shortcut-id':out.result,
652                             'data-id': attrs.res_id
653                         }).text(attrs.name)
654                           .appendTo(self.$element.find('.oe-shortcuts ul'));
655                         attrs.id = out.result;
656                         sc.push(attrs);
657                     });
658                 },
659                 'remove-current': function () {
660                     var menu_id = self.session.active_id;
661                     var $shortcut = self.$element
662                         .find('.oe-shortcuts li[data-id=' + menu_id + ']');
663                     var shortcut_id = $shortcut.data('shortcut-id');
664                     $shortcut.remove();
665                     shortcuts_ds.unlink([shortcut_id]);
666                     var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
667                     sc.splice(0, sc.length);
668                     sc.push.apply(sc, sc_new);
669                     }
670             });
671         }
672         return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
673             sc.splice(0, sc.length);
674             sc.push.apply(sc, shortcuts);
675
676             self.$element.find('.oe-shortcuts')
677                 .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
678                 .undelegate('li', 'click')
679
680                 .delegate('li', 'click', function(e) {
681                     e.stopPropagation();
682                     var id = $(this).data('id');
683                     self.session.active_id = id;
684                     self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
685                         if (ir_menu_data.action.length){
686                             self.on_action(ir_menu_data.action[0][2]);
687                         }
688                     });
689                 });
690         });
691     },
692
693     on_action: function(action) {
694     },
695     on_preferences: function(){
696         var self = this;
697         var action_manager = new openerp.web.ActionManager(this);
698         var dataset = new openerp.web.DataSet (this,'res.users',this.context);
699         dataset.call ('action_get','',function (result){
700             self.rpc('/web/action/load', {action_id:result}, function(result){
701                 action_manager.do_action(_.extend(result['result'], {
702                     res_id: self.session.uid,
703                     res_model: 'res.users',
704                     flags: {
705                         action_buttons: false,
706                         search_view: false,
707                         sidebar: false,
708                         views_switcher: false,
709                         pager: false
710                     }
711                 }));
712             });
713         });
714         this.dialog = new openerp.web.Dialog(this,{
715             modal: true,
716             title: 'Preferences',
717             width: 600,
718             height: 500,
719             buttons: {
720                 "Change password": function(){
721                     self.change_password();
722             },
723                 Cancel: function(){
724                      $(this).dialog('destroy');
725             },
726                 Save: function(){
727                     var inner_viewmanager = action_manager.inner_viewmanager;
728                     inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
729                     .then(function() {
730                         self.dialog.stop();
731                         window.location.reload();
732                     });
733                 }
734             }
735         });
736        this.dialog.start().open();
737        action_manager.appendTo(this.dialog);
738        action_manager.render(this.dialog);
739     },
740
741     change_password :function() {
742         var self = this;
743         this.dialog = new openerp.web.Dialog(this,{
744             modal : true,
745             title : 'Change Password',
746             width : 'auto',
747             height : 'auto'
748         });
749         this.dialog.start().open();
750         this.dialog.$element.html(QWeb.render("Change_Pwd", self));
751         this.dialog.$element.find("form[name=change_password_form]").validate({
752             submitHandler: function (form) {
753                 self.rpc("/web/session/change_password",{
754                     'fields': $(form).serializeArray()
755                 }, function(result) {
756                     if (result.error) {
757                         self.display_error(result);
758                         return;
759                     } else {
760                         self.session.logout();
761                     }
762                 });
763             }
764         });
765     },
766     display_error: function (error) {
767         return $('<div>').dialog({
768             modal: true,
769             title: error.title,
770             buttons: {
771                 Ok: function() {
772                     $(this).dialog("close");
773                 }
774             }
775         }).html(error.error);
776     },
777     on_logout: function() {
778     }
779 });
780
781 openerp.web.Menu =  openerp.web.Widget.extend(/** @lends openerp.web.Menu# */{
782     /**
783      * @constructs openerp.web.Menu
784      * @extends openerp.web.Widget
785      *
786      * @param parent
787      * @param element_id
788      * @param secondary_menu_id
789      */
790     init: function(parent, element_id, secondary_menu_id) {
791         this._super(parent, element_id);
792         this.secondary_menu_id = secondary_menu_id;
793         this.$secondary_menu = $("#" + secondary_menu_id).hide();
794         this.menu = false;
795         this.folded = false;
796         if (window.localStorage) {
797             this.folded = localStorage.getItem('oe_menu_folded') === 'true';
798         }
799         this.float_timeout = 700;
800     },
801     start: function() {
802         this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
803     },
804     do_reload: function() {
805         this.rpc("/web/menu/load", {}, this.on_loaded);
806     },
807     on_loaded: function(data) {
808         this.data = data;
809         this.$element.html(QWeb.render("Menu", { widget : this }));
810         this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
811         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
812         this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
813     },
814     on_toggle_fold: function() {
815         this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
816         if (this.folded) {
817             this.$secondary_menu.find('.oe_secondary_menu.active').show();
818         } else {
819             this.$secondary_menu.find('.oe_secondary_menu').hide();
820         }
821         this.folded = !this.folded;
822         if (window.localStorage) {
823             localStorage.setItem('oe_menu_folded', this.folded.toString());
824         }
825     },
826     on_menu_click: function(ev, id) {
827         id = id || 0;
828         var $clicked_menu, manual = false;
829
830         if (id) {
831             // We can manually activate a menu with it's id (for hash url mapping)
832             manual = true;
833             $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
834             if (!$clicked_menu.length) {
835                 $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
836             }
837         } else {
838             $clicked_menu = $(ev.currentTarget);
839             id = $clicked_menu.data('menu');
840         }
841
842         if (this.do_menu_click($clicked_menu, manual) && id) {
843             this.session.active_id = id;
844             this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
845         }
846         if (ev) {
847             ev.stopPropagation();
848         }
849         return false;
850     },
851     do_menu_click: function($clicked_menu, manual) {
852         var $sub_menu, $main_menu,
853             active = $clicked_menu.is('.active'),
854             sub_menu_visible = false;
855
856         if (this.$secondary_menu.has($clicked_menu).length) {
857             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
858             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
859         } else {
860             $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
861             $main_menu = $clicked_menu;
862         }
863
864         sub_menu_visible = $sub_menu.is(':visible');
865         this.$secondary_menu.find('.oe_secondary_menu').hide();
866
867         $('.active', this.$element.add(this.$secondary_menu.show())).removeClass('active');
868         $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
869
870         if (!(this.folded && manual)) {
871             this.do_show_secondary($sub_menu, $main_menu);
872         }
873
874         if ($main_menu != $clicked_menu) {
875             if ($clicked_menu.is('.submenu')) {
876                 $sub_menu.find('.submenu.opened').each(function() {
877                     if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
878                         $(this).removeClass('opened').next().hide();
879                     }
880                 });
881                 $clicked_menu.toggleClass('opened').next().toggle();
882             } else if ($clicked_menu.is('.leaf')) {
883                 $sub_menu.toggle(!this.folded);
884                 return true;
885             }
886         } else if (this.folded) {
887             if (active && sub_menu_visible) {
888                 $sub_menu.hide();
889                 return true;
890             }
891             return manual;
892         } else {
893             return true;
894         }
895         return false;
896     },
897     do_show_secondary: function($sub_menu, $main_menu) {
898         var self = this;
899         if (this.folded) {
900             var css = $main_menu.position(),
901                 fold_width = this.$secondary_menu.width() + 2,
902                 window_width = $(window).width();
903             css.top += 33;
904             css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
905             css.left = css.left < fold_width ? fold_width : css.left;
906             if ((css.left + $sub_menu.width()) > window_width) {
907                 delete(css.left);
908                 css.right = 1;
909             }
910             $sub_menu.css(css);
911             $sub_menu.mouseenter(function() {
912                 clearTimeout($sub_menu.data('timeoutId'));
913             }).mouseleave(function(evt) {
914                 var timeoutId = setTimeout(function() {
915                     if (self.folded) {
916                         $sub_menu.hide();
917                     }
918                 }, self.float_timeout);
919                 $sub_menu.data('timeoutId', timeoutId);
920             });
921         }
922         $sub_menu.show();
923     },
924     on_menu_action_loaded: function(data) {
925         var self = this;
926         if (data.action.length) {
927             var action = data.action[0][2];
928             self.on_action(action);
929         }
930     },
931     on_action: function(action) {
932     }
933 });
934
935 openerp.web.WebClient = openerp.web.Widget.extend(/** @lends openerp.web.WebClient */{
936     /**
937      * @constructs openerp.web.WebClient
938      * @extends openerp.web.Widget
939      *
940      * @param element_id
941      */
942     init: function(element_id) {
943         this._super(null, element_id);
944         openerp.webclient = this;
945
946         QWeb.add_template("/web/static/src/xml/base.xml");
947         var params = {};
948         if(jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
949             this.$element.addClass("kitten-mode-activated");
950         }
951         this.$element.html(QWeb.render("Interface", params));
952
953         this.notification = new openerp.web.Notification();
954         this.session = new openerp.web.Session();
955         this.loading = new openerp.web.Loading(this,"oe_loading");
956         this.crashmanager =  new openerp.web.CrashManager(this);
957
958         this.header = new openerp.web.Header(this);
959         this.login = new openerp.web.Login(this);
960         this.header.on_logout.add(this.login.on_logout);
961         this.header.on_action.add(this.on_menu_action);
962
963         this.session.on_session_invalid.add(this.login.do_ask_login);
964         this.session.on_session_valid.add_last(this.header.do_update);
965         this.session.on_session_invalid.add_last(this.header.do_update);
966         this.session.on_session_valid.add_last(this.on_logged);
967
968         this.menu = new openerp.web.Menu(this, "oe_menu", "oe_secondary_menu");
969         this.menu.on_action.add(this.on_menu_action);
970
971         this.url_internal_hashchange = false;
972         this.url_external_hashchange = false;
973         jQuery(window).bind('hashchange', this.on_url_hashchange);
974
975     },
976     start: function() {
977         this._super.apply(this, arguments);
978         this.notification.prependTo(this.$element);
979         this.header.appendTo($("#oe_header"));
980         this.session.start();
981         this.login.appendTo($('#oe_login'));
982         this.menu.start();
983     },
984     do_reload: function() {
985         this.session.session_restore();
986         this.menu.do_reload();
987     },
988     do_notify: function() {
989         var n = this.notification;
990         n.notify.apply(n, arguments);
991     },
992     do_warn: function() {
993         var n = this.notification;
994         n.warn.apply(n, arguments);
995     },
996     on_logged: function() {
997         this.menu.do_reload();
998         if(this.action_manager)
999             this.action_manager.stop();
1000         this.action_manager = new openerp.web.ActionManager(this);
1001         this.action_manager.appendTo($("#oe_app"));
1002         this.action_manager.do_url_set_hash.add_last(this.do_url_set_hash);
1003
1004         // if using saved actions, load the action and give it to action manager
1005         var parameters = jQuery.deparam(jQuery.param.querystring());
1006         if (parameters["s_action"] != undefined) {
1007             var key = parseInt(parameters["s_action"], 10);
1008             var self = this;
1009             this.rpc("/web/session/get_session_action", {key:key}, function(action) {
1010                 self.action_manager.do_action(action);
1011             });
1012         } else if (openerp._modules_loaded) { // TODO: find better option than this
1013             this.load_url_state()
1014         } else {
1015             this.session.on_modules_loaded.add({
1016                 callback: $.proxy(this, 'load_url_state'),
1017                 unique: true,
1018                 position: 'last'
1019             })
1020         }
1021     },
1022     /**
1023      * Loads state from URL if any, or checks if there is a home action and
1024      * loads that, assuming we're at the index
1025      */
1026     load_url_state: function () {
1027         var self = this;
1028         // TODO: add actual loading if there is url state to unpack, test on window.location.hash
1029         // not logged in
1030         if (!this.session.uid) { return; }
1031         var ds = new openerp.web.DataSetSearch(this, 'res.users');
1032         ds.read_ids([this.session.uid], ['action_id'], function (users) {
1033             var home_action = users[0].action_id;
1034             if (!home_action) {
1035                 self.default_home();
1036                 return;
1037             }
1038             self.execute_home_action(home_action[0], ds);
1039         })
1040     },
1041     default_home: function () {
1042     },
1043     /**
1044      * Bundles the execution of the home action
1045      *
1046      * @param {Number} action action id
1047      * @param {openerp.web.DataSet} dataset action executor
1048      */
1049     execute_home_action: function (action, dataset) {
1050         var self = this;
1051         this.rpc('/web/action/load', {
1052             action_id: action,
1053             context: dataset.get_context()
1054         }, function (meh) {
1055             var action = meh.result;
1056             action.context = _.extend(action.context || {}, {
1057                 active_id: false,
1058                 active_ids: [false],
1059                 active_model: dataset.model
1060             });
1061             self.action_manager.do_action(action);
1062         });
1063     },
1064     do_url_set_hash: function(url) {
1065         if(!this.url_external_hashchange) {
1066             this.url_internal_hashchange = true;
1067             jQuery.bbq.pushState(url);
1068         }
1069     },
1070     on_url_hashchange: function() {
1071         if(this.url_internal_hashchange) {
1072             this.url_internal_hashchange = false;
1073         } else {
1074             var url = jQuery.deparam.fragment();
1075             this.url_external_hashchange = true;
1076             this.action_manager.on_url_hashchange(url);
1077             this.url_external_hashchange = false;
1078         }
1079     },
1080     on_menu_action: function(action) {
1081         this.action_manager.do_action(action);
1082     },
1083     do_about: function() {
1084     },
1085
1086 });
1087
1088 };
1089
1090 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: