[FIX] No title on page trigered by an action
[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' || model === 'base.module.upgrade') {
127                 db.webclient.do_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])
436             ).then(function() {
437                 var controller = self.views[self.active_view].controller,
438                     fvg = controller.fields_view,
439                     view_id = (fvg && fvg.view_id) || '--';
440                 self.$element.find('.oe_get_xml_view span').text(view_id);
441                 if (!self.action.name && fvg) {
442                     self.$element.find('.oe_view_title').text(fvg.arch.attrs.string || fvg.name);
443                 }
444         });
445     },
446     shortcut_check : function(view) {
447         var self = this;
448         var grandparent = this.widget_parent && this.widget_parent.widget_parent;
449         // display shortcuts if on the first view for the action
450         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
451         if (!(grandparent instanceof db.web.WebClient) ||
452             !(view.view_type === this.views_src[0].view_type
453                 && view.view_id === this.views_src[0].view_id)) {
454             $shortcut_toggle.hide();
455             return;
456         }
457         $shortcut_toggle.removeClass('oe-shortcut-remove').show();
458         if (_(this.session.shortcuts).detect(function (shortcut) {
459                     return shortcut.res_id === self.session.active_id; })) {
460             $shortcut_toggle.addClass("oe-shortcut-remove");
461         }
462         this.shortcut_add_remove();
463     },
464     shortcut_add_remove: function() {
465         var self = this;
466         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
467         $shortcut_toggle
468             .unbind("click")
469             .click(function() {
470                 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
471                     $(self.session.shortcuts.binding).trigger('remove-current');
472                     $shortcut_toggle.removeClass("oe-shortcut-remove");
473                 } else {
474                     $(self.session.shortcuts.binding).trigger('add', {
475                         'user_id': self.session.uid,
476                         'res_id': self.session.active_id,
477                         'resource': 'ir.ui.menu',
478                         'name': self.action.name
479                     });
480                     $shortcut_toggle.addClass("oe-shortcut-remove");
481                 }
482             });
483     },
484     /**
485      * Intercept do_action resolution from children views
486      */
487     on_action_executed: function () {
488         return new db.web.DataSet(this, 'res.log')
489                 .call('get', [], this.do_display_log);
490     },
491     /**
492      * @param {Array<Object>} log_records
493      */
494     do_display_log: function (log_records) {
495         var self = this,
496             $logs = this.$element.find('ul.oe-view-manager-logs:first').empty();
497         _(log_records).each(function (record) {
498             $(_.sprintf('<li><a href="#">%s</a></li>', record.name))
499                 .appendTo($logs)
500                 .delegate('a', 'click', function (e) {
501                     self.do_action({
502                         type: 'ir.actions.act_window',
503                         res_model: record.res_model,
504                         res_id: record.res_id,
505                         // TODO: need to have an evaluated context here somehow
506                         //context: record.context,
507                         views: [[false, 'form']]
508                     });
509                     return false;
510                 });
511         });
512     }
513 });
514
515 db.web.Sidebar = db.web.Widget.extend({
516     init: function(parent, element_id) {
517         this._super(parent, element_id);
518         this.items = {};
519         this.sections = {};
520     },
521     start: function() {
522         this._super(this);
523         var self = this;
524         this.$element.html(db.web.qweb.render('Sidebar'));
525         this.$element.find(".toggle-sidebar").click(function(e) {
526             self.do_toggle();
527         });
528     },
529
530     call_default_on_sidebar: function(item) {
531         var func_name = 'on_sidebar_' + _.underscored(item.label);
532         var fn = this.widget_parent[func_name];
533         if(typeof fn === 'function') {
534             fn(item);
535         }
536     },
537
538     add_default_sections: function() {
539         this.add_section(_t('Customize'), 'customize');
540         this.add_items('customize', [
541             {
542                 label: _t("Manage Views"),
543                 callback: this.call_default_on_sidebar,
544                 title: _t("Manage views of the current object"),
545             }, {
546                 label: _t("Edit Workflow"),
547                 callback: this.call_default_on_sidebar,
548                 title: _t("Manage views of the current object"),
549                 classname: 'oe_hide oe_sidebar_edit_workflow'
550             }, {
551                 label: _t("Customize Object"),
552                 callback: this.call_default_on_sidebar,
553                 title: _t("Manage views of the current object"),
554             }
555         ]);
556
557         this.add_section(_t('Other Options'), 'other');
558         this.add_items('other', [ 
559             {
560                 label: _t("Import"),
561                 callback: this.call_default_on_sidebar,
562             }, {
563                 label: _t("Export"),
564                 callback: this.call_default_on_sidebar,
565             }, {
566                 label: _t("Translate"),
567                 callback: this.call_default_on_sidebar,
568                 classname: 'oe_sidebar_translate oe_hide'
569             }, {
570                 label: _t("View Log"),
571                 callback: this.call_default_on_sidebar,
572                 classname: 'oe_hide oe_sidebar_view_log'
573             }
574         ]);
575     },
576
577     add_toolbar: function(toolbar) {
578         var self = this;
579         _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
580             var items = toolbar[type[0]];
581             if (items.length) {
582                 for (var i = 0; i < items.length; i++) {
583                     items[i] = {
584                         label: items[i]['name'],
585                         action: items[i],
586                         classname: 'oe_sidebar_' + type[0]
587                     }
588                 }
589                 self.add_section(type[1], type[0]);
590                 self.add_items(type[0], items);
591             }
592         });
593     },
594     
595     add_section: function(name, code) {
596         if(!code) code = _.underscored(name);
597         var $section = this.sections[code];
598
599         if(!$section) {
600             section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
601             var $section = $(db.web.qweb.render("Sidebar.section", {
602                 section_id: section_id,
603                 name: name,
604                 classname: 'oe_sidebar_' + code,
605             }));
606             $section.appendTo(this.$element.find('div.sidebar-actions'));
607             this.sections[code] = $section;
608         }
609         return $section;
610     },
611
612     add_items: function(section_code, items) {
613         // An item is a dictonary : {
614         //    label: label to be displayed for the link,
615         //    action: action to be launch when the link is clicked,
616         //    callback: a function to be executed when the link is clicked,
617         //    classname: optional dom class name for the line,
618         //    title: optional title for the link
619         // }
620         // Note: The item should have one action or/and a callback
621         //
622
623         var self = this,
624             $section = this.add_section(_.titleize(section_code.replace('_', ' ')), section_code),
625             section_id = $section.attr('id');
626
627         if (items) {
628             for (var i = 0; i < items.length; i++) {
629                 items[i].element_id = _.uniqueId(section_id + '_item_');
630                 this.items[items[i].element_id] = items[i];
631             }
632
633             var $items = $(db.web.qweb.render("Sidebar.section.items", {items: items}));
634
635             $items.find('a.oe_sidebar_action_a').click(function() {
636                 var item = self.items[$(this).attr('id')];
637                 if (item.callback) {
638                     item.callback.apply(self, [item]);
639                 }
640                 if (item.action) {
641                     var ids = self.widget_parent.get_selected_ids();
642                     if (ids.length == 0) {
643                         //TODO: make prettier warning?
644                         $("<div />").text(_t("You must choose at least one record.")).dialog({
645                             title: _t("Warning"),
646                             modal: true
647                         });
648                         return false;
649                     }
650                     var additional_context = {
651                         active_id: ids[0],
652                         active_ids: ids,
653                         active_model: self.widget_parent.dataset.model
654                     };
655                     self.rpc("/web/action/load", {
656                         action_id: item.action.id,
657                         context: additional_context
658                     }, function(result) {
659                         result.result.context = _.extend(result.result.context || {},
660                             additional_context);
661                         result.result.flags = result.result.flags || {};
662                         result.result.flags.new_window = true;
663                         self.do_action(result.result);
664                     });
665                 }
666                 return false;
667             });
668         
669             var $ul = $section.find('ul');
670             if(!$ul.length) {
671                 $ul = $('<ul/>').appendTo($section);
672             }
673             $items.appendTo($ul);
674         }
675     },
676     do_fold: function() {
677         this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
678     },
679     do_unfold: function() {
680         this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
681     },
682     do_toggle: function() {
683         this.$element.toggleClass('open-sidebar closed-sidebar');
684     }
685 });
686
687 db.web.TranslateDialog = db.web.Dialog.extend({
688     dialog_title: _t("Translations"),
689     init: function(view) {
690         // TODO fme: should add the language to fields_view_get because between the fields view get
691         // and the moment the user opens the translation dialog, the user language could have been changed
692         this.view_language = view.session.user_context.lang;
693         this['on_button' + _t("Save")] = this.on_button_Save;
694         this['on_button' + _t("Close")] = this.on_button_Close;
695         this._super(view, {
696             width: '80%',
697             height: '80%'
698         });
699         this.view = view;
700         this.view_type = view.fields_view.type || '';
701         this.$fields_form = null;
702         this.$view_form = null;
703         this.$sidebar_form = null;
704         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
705         this.languages = null;
706         this.languages_loaded = $.Deferred();
707         (new db.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
708             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }, this.on_languages_loaded);
709     },
710     start: function() {
711         var self = this;
712         this._super();
713         $.when(this.languages_loaded).then(function() {
714             self.$element.html(db.web.qweb.render('TranslateDialog', { widget: self }));
715             self.$element.tabs();
716             if (!(self.view.translatable_fields && self.view.translatable_fields.length)) {
717                 self.hide_tabs('fields');
718                 self.select_tab('view');
719             }
720             self.$fields_form = self.$element.find('.oe_translation_form');
721             self.$fields_form.find('.oe_trad_field').change(function() {
722                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
723             });
724         });
725         return this;
726     },
727     on_languages_loaded: function(langs) {
728         this.languages = langs;
729         this.languages_loaded.resolve();
730     },
731     do_load_fields_values: function(callback) {
732         var self = this,
733             deffered = [];
734         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
735         _.each(self.languages, function(lg) {
736             var deff = $.Deferred();
737             deffered.push(deff);
738             var callback = function(values) {
739                 _.each(self.translatable_fields_keys, function(f) {
740                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
741                 });
742                 deff.resolve();
743             };
744             if (lg.code === self.view_language) {
745                 var values = {};
746                 _.each(self.translatable_fields_keys, function(field) {
747                     values[field] = self.view.fields[field].get_value();
748                 });
749                 callback([values]);
750             } else {
751                 self.rpc('/web/dataset/get', {
752                     model: self.view.dataset.model,
753                     ids: [self.view.datarecord.id],
754                     fields: self.translatable_fields_keys,
755                     context: self.view.dataset.get_context({
756                         'lang': lg.code
757                     })}, callback);
758             }
759         });
760         $.when.apply(null, deffered).then(callback);
761     },
762     show_tabs: function() {
763         for (var i = 0; i < arguments.length; i++) {
764             this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().show();
765         }
766     },
767     hide_tabs: function() {
768         for (var i = 0; i < arguments.length; i++) {
769             this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().hide();
770         }
771     },
772     select_tab: function(name) {
773         this.show_tabs(name);
774         var index = this.$element.find('ul.oe_translate_tabs li a[href$="' + arguments[i] + '"]').parent().index() - 1;
775         this.$element.tabs('select', index);
776     },
777     open: function(field) {
778         var self = this,
779             sup = this._super;
780         $.when(this.languages_loaded).then(function() {
781             if (self.view.translatable_fields && self.view.translatable_fields.length) {
782                 self.do_load_fields_values(function() {
783                     sup.call(self);
784                     if (field) {
785                         // TODO: focus and scroll to field
786                     }
787                 });
788             } else {
789                 sup.call(self);
790             }
791         });
792     },
793     on_button_Save: function() {
794         var trads = {},
795             self = this;
796         self.$fields_form.find('.oe_trad_field.touched').each(function() {
797             var field = $(this).attr('name').split('-');
798             if (!trads[field[0]]) {
799                 trads[field[0]] = {};
800             }
801             trads[field[0]][field[1]] = $(this).val();
802         });
803         _.each(trads, function(data, code) {
804             if (code === self.view_language) {
805                 _.each(data, function(value, field) {
806                     self.view.fields[field].set_value(value);
807                 });
808             } else {
809                 self.view.dataset.write(self.view.datarecord.id, data, { 'lang': code });
810             }
811         });
812         this.close();
813     },
814     on_button_Close: function() {
815         this.close();
816     }
817 });
818
819 db.web.View = db.web.Widget.extend(/** @lends db.web.View# */{
820     template: "EmptyComponent",
821     set_default_options: function(options) {
822         this.options = options || {};
823         _.defaults(this.options, {
824             // All possible views options should be defaulted here
825             sidebar_id: null,
826             sidebar: true,
827             action: null,
828             action_views_ids: {}
829         });
830     },
831     open_translate_dialog: function(field) {
832         if (!this.translate_dialog) {
833             this.translate_dialog = new db.web.TranslateDialog(this).start();
834         }
835         this.translate_dialog.open(field);
836     },
837     /**
838      * Fetches and executes the action identified by ``action_data``.
839      *
840      * @param {Object} action_data the action descriptor data
841      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
842      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
843      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
844      * @param {Object} [action_data.context=null] additional action context, to add to the current context
845      * @param {db.web.DataSet} dataset a dataset object used to communicate with the server
846      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
847      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
848      */
849     do_execute_action: function (action_data, dataset, record_id, on_closed) {
850         var self = this;
851         var result_handler = function () {
852             if (on_closed) { on_closed.apply(null, arguments); }
853             if (self.widget_parent && self.widget_parent.on_action_executed) {
854                 return self.widget_parent.on_action_executed.apply(null, arguments);
855             }
856         };
857         var handler = function (r) {
858             var action = r.result;
859             if (action && action.constructor == Object) {
860                 return self.rpc('/web/session/eval_domain_and_context', {
861                     contexts: [dataset.get_context(), action.context || {}, {
862                         active_id: record_id || false,
863                         active_ids: [record_id || false],
864                         active_model: dataset.model
865                     }],
866                     domains: []
867                 }).pipe(function (results) {
868                     if (!action_data.context) {
869                         action.context = results.context
870                     } else {
871                         action.context = new db.web.CompoundContext(
872                             results.context, action_data.context);
873                     }
874                     return self.do_action(action, result_handler);
875                 }, null);
876             } else {
877                 return result_handler();
878             }
879         };
880
881         var context = new db.web.CompoundContext(dataset.get_context(), action_data.context || {});
882
883         if (action_data.special) {
884             return handler({result: {"type":"ir.actions.act_window_close"}});
885         } else if (action_data.type=="object") {
886             return dataset.call_button(action_data.name, [[record_id], context], handler);
887         } else if (action_data.type=="action") {
888             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context }, handler);
889         } else  {
890             return dataset.exec_workflow(record_id, action_data.name, handler);
891         }
892     },
893     /**
894      * Directly set a view to use instead of calling fields_view_get. This method must
895      * be called before start(). When an embedded view is set, underlying implementations
896      * of db.web.View must use the provided view instead of any other one.
897      *
898      * @param embedded_view A view.
899      */
900     set_embedded_view: function(embedded_view) {
901         this.embedded_view = embedded_view;
902         this.options.sidebar = false;
903     },
904     do_switch_view: function(view) {
905     },
906     do_search: function(view) {
907     },
908
909     set_common_sidebar_sections: function(sidebar) {
910         sidebar.add_default_sections();
911     },
912     on_sidebar_manage_views: function() {
913         if (this.fields_view && this.fields_view.arch) {
914             $('<xmp>' + db.web.json_node_to_xml(this.fields_view.arch, true) + '</xmp>').dialog({ width: '95%', height: 600});
915         } else {
916             this.do_warn("Manage Views", "Could not find current view declaration");
917         }
918     },
919     on_sidebar_edit_workflow: function() {
920         console.log('Todo');
921     },
922     on_sidebar_customize_object: function() {
923         console.log('Todo');
924     },
925     on_sidebar_import: function() {
926         var import_view = new db.web.DataImport(this, this.dataset);
927         import_view.start();
928     },
929     on_sidebar_export: function() {
930         var export_view = new db.web.DataExport(this, this.dataset);
931         export_view.start();
932     },
933     on_sidebar_translate: function() {
934         this.open_translate_dialog();
935     },
936     on_sidebar_view_log: function() {
937     }
938 });
939
940 db.web.json_node_to_xml = function(node, single_quote, indent) {
941     // For debugging purpose, this function will convert a json node back to xml
942     // Maybe usefull for xml view editor
943
944     if (typeof(node) === 'string') {
945         return node;
946     }
947     else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
948         throw("Node a json node");
949     }
950     indent = indent || 0;
951     var sindent = new Array(indent + 1).join('\t'),
952         r = sindent + '<' + node.tag;
953     for (var attr in node.attrs) {
954         var vattr = node.attrs[attr];
955         if (typeof(vattr) !== 'string') {
956             // domains, ...
957             vattr = JSON.stringify(vattr);
958         }
959         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
960         if (single_quote) {
961             vattr = vattr.replace(/&quot;/g, "'");
962         }
963         r += ' ' + attr + '="' + vattr + '"';
964     }
965     if (node.children && node.children.length) {
966         r += '>\n';
967         var childs = [];
968         for (var i = 0, ii = node.children.length; i < ii; i++) {
969             childs.push(db.web.json_node_to_xml(node.children[i], single_quote, indent + 1));
970         }
971         r += childs.join('\n');
972         r += '\n' + sindent + '</' + node.tag + '>';
973         return r;
974     } else {
975         return r + '/>';
976     }
977 }
978
979 };
980
981 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: