[IMP] Added condition for menu reloading
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(db) {
6
7 var _t = db.web._t;
8
9 /**
10  * Registry for all the client actions key: tag value: widget
11  */
12 db.web.client_actions = new db.web.Registry();
13
14 /**
15  * Registry for all the main views
16  */
17 db.web.views = new db.web.Registry();
18
19 db.web.ActionManager = db.web.Widget.extend({
20     identifier_prefix: "actionmanager",
21     init: function(parent) {
22         this._super(parent);
23         this.inner_viewmanager = null;
24         this.dialog = null;
25         this.dialog_viewmanager = null;
26         this.client_widget = null;
27     },
28     render: function() {
29         return "<div id='"+this.element_id+"'></div>";
30     },
31     dialog_stop: function () {
32         if (this.dialog) {
33             this.dialog_viewmanager.stop();
34             this.dialog_viewmanager = null;
35             this.dialog.stop();
36             this.dialog = null;
37         }
38     },
39     content_stop: function () {
40         if (this.inner_viewmanager) {
41             this.inner_viewmanager.stop();
42             this.inner_viewmanager = null;
43         }
44         if (this.client_widget) {
45             this.client_widget.stop();
46             this.client_widget = null;
47         }
48     },
49     url_update: function(action) {
50         var url = {};
51         if(action.id)
52             url.action_id = action.id;
53         // this.url = {
54         //     "model": action.res_model,
55         //     "domain": action.domain,
56         // };
57         // action.res_model
58         // action.domain
59         // action.context
60         // after
61         // action.views
62         // action.res_id
63         // mode
64         // menu
65         this.do_url_set_hash(url);
66     },
67     do_url_set_hash: function(url) {
68     },
69     on_url_hashchange: function(url) {
70         var self = this;
71         if(url && url.action_id) {
72             self.rpc("/web/action/load", { action_id: url.action_id }, function(result) {
73                     self.do_action(result.result);
74                 });
75         }
76     },
77     do_action: function(action, on_close) {
78         var type = action.type.replace(/\./g,'_');
79         var popup = action.target === 'new';
80         action.flags = _.extend({
81             views_switcher : !popup,
82             search_view : !popup,
83             action_buttons : !popup,
84             sidebar : !popup,
85             pager : !popup
86         }, action.flags || {});
87         if (!(type in this)) {
88             console.log("Action manager can't handle action of type " + action.type, action);
89             return;
90         }
91         return this[type](action, on_close);
92     },
93     ir_actions_act_window: function (action, on_close) {
94         if (action.target === 'new') {
95             if (this.dialog == null) {
96                 this.dialog = new db.web.Dialog(this, { title: action.name, width: '80%' });
97                 if(on_close)
98                     this.dialog.on_close.add(on_close);
99                 this.dialog.start();
100             } else {
101                 this.dialog_viewmanager.stop();
102             }
103             this.dialog_viewmanager = new db.web.ViewManagerAction(this, action);
104             this.dialog_viewmanager.appendTo(this.dialog.$element);
105             this.dialog.open();
106         } else  {
107             this.dialog_stop();
108             this.content_stop();
109             this.inner_viewmanager = new db.web.ViewManagerAction(this, action);
110             this.inner_viewmanager.appendTo(this.$element);
111             this.url_update(action);
112         }
113         /* new window code
114             this.rpc("/web/session/save_session_action", { the_action : action}, function(key) {
115                 var url = window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + jQuery.param({ s_action : "" + key });
116                 window.open(url,'_blank');
117             });
118         */
119     },
120     ir_actions_act_window_close: function (action, on_closed) {
121         if (!this.dialog && on_closed) {
122             on_closed();
123         }
124         if (this.dialog && action.context) {
125             var model = action.context.active_model;
126             if (model === 'base.module.upgrade' || model === 'base.setup.installer') {
127                 db.webclient.menu.reload();
128             }
129         }
130         this.dialog_stop();
131     },
132     ir_actions_server: function (action, on_closed) {
133         var self = this;
134         this.rpc('/web/action/run', {
135             action_id: action.id,
136             context: action.context || {}
137         }).then(function (action) {
138             self.do_action(action, on_closed)
139         });
140     },
141     ir_actions_client: function (action) {
142         this.content_stop();
143         var ClientWidget = db.web.client_actions.get_object(action.tag);
144         (this.client_widget = new ClientWidget(this, action.params)).appendTo(this);
145     },
146     ir_actions_report_xml: function(action) {
147         var self = this;
148         $.blockUI();
149         self.rpc("/web/session/eval_domain_and_context", {
150             contexts: [action.context],
151             domains: []
152         }).then(function(res) {
153             action = _.clone(action);
154             action.context = res.context;
155             self.session.get_file({
156                 url: '/web/report',
157                 data: {action: JSON.stringify(action)},
158                 complete: $.unblockUI
159             });
160         });
161     }
162 });
163
164 db.web.ViewManager =  db.web.Widget.extend(/** @lends db.web.ViewManager# */{
165     identifier_prefix: "viewmanager",
166     template: "ViewManager",
167     /**
168      * @constructs db.web.ViewManager
169      * @extends db.web.Widget
170      *
171      * @param parent
172      * @param dataset
173      * @param views
174      */
175     init: function(parent, dataset, views) {
176         this._super(parent);
177         this.model = dataset ? dataset.model : undefined;
178         this.dataset = dataset;
179         this.searchview = null;
180         this.last_search = false;
181         this.active_view = null;
182         this.views_src = _.map(views, function(x) {return x instanceof Array? {view_id: x[0], view_type: x[1]} : x;});
183         this.views = {};
184         this.flags = this.flags || {};
185         this.registry = db.web.views;
186     },
187     render: function() {
188         return db.web.qweb.render(this.template, {
189             self: this,
190             prefix: this.element_id,
191             views: this.views_src});
192     },
193     /**
194      * @returns {jQuery.Deferred} initial view loading promise
195      */
196     start: function() {
197         this._super();
198         var self = this;
199         this.$element.find('.oe_vm_switch button').click(function() {
200             self.on_mode_switch($(this).data('view-type'));
201         });
202         var views_ids = {};
203         _.each(this.views_src, function(view) {
204             self.views[view.view_type] = $.extend({}, view, {
205                 controller : null,
206                 options : _.extend({
207                     sidebar_id : self.element_id + '_sidebar_' + view.view_type,
208                     action : self.action,
209                     action_views_ids : views_ids
210                 }, self.flags, view.options || {})
211             });
212             views_ids[view.view_type] = view.view_id;
213         });
214         if (this.flags.views_switcher === false) {
215             this.$element.find('.oe_vm_switch').hide();
216         }
217         // switch to the first one in sequence
218         return this.on_mode_switch(this.views_src[0].view_type);
219     },
220     /**
221      * Asks the view manager to switch visualization mode.
222      *
223      * @param {String} view_type type of view to display
224      * @returns {jQuery.Deferred} new view loading promise
225      */
226     on_mode_switch: function(view_type) {
227         var self = this,
228             view_promise;
229         this.active_view = view_type;
230         var view = this.views[view_type];
231         if (!view.controller) {
232             // Lazy loading of views
233             var controllerclass = this.registry.get_object(view_type);
234             var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
235             if (view.embedded_view) {
236                 controller.set_embedded_view(view.embedded_view);
237             }
238             controller.do_switch_view.add_last(this.on_mode_switch);
239             var container = $("#" + this.element_id + '_view_' + view_type);
240             view_promise = controller.appendTo(container);
241             this.views[view_type].controller = controller;
242             $.when(view_promise).then(function() {
243                 self.on_controller_inited(view_type, controller);
244                 if (self.searchview && view.controller.searchable !== false) {
245                     self.do_searchview_search();
246                 }
247             });
248         } else if (this.searchview && view.controller.searchable !== false) {
249             self.do_searchview_search();
250         }
251
252         if (this.searchview) {
253             this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
254         }
255
256         this.$element
257             .find('.views-switchers button').removeAttr('disabled')
258             .filter('[data-view-type="' + view_type + '"]')
259             .attr('disabled', true);
260
261         for (var view_name in this.views) {
262             if (!this.views.hasOwnProperty(view_name)) { continue; }
263             if (this.views[view_name].controller) {
264                 if (view_name === view_type) {
265                     $.when(view_promise).then(this.views[view_name].controller.do_show);
266                 } else {
267                     this.views[view_name].controller.do_hide();
268                 }
269             }
270         }
271         return view_promise;
272     },
273     /**
274      * Sets up the current viewmanager's search view.
275      *
276      * @param {Number|false} view_id the view to use or false for a default one
277      * @returns {jQuery.Deferred} search view startup deferred
278      */
279     setup_search_view: function(view_id, search_defaults) {
280         var self = this;
281         if (this.searchview) {
282             this.searchview.stop();
283         }
284         this.searchview = new db.web.SearchView(
285                 this, this.dataset,
286                 view_id, search_defaults, this.flags.search_view === false);
287
288         this.searchview.on_search.add(this.do_searchview_search);
289         return this.searchview.appendTo($("#" + this.element_id + "_search"));
290     },
291     do_searchview_search: function(domains, contexts, groupbys) {
292         var self = this,
293             controller = this.views[this.active_view].controller;
294         if (domains || contexts) {
295             this.rpc('/web/session/eval_domain_and_context', {
296                 domains: [this.action.domain || []].concat(domains || []),
297                 contexts: [this.action.context || {}].concat(contexts || []),
298                 group_by_seq: groupbys || []
299             }, function (results) {
300                 self.dataset.context = results.context;
301                 self.dataset.domain = results.domain;
302                 self.last_search = [results.domain, results.context, results.group_by];
303                 controller.do_search(results.domain, results.context, results.group_by);
304             });
305         } else if (this.last_search) {
306             controller.do_search.apply(controller, this.last_search);
307         }
308     },
309     /**
310      * Event launched when a controller has been inited.
311      *
312      * @param {String} view_type type of view
313      * @param {String} view the inited controller
314      */
315     on_controller_inited: function(view_type, view) {
316     },
317     /**
318      * Called when one of the view want to execute an action
319      */
320     on_action: function(action) {
321     },
322     on_create: function() {
323     },
324     on_remove: function() {
325     },
326     on_edit: function() {
327     },
328     /**
329      * Called by children view after executing an action
330      */
331     on_action_executed: function () {}
332 });
333
334 db.web.ViewManagerAction = db.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
335     template:"ViewManagerAction",
336     /**
337      * @constructs db.web.ViewManagerAction
338      * @extends db.web.ViewManager
339      *
340      * @param {db.web.ActionManager} parent parent object/widget
341      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
342      */
343     init: function(parent, action) {
344         // dataset initialization will take the session from ``this``, so if we
345         // do not have it yet (and we don't, because we've not called our own
346         // ``_super()``) rpc requests will blow up.
347         this._super(parent, null, action.views);
348         this.session = parent.session;
349         this.action = action;
350         var dataset = new db.web.DataSetSearch(this, action.res_model, action.context, action.domain);
351         if (action.res_id) {
352             dataset.ids.push(action.res_id);
353             dataset.index = 0;
354         }
355         this.dataset = dataset;
356         this.flags = this.action.flags || {};
357         if (action.res_model == 'board.board' && action.views.length == 1 && action.views) {
358             // Not elegant but allows to avoid form chrome (pager, save/new
359             // buttons, sidebar, ...) displaying
360             this.flags.search_view = this.flags.pager = this.flags.sidebar = this.flags.action_buttons = false;
361         }
362
363         // setup storage for session-wise menu hiding
364         if (this.session.hidden_menutips) {
365             return;
366         }
367         this.session.hidden_menutips = {}
368     },
369     /**
370      * Initializes the ViewManagerAction: sets up the searchview (if the
371      * searchview is enabled in the manager's action flags), calls into the
372      * parent to initialize the primary view and (if the VMA has a searchview)
373      * launches an initial search after both views are done rendering.
374      */
375     start: function() {
376         var self = this,
377             searchview_loaded,
378             search_defaults = {};
379         _.each(this.action.context, function (value, key) {
380             var match = /^search_default_(.*)$/.exec(key);
381             if (match) {
382                 search_defaults[match[1]] = value;
383             }
384         });
385         // init search view
386         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
387
388         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
389
390         var main_view_loaded = this._super();
391
392         var manager_ready = $.when(searchview_loaded, main_view_loaded);
393         if (searchview_loaded && this.action['auto_search'] !== false) {
394             // schedule auto_search
395             manager_ready.then(this.searchview.do_search);
396         }
397
398         this.$element.find('.oe_get_xml_view').click(function () {
399             // TODO: add search view?
400             $('<pre>').text(db.web.json_node_to_xml(
401                 self.views[self.active_view].controller.fields_view.arch, true))
402                     .dialog({ width: '95%'});
403         });
404         if (this.action.help && !this.flags.low_profile) {
405             var Users = new db.web.DataSet(self, 'res.users'),
406                 header = this.$element.find('.oe-view-manager-header');
407             header.delegate('blockquote button', 'click', function() {
408                 var $this = $(this);
409                 //noinspection FallthroughInSwitchStatementJS
410                 switch ($this.attr('name')) {
411                 case 'disable':
412                     Users.write(self.session.uid, {menu_tips:false});
413                 case 'hide':
414                     $this.closest('blockquote').hide();
415                     self.session.hidden_menutips[self.action.id] = true;
416                 }
417             });
418             if (!(self.action.id in self.session.hidden_menutips)) {
419                 Users.read_ids([this.session.uid], ['menu_tips'], function(users) {
420                     var user = users[0];
421                     if (!(user && user.id === self.session.uid)) {
422                         return;
423                     }
424                     header.find('blockquote').toggle(user.menu_tips);
425                 });
426             }
427         }
428
429         return manager_ready;
430     },
431     on_mode_switch: function (view_type) {
432         var self = this;
433         return $.when(
434             this._super(view_type),
435             this.shortcut_check(this.views[view_type])).then(function () {
436                 var view_id = self.views[self.active_view].controller.fields_view.view_id;
437                 self.$element.find('.oe_get_xml_view span').text(view_id);
438         });
439     },
440     shortcut_check : function(view) {
441         var self = this;
442         var grandparent = this.widget_parent && this.widget_parent.widget_parent;
443         // display shortcuts if on the first view for the action
444         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
445         if (!(grandparent instanceof db.web.WebClient) ||
446             !(view.view_type === this.views_src[0].view_type
447                 && view.view_id === this.views_src[0].view_id)) {
448             $shortcut_toggle.hide();
449             return;
450         }
451         $shortcut_toggle.removeClass('oe-shortcut-remove').show();
452         if (_(this.session.shortcuts).detect(function (shortcut) {
453                     return shortcut.res_id === self.session.active_id; })) {
454             $shortcut_toggle.addClass("oe-shortcut-remove");
455         }
456         this.shortcut_add_remove();
457     },
458     shortcut_add_remove: function() {
459         var self = this;
460         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
461         $shortcut_toggle
462             .unbind("click")
463             .click(function() {
464                 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
465                     $(self.session.shortcuts.binding).trigger('remove-current');
466                     $shortcut_toggle.removeClass("oe-shortcut-remove");
467                 } else {
468                     $(self.session.shortcuts.binding).trigger('add', {
469                         'user_id': self.session.uid,
470                         'res_id': self.session.active_id,
471                         'resource': 'ir.ui.menu',
472                         'name': self.action.name
473                     });
474                     $shortcut_toggle.addClass("oe-shortcut-remove");
475                 }
476             });
477     },
478     /**
479      * Intercept do_action resolution from children views
480      */
481     on_action_executed: function () {
482         return new db.web.DataSet(this, 'res.log')
483                 .call('get', [], this.do_display_log);
484     },
485     /**
486      * @param {Array<Object>} log_records
487      */
488     do_display_log: function (log_records) {
489         var self = this,
490             $logs = this.$element.find('ul.oe-view-manager-logs:first').empty();
491         _(log_records).each(function (record) {
492             $(_.sprintf('<li><a href="#">%s</a></li>', record.name))
493                 .appendTo($logs)
494                 .delegate('a', 'click', function (e) {
495                     self.do_action({
496                         type: 'ir.actions.act_window',
497                         res_model: record.res_model,
498                         res_id: record.res_id,
499                         // TODO: need to have an evaluated context here somehow
500                         //context: record.context,
501                         views: [[false, 'form']]
502                     });
503                     return false;
504                 });
505         });
506     }
507 });
508
509 db.web.Sidebar = db.web.Widget.extend({
510     init: function(parent, element_id) {
511         this._super(parent, element_id);
512         this.items = {};
513         this.sections = {};
514     },
515     start: function() {
516         this._super(this);
517         var self = this;
518         this.$element.html(db.web.qweb.render('Sidebar'));
519         this.$element.find(".toggle-sidebar").click(function(e) {
520             self.do_toggle();
521         });
522     },
523     add_toolbar: function(toolbar) {
524         var self = this;
525         _.each([['print', "Reports"], ['action', "Actions"], ['relate', "Links"]], function(type) {
526             var items = toolbar[type[0]];
527             if (items.length) {
528                 for (var i = 0; i < items.length; i++) {
529                     items[i] = {
530                         label: items[i]['name'],
531                         action: items[i],
532                         classname: 'oe_sidebar_' + type[0]
533                     }
534                 }
535                 self.add_section(type[0], type[1], items);
536             }
537         });
538     },
539     add_section: function(code, name, items) {
540         // For each section, we pass a name/label and optionally an array of items.
541         // If no items are passed, then the section will be created as a custom section
542         // returning back an element_id to be used by a custom controller.
543         // Else, the section is a standard section with items displayed as links.
544         // An item is a dictonary : {
545         //    label: label to be displayed for the link,
546         //    action: action to be launch when the link is clicked,
547         //    callback: a function to be executed when the link is clicked,
548         //    classname: optional dom class name for the line,
549         //    title: optional title for the link
550         // }
551         // Note: The item should have one action or/and a callback
552         var self = this,
553             section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
554         if (items) {
555             for (var i = 0; i < items.length; i++) {
556                 items[i].element_id = _.uniqueId(section_id + '_item_');
557                 this.items[items[i].element_id] = items[i];
558             }
559         }
560         var $section = $(db.web.qweb.render("Sidebar.section", {
561             section_id: section_id,
562             name: name,
563             classname: 'oe_sidebar_' + code,
564             items: items
565         }));
566         if (items) {
567             $section.find('a.oe_sidebar_action_a').click(function() {
568                 var item = self.items[$(this).attr('id')];
569                 if (item.callback) {
570                     item.callback();
571                 }
572                 if (item.action) {
573                     var ids = self.widget_parent.get_selected_ids();
574                     if (ids.length == 0) {
575                         //TODO: make prettier warning?
576                         $("<div />").text(_t("You must choose at least one record.")).dialog({
577                             title: _t("Warning"),
578                             modal: true
579                         });
580                         return false;
581                     }
582                     var additional_context = {
583                         active_id: ids[0],
584                         active_ids: ids,
585                         active_model: self.widget_parent.dataset.model
586                     };
587                     self.rpc("/web/action/load", {
588                         action_id: item.action.id,
589                         context: additional_context
590                     }, function(result) {
591                         result.result.context = _.extend(result.result.context || {},
592                             additional_context);
593                         result.result.flags = result.result.flags || {};
594                         result.result.flags.new_window = true;
595                         self.do_action(result.result);
596                     });
597                 }
598                 return false;
599             });
600         }
601         $section.appendTo(this.$element.find('div.sidebar-actions'));
602         this.sections[code] = $section;
603         return section_id;
604     },
605     do_fold: function() {
606         this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
607     },
608     do_unfold: function() {
609         this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
610     },
611     do_toggle: function() {
612         this.$element.toggleClass('open-sidebar closed-sidebar');
613     }
614 });
615
616 db.web.TranslateDialog = db.web.Dialog.extend({
617     dialog_title: _t("Translations"),
618     init: function(view) {
619         // TODO fme: should add the language to fields_view_get because between the fields view get
620         // and the moment the user opens the translation dialog, the user language could have been changed
621         this.view_language = view.session.user_context.lang;
622         this['on_button' + _t("Save")] = this.on_button_Save;
623         this['on_button' + _t("Close")] = this.on_button_Close;
624         this._super(view, {
625             width: '80%',
626             height: '80%'
627         });
628         this.view = view;
629         this.view_type = view.fields_view.type || '';
630         this.$fields_form = null;
631         this.$view_form = null;
632         this.$sidebar_form = null;
633         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
634         this.languages = null;
635         this.languages_loaded = $.Deferred();
636         (new db.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
637             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }, this.on_languages_loaded);
638     },
639     start: function() {
640         var self = this;
641         this._super();
642         $.when(this.languages_loaded).then(function() {
643             self.$element.html(db.web.qweb.render('TranslateDialog', { widget: self }));
644             self.$element.tabs();
645             if (!(self.view.translatable_fields && self.view.translatable_fields.length)) {
646                 self.hide_tabs('fields');
647                 self.select_tab('view');
648             }
649             self.$fields_form = self.$element.find('.oe_translation_form');
650             self.$fields_form.find('.oe_trad_field').change(function() {
651                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
652             });
653         });
654         return this;
655     },
656     on_languages_loaded: function(langs) {
657         this.languages = langs;
658         this.languages_loaded.resolve();
659     },
660     do_load_fields_values: function(callback) {
661         var self = this,
662             deffered = [];
663         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
664         _.each(self.languages, function(lg) {
665             var deff = $.Deferred();
666             deffered.push(deff);
667             var callback = function(values) {
668                 _.each(self.translatable_fields_keys, function(f) {
669                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
670                 });
671                 deff.resolve();
672             };
673             if (lg.code === self.view_language) {
674                 var values = {};
675                 _.each(self.translatable_fields_keys, function(field) {
676                     values[field] = self.view.fields[field].get_value();
677                 });
678                 callback([values]);
679             } else {
680                 self.rpc('/web/dataset/get', {
681                     model: self.view.dataset.model,
682                     ids: [self.view.datarecord.id],
683                     fields: self.translatable_fields_keys,
684                     context: self.view.dataset.get_context({
685                         'lang': lg.code
686                     })}, callback);
687             }
688         });
689         $.when.apply(null, deffered).then(callback);
690     },
691     show_tabs: function() {
692         for (var i = 0; i < arguments.length; i++) {
693             this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().show();
694         }
695     },
696     hide_tabs: function() {
697         for (var i = 0; i < arguments.length; i++) {
698             this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().hide();
699         }
700     },
701     select_tab: function(name) {
702         this.show_tabs(name);
703         var index = this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().index() - 1;
704         this.$element.tabs('select', index);
705     },
706     open: function(field) {
707         var self = this,
708             sup = this._super;
709         $.when(this.languages_loaded).then(function() {
710             if (self.view.translatable_fields && self.view.translatable_fields.length) {
711                 self.do_load_fields_values(function() {
712                     sup.call(self);
713                     if (field) {
714                         // TODO: focus and scroll to field
715                     }
716                 });
717             } else {
718                 sup.call(self);
719             }
720         });
721     },
722     on_button_Save: function() {
723         var trads = {},
724             self = this;
725         self.$fields_form.find('.oe_trad_field.touched').each(function() {
726             var field = $(this).attr('name').split('-');
727             if (!trads[field[0]]) {
728                 trads[field[0]] = {};
729             }
730             trads[field[0]][field[1]] = $(this).val();
731         });
732         _.each(trads, function(data, code) {
733             if (code === self.view_language) {
734                 _.each(data, function(value, field) {
735                     self.view.fields[field].set_value(value);
736                 });
737             } else {
738                 self.view.dataset.write(self.view.datarecord.id, data, { 'lang': code });
739             }
740         });
741         this.close();
742     },
743     on_button_Close: function() {
744         this.close();
745     }
746 });
747
748 db.web.View = db.web.Widget.extend(/** @lends db.web.View# */{
749     template: "EmptyComponent",
750     set_default_options: function(options) {
751         this.options = options || {};
752         _.defaults(this.options, {
753             // All possible views options should be defaulted here
754             sidebar_id: null,
755             sidebar: true,
756             action: null,
757             action_views_ids: {}
758         });
759     },
760     open_translate_dialog: function(field) {
761         if (!this.translate_dialog) {
762             this.translate_dialog = new db.web.TranslateDialog(this).start();
763         }
764         this.translate_dialog.open(field);
765     },
766     /**
767      * Fetches and executes the action identified by ``action_data``.
768      *
769      * @param {Object} action_data the action descriptor data
770      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
771      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
772      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
773      * @param {Object} [action_data.context=null] additional action context, to add to the current context
774      * @param {db.web.DataSet} dataset a dataset object used to communicate with the server
775      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
776      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
777      */
778     do_execute_action: function (action_data, dataset, record_id, on_closed) {
779         var self = this;
780         var result_handler = function () {
781             if (on_closed) { on_closed.apply(null, arguments); }
782             if (self.widget_parent && self.widget_parent.on_action_executed) {
783                 return self.widget_parent.on_action_executed.apply(null, arguments);
784             }
785         };
786         var handler = function (r) {
787             var action = r.result;
788             if (action && action.constructor == Object) {
789                 return self.rpc('/web/session/eval_domain_and_context', {
790                     contexts: [dataset.get_context(), action.context || {}, {
791                         active_id: record_id || false,
792                         active_ids: [record_id || false],
793                         active_model: dataset.model
794                     }],
795                     domains: []
796                 }).pipe(function (results) {
797                     action.context = results.context
798                     return self.do_action(action, result_handler);
799                 });
800             } else {
801                 return result_handler();
802             }
803         };
804
805         var context = new db.web.CompoundContext(dataset.get_context(), action_data.context || {});
806
807         if (action_data.special) {
808             return handler({result: {"type":"ir.actions.act_window_close"}});
809         } else if (action_data.type=="object") {
810             return dataset.call_button(action_data.name, [[record_id], context], handler);
811         } else if (action_data.type=="action") {
812             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context }, handler);
813         } else  {
814             return dataset.exec_workflow(record_id, action_data.name, handler);
815         }
816     },
817     /**
818      * Directly set a view to use instead of calling fields_view_get. This method must
819      * be called before start(). When an embedded view is set, underlying implementations
820      * of db.web.View must use the provided view instead of any other one.
821      *
822      * @param embedded_view A view.
823      */
824     set_embedded_view: function(embedded_view) {
825         this.embedded_view = embedded_view;
826         this.options.sidebar = false;
827     },
828     do_switch_view: function(view) {
829     },
830     do_search: function(view) {
831     },
832     set_common_sidebar_sections: function(sidebar) {
833         sidebar.add_section('customize', "Customize", [
834             {
835                 label: "Manage Views",
836                 callback: this.on_sidebar_manage_view,
837                 title: "Manage views of the current object"
838             }, {
839                 label: "Edit Workflow",
840                 callback: this.on_sidebar_edit_workflow,
841                 title: "Manage views of the current object",
842                 classname: 'oe_hide oe_sidebar_edit_workflow'
843             }, {
844                 label: "Customize Object",
845                 callback: this.on_sidebar_customize_object,
846                 title: "Manage views of the current object"
847             }
848         ]);
849         sidebar.add_section('other', "Other Options", [
850             {
851                 label: "Import",
852                 callback: this.on_sidebar_import
853             }, {
854                 label: "Export",
855                 callback: this.on_sidebar_export
856             }, {
857                 label: "Translate",
858                 callback: this.on_sidebar_translate,
859                 classname: 'oe_sidebar_translate oe_hide'
860             }, {
861                 label: "View Log",
862                 callback: this.on_sidebar_view_log,
863                 classname: 'oe_hide oe_sidebar_view_log'
864             }
865         ]);
866     },
867     on_sidebar_manage_view: function() {
868         if (this.fields_view && this.fields_view.arch) {
869             $('<xmp>' + db.web.json_node_to_xml(this.fields_view.arch, true) + '</xmp>').dialog({ width: '95%', height: 600});
870         } else {
871             this.notification.warn("Manage Views", "Could not find current view declaration");
872         }
873     },
874     on_sidebar_edit_workflow: function() {
875         console.log('Todo');
876     },
877     on_sidebar_customize_object: function() {
878         console.log('Todo');
879     },
880     on_sidebar_import: function() {
881         var import_view = new db.web.DataImport(this, this.dataset);
882         import_view.start();
883     },
884     on_sidebar_export: function() {
885         var export_view = new db.web.DataExport(this, this.dataset);
886         export_view.start();
887     },
888     on_sidebar_translate: function() {
889         this.open_translate_dialog();
890     },
891     on_sidebar_view_log: function() {
892     }
893 });
894
895 db.web.json_node_to_xml = function(node, single_quote, indent) {
896     // For debugging purpose, this function will convert a json node back to xml
897     // Maybe usefull for xml view editor
898
899     if (typeof(node) === 'string') {
900         return node;
901     }
902     else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
903         throw("Node a json node");
904     }
905     indent = indent || 0;
906     var sindent = new Array(indent + 1).join('\t'),
907         r = sindent + '<' + node.tag;
908     for (var attr in node.attrs) {
909         var vattr = node.attrs[attr];
910         if (typeof(vattr) !== 'string') {
911             // domains, ...
912             vattr = JSON.stringify(vattr);
913         }
914         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
915         if (single_quote) {
916             vattr = vattr.replace(/&quot;/g, "'");
917         }
918         r += ' ' + attr + '="' + vattr + '"';
919     }
920     if (node.children && node.children.length) {
921         r += '>\n';
922         var childs = [];
923         for (var i = 0, ii = node.children.length; i < ii; i++) {
924             childs.push(db.web.json_node_to_xml(node.children[i], single_quote, indent + 1));
925         }
926         r += childs.join('\n');
927         r += '\n' + sindent + '</' + node.tag + '>';
928         return r;
929     } else {
930         return r + '/>';
931     }
932 }
933
934 };
935
936 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: