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