[FIX] handling of being denied access to the list of databases in the database-manage...
[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     _t = openerp.web._t;
7
8 openerp.web.Notification =  openerp.web.OldWidget.extend(/** @lends openerp.web.Notification# */{
9     template: '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: 2500
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     }
35
36 });
37
38 openerp.web.Dialog = openerp.web.OldWidget.extend(/** @lends openerp.web.Dialog# */{
39     dialog_title: "",
40     /**
41      * @constructs openerp.web.Dialog
42      * @extends openerp.web.OldWidget
43      *
44      * @param parent
45      * @param options
46      */
47     init: function (parent, options, content) {
48         var self = this;
49         this._super(parent);
50         if (content) {
51             this.$element = content instanceof $ ? content : $(content);
52         }
53         this.dialog_options = {
54             modal: true,
55             destroy_on_close: true,
56             width: $(window).width() * (($(window).width() > 1024) ? 0.5 : 0.75),
57             min_width: 0,
58             max_width: '95%',
59             height: 'auto',
60             min_height: 0,
61             max_height: this.get_height('100%') - 140,
62             autoOpen: false,
63             position: [false, 50],
64             buttons: {},
65             beforeClose: function () { self.on_close(); },
66             resizeStop: this.on_resized
67         };
68         for (var f in this) {
69             if (f.substr(0, 10) == 'on_button_') {
70                 this.dialog_options.buttons[f.substr(10)] = this[f];
71             }
72         }
73         if (options) {
74             _.extend(this.dialog_options, options);
75         }
76         if (this.dialog_options.autoOpen) {
77             this.open();
78         } else {
79             this.$element.dialog(this.get_options());
80         }
81     },
82     get_options: function(options) {
83         var self = this,
84             o = _.extend({}, this.dialog_options, options || {});
85         _.each(['width', 'height'], function(unit) {
86             o[unit] = self['get_' + unit](o[unit]);
87             o['min_' + unit] = self['get_' + unit](o['min_' + unit] || 0);
88             o['max_' + unit] = self['get_' + unit](o['max_' + unit] || 0);
89             if (o[unit] !== 'auto' && o['min_' + unit] && o[unit] < o['min_' + unit]) o[unit] = o['min_' + unit];
90             if (o[unit] !== 'auto' && o['max_' + unit] && o[unit] > o['max_' + unit]) o[unit] = o['max_' + unit];
91         });
92         if (!o.title && this.dialog_title) {
93             o.title = this.dialog_title;
94         }
95         return o;
96     },
97     get_width: function(val) {
98         return this.get_size(val.toString(), $(window.top).width());
99     },
100     get_height: function(val) {
101         return this.get_size(val.toString(), $(window.top).height());
102     },
103     get_size: function(val, available_size) {
104         if (val === 'auto') {
105             return val;
106         } else if (val.slice(-1) == "%") {
107             return Math.round(available_size / 100 * parseInt(val.slice(0, -1), 10));
108         } else {
109             return parseInt(val, 10);
110         }
111     },
112     open: function(options) {
113         // TODO fme: bind window on resize
114         if (this.template) {
115             this.$element.html(this.render());
116         }
117         var o = this.get_options(options);
118         this.$element.dialog(o).dialog('open');
119         if (o.height === 'auto' && o.max_height) {
120             this.$element.css({ 'max-height': o.max_height, 'overflow-y': 'auto' });
121         }
122         return this;
123     },
124     close: function() {
125         this.$element.dialog('close');
126     },
127     on_close: function() {
128         if (this.dialog_options.destroy_on_close) {
129             this.$element.dialog('destroy');
130         }
131     },
132     on_resized: function() {
133         //openerp.log("Dialog resized to %d x %d", this.$element.width(), this.$element.height());
134     },
135     stop: function () {
136         // Destroy widget
137         this.close();
138         this.$element.dialog('destroy');
139         this._super();
140     }
141 });
142
143 openerp.web.CrashManager = openerp.web.CallbackEnabled.extend({
144     init: function() {
145         this._super();
146         openerp.connection.on_rpc_error.add(this.on_rpc_error);
147     },
148     on_rpc_error: function(error) {
149         this.error = error;
150         if (error.data.fault_code) {
151             var split = ("" + error.data.fault_code).split('\n')[0].split(' -- ');
152             if (split.length > 1) {
153                 error.type = split.shift();
154                 error.data.fault_code = error.data.fault_code.substr(error.type.length + 4);
155             }
156         }
157         if (error.code === 200 && error.type) {
158             this.on_managed_error(error);
159         } else {
160             this.on_traceback(error);
161         }
162     },
163     on_managed_error: function(error) {
164         $('<div>' + QWeb.render('CrashManagerWarning', {error: error}) + '</div>').dialog({
165             title: "OpenERP " + _.str.capitalize(error.type),
166             buttons: [
167                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
168             ]
169         });
170     },
171     on_traceback: function(error) {
172         var self = this;
173         var buttons = {};
174         if (openerp.connection.openerp_entreprise) {
175             buttons[_t("Send OpenERP Enterprise Report")] = function() {
176                 var $this = $(this);
177                 var issuename = $('#issuename').val();
178                 var explanation = $('#explanation').val();
179                 var remark = $('#remark').val();
180                 // Call the send method from server to send mail with details
181                 new openerp.web.DataSet(self, 'publisher_warranty.contract').call_and_eval('send', [error.data,explanation,remark,issuename]).then(function(result){
182                     if (result === false) {
183                         alert('There was a communication error.')
184                     } else {
185                         $this.dialog('close');
186                     }
187                 });
188             };
189             buttons[_t("Dont send")] = function() {
190                 $(this).dialog("close");
191             };
192         } else {
193             buttons[_t("Ok")] = function() {
194                 $(this).dialog("close");
195             };
196         }
197         var dialog = new openerp.web.Dialog(this, {
198             title: "OpenERP " + _.str.capitalize(this.error.type),
199             width: '80%',
200             height: '50%',
201             min_width: '800px',
202             min_height: '600px',
203             buttons: buttons
204         }).open();
205         dialog.$element.html(QWeb.render('CrashManagerError', {session: openerp.connection, error: error}));
206     }
207 });
208
209 openerp.web.Loading = openerp.web.OldWidget.extend(/** @lends openerp.web.Loading# */{
210     template: 'Loading',
211     /**
212      * @constructs openerp.web.Loading
213      * @extends openerp.web.OldWidget
214      *
215      * @param parent
216      * @param element_id
217      */
218     init: function(parent) {
219         this._super(parent);
220         this.count = 0;
221         this.blocked_ui = false;
222         var self = this;
223         this.request_call = function() {
224             self.on_rpc_event(1);
225         };
226         this.response_call = function() {
227             self.on_rpc_event(-1);
228         };
229         this.session.on_rpc_request.add_first(this.request_call);
230         this.session.on_rpc_response.add_last(this.response_call);
231     },
232     stop: function() {
233         this.session.on_rpc_request.remove(this.request_call);
234         this.session.on_rpc_response.remove(this.response_call);
235         this.on_rpc_event(-this.count);
236         this._super();
237     },
238     on_rpc_event : function(increment) {
239         var self = this;
240         if (!this.count && increment === 1) {
241             // Block UI after 3s
242             this.long_running_timer = setTimeout(function () {
243                 self.blocked_ui = true;
244                 $.blockUI();
245             }, 3000);
246         }
247
248         this.count += increment;
249         if (this.count > 0) {
250             //this.$element.html(QWeb.render("Loading", {}));
251             $(".loading",this.$element).html("Loading ("+this.count+")");
252             $(".loading",this.$element).show();
253             this.widget_parent.$element.addClass('loading');
254         } else {
255             this.count = 0;
256             clearTimeout(this.long_running_timer);
257             // Don't unblock if blocked by somebody else
258             if (self.blocked_ui) {
259                 this.blocked_ui = false;
260                 $.unblockUI();
261             }
262             $(".loading",this.$element).fadeOut();
263             this.widget_parent.$element.removeClass('loading');
264         }
265     }
266 });
267
268 openerp.web.Database = openerp.web.OldWidget.extend(/** @lends openerp.web.Database# */{
269     template: "DatabaseManager",
270     /**
271      * @constructs openerp.web.Database
272      * @extends openerp.web.OldWidget
273      *
274      * @param parent
275      * @param element_id
276      * @param option_id
277      */
278     init: function(parent, element_id, option_id) {
279         this._super(parent, element_id);
280         this.unblockUIFunction = $.unblockUI;
281         $.validator.addMethod('matches', function (s, _, re) {
282             return new RegExp(re).test(s);
283         }, _t("Invalid database name"));
284     },
285     start: function() {
286         this.$option_id = $("#oe_db_options");
287
288         var self = this;
289         var fetch_db = this.rpc("/web/database/get_list", {}).pipe(
290             function(result) { self.db_list = result.db_list; },
291             function (_, ev) { ev.preventDefault(); self.db_list = null; });
292         var fetch_langs = this.rpc("/web/session/get_lang_list", {}, function(result) {
293             if (result.error) {
294                 self.display_error(result);
295                 return;
296             }
297             self.lang_list = result.lang_list;
298         });
299         $.when(fetch_db, fetch_langs).then(function () {self.do_create();});
300
301         this.$element.find('#db-create').click(this.do_create);
302         this.$element.find('#db-drop').click(this.do_drop);
303         this.$element.find('#db-backup').click(this.do_backup);
304         this.$element.find('#db-restore').click(this.do_restore);
305         this.$element.find('#db-change-password').click(this.do_change_password);
306         this.$element.find('#back-to-login').click(function() {
307             self.hide();
308         });
309     },
310     stop: function () {
311         this.hide();
312         this.$option_id.empty();
313
314         this.$element
315             .find('#db-create, #db-drop, #db-backup, #db-restore, #db-change-password, #back-to-login')
316                 .unbind('click')
317             .end()
318             .empty();
319         this._super();
320     },
321     show: function () {
322         this.$element.closest(".login")
323                 .addClass("database_block");
324     },
325     hide: function () {
326         this.$element.closest(".login")
327                 .removeClass("database_block")
328     },
329     /**
330      * Converts a .serializeArray() result into a dict. Does not bother folding
331      * multiple identical keys into an array, last key wins.
332      *
333      * @param {Array} array
334      */
335     to_object: function (array) {
336         var result = {};
337         _(array).each(function (record) {
338             result[record.name] = record.value;
339         });
340         return result;
341     },
342     /**
343      * Waits until the new database is done creating, then unblocks the UI and
344      * logs the user in as admin
345      *
346      * @param {Number} db_creation_id identifier for the db-creation operation, used to fetch the current installation progress
347      * @param {Object} info info fields for this database creation
348      * @param {String} info.db name of the database being created
349      * @param {String} info.password super-admin password for the database
350      */
351     wait_for_newdb: function (db_creation_id, info) {
352         var self = this;
353         self.rpc('/web/database/progress', {
354             id: db_creation_id,
355             password: info.password
356         }, function (result) {
357             var progress = result[0];
358             // I'd display a progress bar, but turns out the progress status
359             // the server report kind-of blows goats: it's at 0 for ~75% of
360             // the installation, then jumps to 75%, then jumps down to either
361             // 0 or ~40%, then back up to 75%, then terminates. Let's keep that
362             // mess hidden behind a not-very-useful but not overly weird
363             // message instead.
364             if (progress < 1) {
365                 setTimeout(function () {
366                     self.wait_for_newdb(db_creation_id, info);
367                 }, 500);
368                 return;
369             }
370
371             var admin = result[1][0];
372             setTimeout(function () {
373                 self.widget_parent.do_login(
374                         info.db, admin.login, admin.password);
375                 self.stop();
376                 self.unblockUI();
377             });
378         });
379     },
380     /**
381      * Blocks UI and replaces $.unblockUI by a noop to prevent third parties
382      * from unblocking the UI
383      */
384     blockUI: function () {
385         $.blockUI();
386         $.unblockUI = function () {};
387     },
388     /**
389      * Reinstates $.unblockUI so third parties can play with blockUI, and
390      * unblocks the UI
391      */
392     unblockUI: function () {
393         $.unblockUI = this.unblockUIFunction;
394         $.unblockUI();
395     },
396     /**
397      * Displays an error dialog resulting from the various RPC communications
398      * failing over themselves
399      *
400      * @param {Object} error error description
401      * @param {String} error.title title of the error dialog
402      * @param {String} error.error message of the error dialog
403      */
404     display_error: function (error) {
405         return $('<div>').dialog({
406             modal: true,
407             title: error.title,
408             buttons: [
409                 {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
410             ]
411         }).html(error.error);
412     },
413     do_create: function() {
414         var self = this;
415         self.$option_id.html(QWeb.render("Database.CreateDB", self));
416         self.$option_id.find("form[name=create_db_form]").validate({
417             submitHandler: function (form) {
418                 var fields = $(form).serializeArray();
419                 self.blockUI();
420                 self.rpc("/web/database/create", {'fields': fields}, function(result) {
421                     if (result.error) {
422                         self.unblockUI();
423                         self.display_error(result);
424                         return;
425                     }
426                     if (self.db_list) {
427                         self.db_list.push(self.to_object(fields)['db_name']);
428                         self.db_list.sort();
429                         self.widget_parent.set_db_list(self.db_list);
430                     }
431                     var form_obj = self.to_object(fields);
432                     self.wait_for_newdb(result, {
433                         password: form_obj['super_admin_pwd'],
434                         db: form_obj['db_name']
435                     });
436                 });
437             }
438         });
439     },
440     do_drop: function() {
441         var self = this;
442         self.$option_id.html(QWeb.render("DropDB", self));
443         self.$option_id.find("form[name=drop_db_form]").validate({
444             submitHandler: function (form) {
445                 var $form = $(form),
446                     fields = $form.serializeArray(),
447                     $db_list = $form.find('select[name=drop_db]'),
448                     db = $db_list.val();
449
450                 if (!confirm("Do you really want to delete the database: " + db + " ?")) {
451                     return;
452                 }
453                 self.rpc("/web/database/drop", {'fields': fields}, function(result) {
454                     if (result.error) {
455                         self.display_error(result);
456                         return;
457                     }
458                     $db_list.find(':selected').remove();
459                     if (self.db_list) {
460                         self.db_list.splice(_.indexOf(self.db_list, db, true), 1);
461                         self.widget_parent.set_db_list(self.db_list);
462                     }
463                     self.do_notify("Dropping database", "The database '" + db + "' has been dropped");
464                 });
465             }
466         });
467     },
468     do_backup: function() {
469         var self = this;
470         self.$option_id
471             .html(QWeb.render("BackupDB", self))
472             .find("form[name=backup_db_form]").validate({
473             submitHandler: function (form) {
474                 self.blockUI();
475                 self.session.get_file({
476                     form: form,
477                     success: function () {
478                         self.do_notify(_t("Backed"),
479                             _t("Database backed up successfully"));
480                     },
481                     error: openerp.webclient.crashmanager.on_rpc_error,
482                     complete: function() {
483                         self.unblockUI();
484                     }
485                 });
486             }
487         });
488     },
489     do_restore: function() {
490         var self = this;
491         self.$option_id.html(QWeb.render("RestoreDB", self));
492
493         self.$option_id.find("form[name=restore_db_form]").validate({
494             submitHandler: function (form) {
495                 self.blockUI();
496                 $(form).ajaxSubmit({
497                     url: '/web/database/restore',
498                     type: 'POST',
499                     resetForm: true,
500                     success: function (body) {
501                         // TODO: ui manipulations
502                         // note: response objects don't work, but we have the
503                         // HTTP body of the response~~
504
505                         // If empty body, everything went fine
506                         if (!body) { return; }
507
508                         if (body.indexOf('403 Forbidden') !== -1) {
509                             self.display_error({
510                                 title: 'Access Denied',
511                                 error: 'Incorrect super-administrator password'
512                             })
513                         } else {
514                             self.display_error({
515                                 title: 'Restore Database',
516                                 error: 'Could not restore the database'
517                             })
518                         }
519                     },
520                     complete: function() {
521                         self.unblockUI();
522                         self.do_notify(_t("Restored"), _t("Database restored successfully"));
523                     }
524                 });
525             }
526         });
527     },
528     do_change_password: function() {
529         var self = this;
530         self.$option_id.html(QWeb.render("Change_DB_Pwd", self));
531
532         self.$option_id.find("form[name=change_pwd_form]").validate({
533             messages: {
534                 old_pwd: "Please enter your previous password",
535                 new_pwd: "Please enter your new password",
536                 confirm_pwd: {
537                     required: "Please confirm your new password",
538                     equalTo: "The confirmation does not match the password"
539                 }
540             },
541             submitHandler: function (form) {
542                 self.rpc("/web/database/change_password", {
543                     'fields': $(form).serializeArray()
544                 }, function(result) {
545                     if (result.error) {
546                         self.display_error(result);
547                         return;
548                     }
549                     self.do_notify("Changed Password", "Password has been changed successfully");
550                 });
551             }
552         });
553     }
554 });
555
556 openerp.web.Login =  openerp.web.OldWidget.extend(/** @lends openerp.web.Login# */{
557     remember_credentials: true,
558     
559     template: "Login",
560     /**
561      * @constructs openerp.web.Login
562      * @extends openerp.web.OldWidget
563      *
564      * @param parent
565      * @param element_id
566      */
567
568     init: function(parent) {
569         this._super(parent);
570         this.has_local_storage = typeof(localStorage) != 'undefined';
571         this.selected_db = null;
572         this.selected_login = null;
573
574         if (this.has_local_storage && this.remember_credentials) {
575             this.selected_db = localStorage.getItem('last_db_login_success');
576             this.selected_login = localStorage.getItem('last_login_login_success');
577             if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
578                 this.selected_password = localStorage.getItem('last_password_login_success');
579             }
580         }
581     },
582     start: function() {
583         var self = this;
584         this.database = new openerp.web.Database(this);
585         this.database.appendTo(this.$element);
586
587         this.$element.find('#oe-db-config').click(function() {
588             self.database.show();
589         });
590
591         this.$element.find("form").submit(this.on_submit);
592
593         this.rpc("/web/database/get_list", {}, function(result) {
594             self.set_db_list(result.db_list);
595         }, 
596         function(error, event) {
597             if (error.data.fault_code === 'AccessDenied') {
598                 event.preventDefault();
599             }
600         });
601
602     },
603     set_db_list: function (list) {
604         this.$element.find("[name=db]").replaceWith(
605             openerp.web.qweb.render('Login_dblist', {
606                 db_list: list, selected_db: this.selected_db}))
607     },
608     on_submit: function(ev) {
609         if(ev) {
610             ev.preventDefault();
611         }
612         var $e = this.$element;
613         var db = $e.find("form [name=db]").val();
614         var login = $e.find("form input[name=login]").val();
615         var password = $e.find("form input[name=password]").val();
616
617         this.do_login(db, login, password);
618     },
619     /**
620      * Performs actual login operation, and UI-related stuff
621      *
622      * @param {String} db database to log in
623      * @param {String} login user login
624      * @param {String} password user password
625      */
626     do_login: function (db, login, password) {
627         var self = this;
628         this.$element.removeClass('login_invalid');
629         this.session.on_session_invalid.add({
630             callback: function () {
631                 self.$element.addClass("login_invalid");
632             },
633             unique: true
634         });
635         this.session.session_authenticate(db, login, password).then(function() {
636             self.$element.removeClass("login_invalid");
637             if (self.has_local_storage) {
638                 if(self.remember_credentials) {
639                     localStorage.setItem('last_db_login_success', db);
640                     localStorage.setItem('last_login_login_success', login);
641                     if (jQuery.deparam(jQuery.param.querystring()).debug != undefined) {
642                         localStorage.setItem('last_password_login_success', password);
643                     }
644                 } else {
645                     localStorage.setItem('last_db_login_success', '');
646                     localStorage.setItem('last_login_login_success', '');
647                     localStorage.setItem('last_password_login_success', '');
648                 }
649             }
650         });
651     }
652 });
653
654 openerp.web.Header =  openerp.web.OldWidget.extend(/** @lends openerp.web.Header# */{
655     template: "Header",
656     /**
657      * @constructs openerp.web.Header
658      * @extends openerp.web.OldWidget
659      *
660      * @param parent
661      */
662     init: function(parent) {
663         this._super(parent);
664         this.qs = "?" + jQuery.param.querystring();
665         this.$content = $();
666         this.update_promise = $.Deferred().resolve();
667     },
668     start: function() {
669         this._super();
670     },
671     do_update: function () {
672         var self = this;
673         var fct = function() {
674             self.$content.remove();
675             if (!self.session.uid)
676                 return;
677             var func = new openerp.web.Model("res.users").get_func("read");
678             return func(self.session.uid, ["name", "company_id"]).pipe(function(res) {
679                 self.$content = $(QWeb.render("Header-content", {widget: self, user: res}));
680                 self.$content.appendTo(self.$element);
681                 self.$element.find(".logout").click(self.on_logout);
682                 self.$element.find("a.preferences").click(self.on_preferences);
683                 self.$element.find(".about").click(self.on_about);
684                 return self.shortcut_load();
685             });
686         };
687         this.update_promise = this.update_promise.pipe(fct, fct);
688     },
689     on_about: function() {
690         var self = this;
691         self.rpc("/web/webclient/version_info", {}).then(function(res) {
692             var $help = $(QWeb.render("About-Page", {version_info: res}));
693             $help.find('a.oe_activate_debug_mode').click(function (e) {
694                 e.preventDefault();
695                 window.location = $.param.querystring(
696                         window.location.href, 'debug');
697             });
698             $help.dialog({autoOpen: true,
699                 modal: true, width: 960, title: _t("About")});
700         });
701     },
702     shortcut_load :function(){
703         var self = this,
704             sc = self.session.shortcuts,
705             shortcuts_ds = new openerp.web.DataSet(this, 'ir.ui.view_sc');
706         // TODO: better way to communicate between sections.
707         // sc.bindings, because jquery does not bind/trigger on arrays...
708         if (!sc.binding) {
709             sc.binding = {};
710             $(sc.binding).bind({
711                 'add': function (e, attrs) {
712                     shortcuts_ds.create(attrs, function (out) {
713                         $('<li>', {
714                             'data-shortcut-id':out.result,
715                             'data-id': attrs.res_id
716                         }).text(attrs.name)
717                           .appendTo(self.$element.find('.oe-shortcuts ul'));
718                         attrs.id = out.result;
719                         sc.push(attrs);
720                     });
721                 },
722                 'remove-current': function () {
723                     var menu_id = self.session.active_id;
724                     var $shortcut = self.$element
725                         .find('.oe-shortcuts li[data-id=' + menu_id + ']');
726                     var shortcut_id = $shortcut.data('shortcut-id');
727                     $shortcut.remove();
728                     shortcuts_ds.unlink([shortcut_id]);
729                     var sc_new = _.reject(sc, function(shortcut){ return shortcut_id === shortcut.id});
730                     sc.splice(0, sc.length);
731                     sc.push.apply(sc, sc_new);
732                     }
733             });
734         }
735         return this.rpc('/web/session/sc_list', {}, function(shortcuts) {
736             sc.splice(0, sc.length);
737             sc.push.apply(sc, shortcuts);
738
739             self.$element.find('.oe-shortcuts')
740                 .html(QWeb.render('Shortcuts', {'shortcuts': shortcuts}))
741                 .undelegate('li', 'click')
742
743                 .delegate('li', 'click', function(e) {
744                     e.stopPropagation();
745                     var id = $(this).data('id');
746                     self.session.active_id = id;
747                     self.rpc('/web/menu/action', {'menu_id':id}, function(ir_menu_data) {
748                         if (ir_menu_data.action.length){
749                             self.on_action(ir_menu_data.action[0][2]);
750                         }
751                     });
752                 });
753         });
754     },
755
756     on_action: function(action) {
757     },
758     on_preferences: function(){
759         var self = this;
760         var action_manager = new openerp.web.ActionManager(this);
761         var dataset = new openerp.web.DataSet (this,'res.users',this.context);
762         dataset.call ('action_get','',function (result){
763             self.rpc('/web/action/load', {action_id:result}, function(result){
764                 action_manager.do_action(_.extend(result['result'], {
765                     res_id: self.session.uid,
766                     res_model: 'res.users',
767                     flags: {
768                         action_buttons: false,
769                         search_view: false,
770                         sidebar: false,
771                         views_switcher: false,
772                         pager: false
773                     }
774                 }));
775             });
776         });
777         this.dialog = new openerp.web.Dialog(this,{
778             title: _t("Preferences"),
779             width: '700px',
780             buttons: [
781                 {text: _t("Cancel"), click: function(){ $(this).dialog('destroy'); }},
782                 {text: _t("Change password"), click: function(){ self.change_password(); }},
783                 {text: _t("Save"), click: function(){
784                         var inner_viewmanager = action_manager.inner_viewmanager;
785                         inner_viewmanager.views[inner_viewmanager.active_view].controller.do_save()
786                         .then(function() {
787                             self.dialog.stop();
788                             // needs to refresh interface in case language changed
789                             window.location.reload();
790                         });
791                     }
792                 }
793             ]
794         }).open();
795        action_manager.appendTo(this.dialog);
796        action_manager.render(this.dialog);
797     },
798
799     change_password :function() {
800         var self = this;
801         this.dialog = new openerp.web.Dialog(this, {
802             title: _t("Change Password"),
803             width : 'auto'
804         }).open();
805         this.dialog.$element.html(QWeb.render("Change_Pwd", self));
806         this.dialog.$element.find("form[name=change_password_form]").validate({
807             submitHandler: function (form) {
808                 self.rpc("/web/session/change_password",{
809                     'fields': $(form).serializeArray()
810                 }, function(result) {
811                     if (result.error) {
812                         self.display_error(result);
813                         return;
814                     } else {
815                         openerp.webclient.on_logout();
816                     }
817                 });
818             }
819         });
820     },
821     display_error: function (error) {
822         return $('<div>').dialog({
823             modal: true,
824             title: error.title,
825             buttons: [
826                 {text: _("Ok"), click: function() { $(this).dialog("close"); }}
827             ]
828         }).html(error.error);
829     },
830     on_logout: function() {
831     }
832 });
833
834 openerp.web.Menu =  openerp.web.OldWidget.extend(/** @lends openerp.web.Menu# */{
835     /**
836      * @constructs openerp.web.Menu
837      * @extends openerp.web.OldWidget
838      *
839      * @param parent
840      * @param element_id
841      * @param secondary_menu_id
842      */
843     init: function(parent, element_id, secondary_menu_id) {
844         this._super(parent, element_id);
845         this.secondary_menu_id = secondary_menu_id;
846         this.$secondary_menu = $("#" + secondary_menu_id);
847         this.menu = false;
848         this.folded = false;
849         if (window.localStorage) {
850             this.folded = localStorage.getItem('oe_menu_folded') === 'true';
851         }
852         this.float_timeout = 700;
853     },
854     start: function() {
855         this.$secondary_menu.addClass(this.folded ? 'oe_folded' : 'oe_unfolded');
856     },
857     do_reload: function() {
858         var self = this;
859         return this.rpc("/web/menu/load", {}, this.on_loaded).then(function () {
860             if (self.current_menu) {
861                 self.open_menu(self.current_menu);
862             }
863         });
864     },
865     on_loaded: function(data) {
866         this.data = data;
867         this.$element.html(QWeb.render("Menu", { widget : this }));
868         this.$secondary_menu.html(QWeb.render("Menu.secondary", { widget : this }));
869         this.$element.add(this.$secondary_menu).find("a").click(this.on_menu_click);
870         this.$secondary_menu.find('.oe_toggle_secondary_menu').click(this.on_toggle_fold);
871     },
872     on_toggle_fold: function() {
873         this.$secondary_menu.toggleClass('oe_folded').toggleClass('oe_unfolded');
874         if (this.folded) {
875             this.$secondary_menu.find('.oe_secondary_menu.active').show();
876         } else {
877             this.$secondary_menu.find('.oe_secondary_menu').hide();
878         }
879         this.folded = !this.folded;
880         if (window.localStorage) {
881             localStorage.setItem('oe_menu_folded', this.folded.toString());
882         }
883     },
884     /**
885      * Opens a given menu by id, as if a user had browsed to that menu by hand
886      * except does not trigger any event on the way
887      *
888      * @param {Number} menu_id database id of the terminal menu to select
889      */
890     open_menu: function (menu_id) {
891         this.$element.add(this.$secondary_menu).find('.active')
892                 .removeClass('active');
893         this.$secondary_menu.find('> .oe_secondary_menu').hide();
894
895         var $primary_menu;
896         var $secondary_submenu = this.$secondary_menu.find(
897                 'a[data-menu=' + menu_id +']');
898         if ($secondary_submenu.length) {
899             for(;;) {
900                 if ($secondary_submenu.hasClass('leaf')) {
901                     $secondary_submenu.addClass('active');
902                 } else if ($secondary_submenu.hasClass('submenu')) {
903                     $secondary_submenu.addClass('opened')
904                 }
905                 var $parent = $secondary_submenu.parent().show();
906                 if ($parent.hasClass('oe_secondary_menu')) {
907                     var primary_id = $parent.data('menu-parent');
908                     $primary_menu = this.$element.find(
909                             'a[data-menu=' + primary_id + ']');
910                     break;
911                 }
912                 $secondary_submenu = $parent.prev();
913             }
914         } else {
915             $primary_menu = this.$element.find('a[data-menu=' + menu_id + ']');
916         }
917         if (!$primary_menu.length) {
918             return;
919         }
920         $primary_menu.addClass('active');
921         this.$secondary_menu.find(
922             'div[data-menu-parent=' + $primary_menu.data('menu') + ']').show();
923     },
924     on_menu_click: function(ev, id) {
925         id = id || 0;
926         var $clicked_menu, manual = false;
927
928         if (id) {
929             // We can manually activate a menu with it's id (for hash url mapping)
930             manual = true;
931             $clicked_menu = this.$element.find('a[data-menu=' + id + ']');
932             if (!$clicked_menu.length) {
933                 $clicked_menu = this.$secondary_menu.find('a[data-menu=' + id + ']');
934             }
935         } else {
936             $clicked_menu = $(ev.currentTarget);
937             id = $clicked_menu.data('menu');
938         }
939
940         if (this.do_menu_click($clicked_menu, manual) && id) {
941             this.current_menu = id;
942             this.session.active_id = id;
943             this.rpc('/web/menu/action', {'menu_id': id}, this.on_menu_action_loaded);
944         }
945         if (ev) {
946             ev.stopPropagation();
947         }
948         return false;
949     },
950     do_menu_click: function($clicked_menu, manual) {
951         var $sub_menu, $main_menu,
952             active = $clicked_menu.is('.active'),
953             sub_menu_visible = false;
954
955         if (this.$secondary_menu.has($clicked_menu).length) {
956             $sub_menu = $clicked_menu.parents('.oe_secondary_menu');
957             $main_menu = this.$element.find('a[data-menu=' + $sub_menu.data('menu-parent') + ']');
958         } else {
959             $sub_menu = this.$secondary_menu.find('.oe_secondary_menu[data-menu-parent=' + $clicked_menu.attr('data-menu') + ']');
960             $main_menu = $clicked_menu;
961         }
962
963         sub_menu_visible = $sub_menu.is(':visible');
964         this.$secondary_menu.find('.oe_secondary_menu').hide();
965
966         $('.active', this.$element.add(this.$secondary_menu)).removeClass('active');
967         $main_menu.add($clicked_menu).add($sub_menu).addClass('active');
968
969         if (!(this.folded && manual)) {
970             this.do_show_secondary($sub_menu, $main_menu);
971         } else {
972             this.do_show_secondary();
973         }
974
975         if ($main_menu != $clicked_menu) {
976             if ($clicked_menu.is('.submenu')) {
977                 $sub_menu.find('.submenu.opened').each(function() {
978                     if (!$(this).next().has($clicked_menu).length && !$(this).is($clicked_menu)) {
979                         $(this).removeClass('opened').next().hide();
980                     }
981                 });
982                 $clicked_menu.toggleClass('opened').next().toggle();
983             } else if ($clicked_menu.is('.leaf')) {
984                 $sub_menu.toggle(!this.folded);
985                 return true;
986             }
987         } else if (this.folded) {
988             if (active && sub_menu_visible) {
989                 $sub_menu.hide();
990                 return true;
991             }
992             return manual;
993         } else {
994             return true;
995         }
996         return false;
997     },
998     do_hide_secondary: function() {
999         this.$secondary_menu.hide();
1000     },
1001     do_show_secondary: function($sub_menu, $main_menu) {
1002         var self = this;
1003         this.$secondary_menu.show();
1004         if (!arguments.length) {
1005             return;
1006         }
1007         if (this.folded) {
1008             var css = $main_menu.position(),
1009                 fold_width = this.$secondary_menu.width() + 2,
1010                 window_width = $(window).width();
1011             css.top += 33;
1012             css.left -= Math.round(($sub_menu.width() - $main_menu.width()) / 2);
1013             css.left = css.left < fold_width ? fold_width : css.left;
1014             if ((css.left + $sub_menu.width()) > window_width) {
1015                 delete(css.left);
1016                 css.right = 1;
1017             }
1018             $sub_menu.css(css);
1019             $sub_menu.mouseenter(function() {
1020                 clearTimeout($sub_menu.data('timeoutId'));
1021                 $sub_menu.data('timeoutId', null);
1022                 return false;
1023             }).mouseleave(function(evt) {
1024                 var timeoutId = setTimeout(function() {
1025                     if (self.folded && $sub_menu.data('timeoutId')) {
1026                         $sub_menu.hide().unbind('mouseenter').unbind('mouseleave');
1027                     }
1028                 }, self.float_timeout);
1029                 $sub_menu.data('timeoutId', timeoutId);
1030                 return false;
1031             });
1032         }
1033         $sub_menu.show();
1034     },
1035     on_menu_action_loaded: function(data) {
1036         var self = this;
1037         if (data.action.length) {
1038             var action = data.action[0][2];
1039             action.from_menu = true;
1040             self.on_action(action);
1041         } else {
1042             self.on_action({type: 'null_action'});
1043         }
1044     },
1045     on_action: function(action) {
1046     }
1047 });
1048
1049 openerp.web.WebClient = openerp.web.OldWidget.extend(/** @lends openerp.web.WebClient */{
1050     /**
1051      * @constructs openerp.web.WebClient
1052      * @extends openerp.web.OldWidget
1053      *
1054      * @param element_id
1055      */
1056     init: function(parent) {
1057         var self = this;
1058         this._super(parent);
1059         openerp.webclient = this;
1060
1061         this._current_state = null;
1062     },
1063     start: function() {
1064         var self = this;
1065         this.$element = $(document.body);
1066         if (jQuery.param != undefined && jQuery.deparam(jQuery.param.querystring()).kitten != undefined) {
1067             this.$element.addClass("kitten-mode-activated");
1068             this.$element.delegate('img.oe-record-edit-link-img', 'hover', function(e) {
1069                 self.$element.toggleClass('clark-gable');
1070             });
1071         }
1072         this.session.bind().then(function() {
1073             if (!self.session.session_is_valid()) {
1074                 self.show_login();
1075             }
1076         });
1077         this.session.on_session_valid.add(function() {
1078             self.show_application();
1079             
1080             self.header.do_update();
1081             self.menu.do_reload();
1082             if(self.action_manager)
1083                 self.action_manager.stop();
1084             self.action_manager = new openerp.web.ActionManager(self);
1085             self.action_manager.appendTo($("#oe_app"));
1086             self.bind_hashchange();
1087             if (!self.session.openerp_entreprise) {
1088                 self.$element.find('.oe_footer_powered').append('<span> - <a href="http://www.openerp.com/support-or-publisher-warranty-contract" target="_blank">Unsupported/Community Version</a></span>');
1089                 document.title = _t("OpenERP - Unsupported/Community Version");
1090             }
1091         });
1092     },
1093     show_login: function() {
1094         var self = this;
1095         this.destroy_content();
1096         this.show_common();
1097         self.login = new openerp.web.Login(self);
1098         self.login.appendTo(self.$element);
1099     },
1100     show_application: function() {
1101         var self = this;
1102         this.destroy_content();
1103         this.show_common();
1104         self.$table = $(QWeb.render("Interface", {}));
1105         self.$element.append(self.$table);
1106         self.header = new openerp.web.Header(self);
1107         self.header.on_logout.add(this.proxy('on_logout'));
1108         self.header.on_action.add(this.proxy('on_menu_action'));
1109         self.header.appendTo($("#oe_header"));
1110         self.menu = new openerp.web.Menu(self, "oe_menu", "oe_secondary_menu");
1111         self.menu.on_action.add(this.proxy('on_menu_action'));
1112         self.menu.start();
1113     },
1114     show_common: function() {
1115         if (!this.crashmanager) {
1116             this.crashmanager =  new openerp.web.CrashManager();
1117         }
1118         this.notification = new openerp.web.Notification(this);
1119         this.notification.appendTo(this.$element);
1120         this.loading = new openerp.web.Loading(this);
1121         this.loading.appendTo(this.$element);
1122     },
1123     destroy_content: function() {
1124         _.each(_.clone(this.widget_children), function(el) {
1125             el.stop();
1126         });
1127         this.$element.children().remove();
1128     },
1129     do_reload: function() {
1130         var self = this;
1131         return this.session.session_reload().pipe(function () {
1132             openerp.connection.load_modules(true).pipe(
1133                 self.menu.proxy('do_reload')); });
1134
1135     },
1136     do_notify: function() {
1137         var n = this.notification;
1138         n.notify.apply(n, arguments);
1139     },
1140     do_warn: function() {
1141         var n = this.notification;
1142         n.warn.apply(n, arguments);
1143     },
1144     on_logout: function() {
1145         this.session.session_logout();
1146         $(window).unbind('hashchange', this.on_hashchange);
1147         this.do_push_state({});
1148         //would be cool to be able to do this, but I think it will make addons do strange things
1149         //this.show_login();
1150         window.location.reload();
1151     },
1152     bind_hashchange: function() {
1153         $(window).bind('hashchange', this.on_hashchange);
1154
1155         var state = $.bbq.getState(true);
1156         if (! _.isEmpty(state)) {
1157             $(window).trigger('hashchange');
1158         } else {
1159             this.action_manager.do_action({type: 'ir.actions.client', tag: 'default_home'});
1160         }
1161     },
1162     on_hashchange: function(event) {
1163         var state = event.getState(true);
1164         if (!_.isEqual(this._current_state, state)) {
1165             this.action_manager.do_load_state(state);
1166         }
1167         this._current_state = state;
1168     },
1169     do_push_state: function(state) {
1170         var url = '#' + $.param(state);
1171         this._current_state = _.clone(state);
1172         $.bbq.pushState(url);
1173     },
1174     on_menu_action: function(action) {
1175         this.action_manager.do_action(action);
1176     },
1177     do_action: function(action) {
1178         var self = this;
1179         // TODO replace by client action menuclick 
1180         if(action.menu_id) {
1181             this.do_reload().then(function () {
1182                 self.menu.on_menu_click(null, action.menu_id);
1183             });
1184         }
1185     }
1186 });
1187
1188 openerp.web.EmbeddedClient = openerp.web.OldWidget.extend({
1189     template: 'EmptyComponent',
1190     init: function(action_id, options) {
1191         this._super();
1192         // TODO take the xmlid of a action instead of its id 
1193         this.action_id = action_id;
1194         this.options = options || {};
1195         this.am = new openerp.web.ActionManager(this);
1196     },
1197
1198     start: function() {
1199         var self = this;
1200         this.am.appendTo(this.$element.addClass('openerp'));
1201         return this.rpc("/web/action/load", { action_id: this.action_id }, function(result) {
1202             var action = result.result;
1203             action.flags = _.extend({
1204                 //views_switcher : false,
1205                 search_view : false,
1206                 action_buttons : false,
1207                 sidebar : false
1208                 //pager : false
1209             }, self.options, action.flags || {});
1210
1211             self.am.do_action(action);
1212         });
1213     }
1214
1215 });
1216
1217 openerp.web.embed = function (origin, dbname, login, key, action, options) {
1218     $('head').append($('<link>', {
1219         'rel': 'stylesheet',
1220         'type': 'text/css',
1221         'href': origin +'/web/webclient/css'
1222     }));
1223     var currentScript = document.currentScript;
1224     if (!currentScript) {
1225         var sc = document.getElementsByTagName('script');
1226         currentScript = sc[sc.length-1];
1227     }
1228     openerp.connection.bind(origin).then(function () {
1229         openerp.connection.session_authenticate(dbname, login, key, true).then(function () {
1230             var client = new openerp.web.EmbeddedClient(action, options);
1231             client.insertAfter(currentScript);
1232         });
1233     });
1234
1235 }
1236
1237 };
1238
1239 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: