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