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