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