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