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