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