[FIX] Do not omit current language value when saving translation box values
[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             controller.do_search(results.domain, results.context, groupby || []);
412         });
413     },
414     /**
415      * Event launched when a controller has been inited.
416      *
417      * @param {String} view_type type of view
418      * @param {String} view the inited controller
419      */
420     on_controller_inited: function(view_type, view) {
421     },
422     /**
423      * Called when one of the view want to execute an action
424      */
425     on_action: function(action) {
426     },
427     on_create: function() {
428     },
429     on_remove: function() {
430     },
431     on_edit: function() {
432     },
433     /**
434      * Called by children view after executing an action
435      */
436     on_action_executed: function () {
437     },
438     display_title: function () {
439         var view = this.views[this.active_view];
440         if (view) {
441             // ick
442             return view.controller.fields_view.arch.attrs.string;
443         }
444         return '';
445     }
446 });
447
448 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
449     template:"ViewManagerAction",
450     /**
451      * @constructs session.web.ViewManagerAction
452      * @extends session.web.ViewManager
453      *
454      * @param {session.web.ActionManager} parent parent object/widget
455      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
456      */
457     init: function(parent, action) {
458         // dataset initialization will take the session from ``this``, so if we
459         // do not have it yet (and we don't, because we've not called our own
460         // ``_super()``) rpc requests will blow up.
461         var flags = action.flags || {};
462         if (!('auto_search' in flags)) {
463             flags.auto_search = action.auto_search !== false;
464         }
465         if (action.res_model == 'board.board' && action.view_mode === 'form') {
466             // Special case for Dashboards
467             _.extend(flags, {
468                 views_switcher : false,
469                 display_title : false,
470                 search_view : false,
471                 pager : false,
472                 sidebar : false,
473                 action_buttons : false
474             });
475         }
476         this._super(parent, null, action.views, flags);
477         this.session = parent.session;
478         this.action = action;
479         var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
480         if (action.res_id) {
481             dataset.ids.push(action.res_id);
482             dataset.index = 0;
483         }
484         this.dataset = dataset;
485
486         // setup storage for session-wise menu hiding
487         if (this.session.hidden_menutips) {
488             return;
489         }
490         this.session.hidden_menutips = {}
491     },
492     /**
493      * Initializes the ViewManagerAction: sets up the searchview (if the
494      * searchview is enabled in the manager's action flags), calls into the
495      * parent to initialize the primary view and (if the VMA has a searchview)
496      * launches an initial search after both views are done rendering.
497      */
498     start: function() {
499         var self = this,
500             searchview_loaded,
501             search_defaults = {};
502         _.each(this.action.context, function (value, key) {
503             var match = /^search_default_(.*)$/.exec(key);
504             if (match) {
505                 search_defaults[match[1]] = value;
506             }
507         });
508         // init search view
509         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
510
511         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
512
513         var main_view_loaded = this._super();
514
515         var manager_ready = $.when(searchview_loaded, main_view_loaded);
516
517         this.$element.find('.oe_debug_view').change(this.on_debug_changed);
518
519         if (this.action.help && !this.flags.low_profile) {
520             var Users = new session.web.DataSet(self, 'res.users'),
521                 $tips = this.$element.find('.oe_view_manager_menu_tips');
522             $tips.delegate('blockquote button', 'click', function() {
523                 var $this = $(this);
524                 //noinspection FallthroughInSwitchStatementJS
525                 switch ($this.attr('name')) {
526                 case 'disable':
527                     Users.write(self.session.uid, {menu_tips:false});
528                 case 'hide':
529                     $this.closest('blockquote').hide();
530                     self.session.hidden_menutips[self.action.id] = true;
531                 }
532             });
533             if (!(self.action.id in self.session.hidden_menutips)) {
534                 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
535                     var user = users[0];
536                     if (!(user && user.id === self.session.uid)) {
537                         return;
538                     }
539                     $tips.find('blockquote').toggle(user.menu_tips);
540                 });
541             }
542         }
543
544         var $res_logs = this.$element.find('.oe-view-manager-logs:first');
545         $res_logs.delegate('a.oe-more-logs', 'click', function () {
546             $res_logs.removeClass('oe-folded');
547             return false;
548         }).delegate('a.oe-remove-everything', 'click', function () {
549             $res_logs.removeClass('oe-has-more').find('ul').empty();
550             $res_logs.css('display','none');
551             return false;
552         });
553         $res_logs.css('display','none');
554
555         return manager_ready;
556     },
557     on_debug_changed: function (evt) {
558         var self = this,
559             $sel = $(evt.currentTarget),
560             $option = $sel.find('option:selected'),
561             val = $sel.val(),
562             current_view = this.views[this.active_view].controller;
563         switch (val) {
564             case 'fvg':
565                 var dialog = new session.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
566                 $('<pre>').text(session.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
567                 break;
568             case 'perm_read':
569                 var ids = current_view.get_selected_ids();
570                 if (ids.length === 1) {
571                     this.dataset.call('perm_read', [ids]).then(function(result) {
572                         var dialog = new session.web.Dialog(this, {
573                             title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
574                             width: 400
575                         }, QWeb.render('ViewManagerDebugViewLog', {
576                             perm : result[0],
577                             format : session.web.format_value
578                         })).open();
579                     });
580                 }
581                 break;
582             case 'fields':
583                 this.dataset.call_and_eval(
584                         'fields_get', [false, {}], null, 1).then(function (fields) {
585                     var $root = $('<dl>');
586                     _(fields).each(function (attributes, name) {
587                         $root.append($('<dt>').append($('<h4>').text(name)));
588                         var $attrs = $('<dl>').appendTo(
589                                 $('<dd>').appendTo($root));
590                         _(attributes).each(function (def, name) {
591                             if (def instanceof Object) {
592                                 def = JSON.stringify(def);
593                             }
594                             $attrs
595                                 .append($('<dt>').text(name))
596                                 .append($('<dd style="white-space: pre-wrap;">').text(def));
597                         });
598                     });
599                     new session.web.Dialog(self, {
600                         title: _.str.sprintf(_t("Model %s fields"),
601                                              self.dataset.model),
602                         width: '95%'}, $root).open();
603                 });
604                 break;
605             case 'manage_views':
606                 if (current_view.fields_view && current_view.fields_view.arch) {
607                     var view_editor = new session.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
608                     view_editor.start();
609                 } else {
610                     this.do_warn(_t("Manage Views"),
611                             _t("Could not find current view declaration"));
612                 }
613                 break;
614             case 'edit_workflow':
615                 return this.do_action({
616                     res_model : 'workflow',
617                     domain : [['osv', '=', this.dataset.model]],
618                     views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
619                     type : 'ir.actions.act_window',
620                     view_type : 'list',
621                     view_mode : 'list'
622                 });
623                 break;
624             case 'edit':
625                 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
626                 break;
627             default:
628                 if (val) {
629                     console.log("No debug handler for ", val);
630                 }
631         }
632         evt.currentTarget.selectedIndex = 0;
633     },
634     do_edit_resource: function(model, id, action) {
635         var action = _.extend({
636             res_model : model,
637             res_id : id,
638             type : 'ir.actions.act_window',
639             view_type : 'form',
640             view_mode : 'form',
641             views : [[false, 'form']],
642             target : 'new',
643             flags : {
644                 action_buttons : true,
645                 form : {
646                     resize_textareas : true
647                 }
648             }
649         }, action || {});
650         this.do_action(action);
651     },
652     on_mode_switch: function (view_type, no_store) {
653         var self = this;
654
655         return $.when(this._super(view_type, no_store)).then(function () {
656             self.shortcut_check(self.views[view_type]);
657
658             self.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').removeClass('oe-has-more').css('display','none').find('ul').empty();
659
660             var controller = self.views[self.active_view].controller,
661                 fvg = controller.fields_view,
662                 view_id = (fvg && fvg.view_id) || '--';
663             self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
664                 view: controller,
665                 view_manager: self
666             }));
667             if (!self.action.name && fvg) {
668                 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
669             }
670
671             var $title = self.$element.find('.oe_view_title_text'),
672                 $search_prefix = $title.find('span.oe_searchable_view');
673             if (controller.searchable !== false && self.flags.search_view !== false) {
674                 if (!$search_prefix.length) {
675                     $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
676                 }
677             } else {
678                 $search_prefix.remove();
679             }
680         });
681     },
682     do_push_state: function(state) {
683         if (this.widget_parent && this.widget_parent.do_push_state) {
684             state["view_type"] = this.active_view;
685             this.widget_parent.do_push_state(state);
686         }
687     },
688     do_load_state: function(state, warm) {
689         var self = this,
690             defs = [];
691         if (state.view_type && state.view_type !== this.active_view) {
692             defs.push(
693                 this.views[this.active_view].deferred.pipe(function() {
694                     return self.on_mode_switch(state.view_type, true);
695                 })
696             );
697         } 
698
699         $.when(defs).then(function() {
700             self.views[self.active_view].controller.do_load_state(state, warm);
701         });
702     },
703     shortcut_check : function(view) {
704         var self = this;
705         var grandparent = this.widget_parent && this.widget_parent.widget_parent;
706         // display shortcuts if on the first view for the action
707         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
708         if (!this.action.name ||
709             !(view.view_type === this.views_src[0].view_type
710                 && view.view_id === this.views_src[0].view_id)) {
711             $shortcut_toggle.hide();
712             return;
713         }
714         $shortcut_toggle.removeClass('oe-shortcut-remove').show();
715         if (_(this.session.shortcuts).detect(function (shortcut) {
716                     return shortcut.res_id === self.session.active_id; })) {
717             $shortcut_toggle.addClass("oe-shortcut-remove");
718         }
719         this.shortcut_add_remove();
720     },
721     shortcut_add_remove: function() {
722         var self = this;
723         var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
724         $shortcut_toggle
725             .unbind("click")
726             .click(function() {
727                 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
728                     $(self.session.shortcuts.binding).trigger('remove-current');
729                     $shortcut_toggle.removeClass("oe-shortcut-remove");
730                 } else {
731                     $(self.session.shortcuts.binding).trigger('add', {
732                         'user_id': self.session.uid,
733                         'res_id': self.session.active_id,
734                         'resource': 'ir.ui.menu',
735                         'name': self.action.name
736                     });
737                     $shortcut_toggle.addClass("oe-shortcut-remove");
738                 }
739             });
740     },
741     /**
742      * Intercept do_action resolution from children views
743      */
744     on_action_executed: function () {
745         return new session.web.DataSet(this, 'res.log')
746                 .call('get', [], this.do_display_log);
747     },
748     /**
749      * @param {Array<Object>} log_records
750      */
751     do_display_log: function (log_records) {
752         var self = this;
753         var cutoff = 3;
754         var $logs = this.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').css('display', 'block');
755         var $logs_list = $logs.find('ul').empty();
756         $logs.toggleClass('oe-has-more', log_records.length > cutoff);
757         _(log_records.reverse()).each(function (record) {
758             var context = {};
759             if (record.context) {
760                 try { context = py.eval(record.context).toJSON(); }
761                 catch (e) { /* TODO: what do I do now? */ }
762             }
763             $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
764                 .appendTo($logs_list)
765                 .delegate('a', 'click', function () {
766                     self.do_action({
767                         type: 'ir.actions.act_window',
768                         res_model: record.res_model,
769                         res_id: record.res_id,
770                         // TODO: need to have an evaluated context here somehow
771                         context: context,
772                         views: [[context.view_id || false, 'form']]
773                     });
774                     return false;
775                 });
776         });
777     },
778     display_title: function () {
779         return this.action.name;
780     }
781 });
782
783 session.web.Sidebar = session.web.OldWidget.extend({
784     init: function(parent, element_id) {
785         this._super(parent, element_id);
786         this.items = {};
787         this.sections = {};
788     },
789     start: function() {
790         this._super(this);
791         var self = this;
792         this.$element.html(session.web.qweb.render('Sidebar'));
793         this.$element.find(".toggle-sidebar").click(function(e) {
794             self.do_toggle();
795         });
796     },
797     add_default_sections: function() {
798         var self = this,
799             view = this.widget_parent,
800             view_manager = view.widget_parent,
801             action = view_manager.action;
802         if (this.session.uid === 1) {
803             this.add_section(_t('Customize'), 'customize');
804             this.add_items('customize', [{
805                 label: _t("Translate"),
806                 callback: view.on_sidebar_translate,
807                 title: _t("Technical translation")
808             }]);
809         }
810
811         this.add_section(_t('Other Options'), 'other');
812         this.add_items('other', [
813             {
814                 label: _t("Import"),
815                 callback: view.on_sidebar_import
816             }, {
817                 label: _t("Export"),
818                 callback: view.on_sidebar_export
819             }
820         ]);
821     },
822
823     add_toolbar: function(toolbar) {
824         var self = this;
825         _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
826             var items = toolbar[type[0]];
827             if (items.length) {
828                 for (var i = 0; i < items.length; i++) {
829                     items[i] = {
830                         label: items[i]['name'],
831                         action: items[i],
832                         classname: 'oe_sidebar_' + type[0]
833                     }
834                 }
835                 self.add_section(type[1], type[0]);
836                 self.add_items(type[0], items);
837             }
838         });
839     },
840
841     add_section: function(name, code) {
842         if(!code) code = _.str.underscored(name);
843         var $section = this.sections[code];
844
845         if(!$section) {
846             var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
847             $section = $(session.web.qweb.render("Sidebar.section", {
848                 section_id: section_id,
849                 name: name,
850                 classname: 'oe_sidebar_' + code
851             }));
852             $section.appendTo(this.$element.find('div.sidebar-actions'));
853             this.sections[code] = $section;
854         }
855         return $section;
856     },
857     /**
858      * For each item added to the section:
859      *
860      * ``label``
861      *     will be used as the item's name in the sidebar
862      *
863      * ``action``
864      *     descriptor for the action which will be executed, ``action`` and
865      *     ``callback`` should be exclusive
866      *
867      * ``callback``
868      *     function to call when the item is clicked in the sidebar, called
869      *     with the item descriptor as its first argument (so information
870      *     can be stored as additional keys on the object passed to
871      *     ``add_items``)
872      *
873      * ``classname`` (optional)
874      *     ``@class`` set on the sidebar serialization of the item
875      *
876      * ``title`` (optional)
877      *     will be set as the item's ``@title`` (tooltip)
878      *
879      * @param {String} section_code
880      * @param {Array<{label, action | callback[, classname][, title]}>} items
881      */
882     add_items: function(section_code, items) {
883         var self = this,
884             $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
885             section_id = $section.attr('id');
886
887         if (items) {
888             for (var i = 0; i < items.length; i++) {
889                 items[i].element_id = _.uniqueId(section_id + '_item_');
890                 this.items[items[i].element_id] = items[i];
891             }
892
893             var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
894
895             $items.find('a.oe_sidebar_action_a').click(function() {
896                 var item = self.items[$(this).attr('id')];
897                 if (item.callback) {
898                     item.callback.apply(self, [item]);
899                 }
900                 if (item.action) {
901                     self.on_item_action_clicked(item);
902                 }
903                 return false;
904             });
905
906             var $ul = $section.find('ul');
907             if(!$ul.length) {
908                 $ul = $('<ul/>').appendTo($section);
909             }
910             $items.appendTo($ul);
911         }
912     },
913     on_item_action_clicked: function(item) {
914         var self = this;
915         self.widget_parent.sidebar_context().then(function (context) {
916             var ids = self.widget_parent.get_selected_ids();
917             if (ids.length == 0) {
918                 //TODO: make prettier warning?
919                 $("<div />").text(_t("You must choose at least one record.")).dialog({
920                     title: _t("Warning"),
921                     modal: true
922                 });
923                 return false;
924             }
925             var additional_context = _.extend({
926                 active_id: ids[0],
927                 active_ids: ids,
928                 active_model: self.widget_parent.dataset.model
929             }, context);
930             self.rpc("/web/action/load", {
931                 action_id: item.action.id,
932                 context: additional_context
933             }, function(result) {
934                 result.result.context = _.extend(result.result.context || {},
935                     additional_context);
936                 result.result.flags = result.result.flags || {};
937                 result.result.flags.new_window = true;
938                 self.do_action(result.result, function () {
939                     // reload view
940                     self.widget_parent.reload();
941                 });
942             });
943         });
944     },
945     do_fold: function() {
946         this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
947     },
948     do_unfold: function() {
949         this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
950     },
951     do_toggle: function() {
952         this.$element.toggleClass('open-sidebar closed-sidebar');
953     }
954 });
955
956 session.web.TranslateDialog = session.web.Dialog.extend({
957     dialog_title: {toString: function () { return _t("Translations"); }},
958     init: function(view) {
959         // TODO fme: should add the language to fields_view_get because between the fields view get
960         // and the moment the user opens the translation dialog, the user language could have been changed
961         this.view_language = view.session.user_context.lang;
962         this['on_button' + _t("Save")] = this.on_button_Save;
963         this['on_button' + _t("Close")] = this.on_button_Close;
964         this._super(view, {
965             width: '80%',
966             height: '80%'
967         });
968         this.view = view;
969         this.view_type = view.fields_view.type || '';
970         this.$fields_form = null;
971         this.$view_form = null;
972         this.$sidebar_form = null;
973         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
974         this.languages = null;
975         this.languages_loaded = $.Deferred();
976         (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
977             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
978     },
979     start: function() {
980         var self = this;
981         this._super();
982         $.when(this.languages_loaded).then(function() {
983             self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
984             self.$fields_form = self.$element.find('.oe_translation_form');
985             self.$fields_form.find('.oe_trad_field').change(function() {
986                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
987             });
988         });
989         return this;
990     },
991     on_languages_loaded: function(langs) {
992         this.languages = langs;
993         this.languages_loaded.resolve();
994     },
995     do_load_fields_values: function(callback) {
996         var self = this,
997             deffered = [];
998         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
999         _.each(self.languages, function(lg) {
1000             var deff = $.Deferred();
1001             deffered.push(deff);
1002             var callback = function(values) {
1003                 _.each(self.translatable_fields_keys, function(f) {
1004                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1005                 });
1006                 deff.resolve();
1007             };
1008             if (lg.code === self.view_language) {
1009                 var values = {};
1010                 _.each(self.translatable_fields_keys, function(field) {
1011                     values[field] = self.view.fields[field].get_value();
1012                 });
1013                 callback([values]);
1014             } else {
1015                 self.rpc('/web/dataset/get', {
1016                     model: self.view.dataset.model,
1017                     ids: [self.view.datarecord.id],
1018                     fields: self.translatable_fields_keys,
1019                     context: self.view.dataset.get_context({
1020                         'lang': lg.code
1021                     })}, callback);
1022             }
1023         });
1024         $.when.apply(null, deffered).then(callback);
1025     },
1026     open: function(field) {
1027         var self = this,
1028             sup = this._super;
1029         $.when(this.languages_loaded).then(function() {
1030             if (self.view.translatable_fields && self.view.translatable_fields.length) {
1031                 self.do_load_fields_values(function() {
1032                     sup.call(self);
1033                     if (field) {
1034                         var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1035                         self.$element.scrollTo($field_input);
1036                         $field_input.focus();
1037                     }
1038                 });
1039             } else {
1040                 sup.call(self);
1041             }
1042         });
1043     },
1044     on_button_Save: function() {
1045         var trads = {},
1046             self = this,
1047             trads_mutex = new $.Mutex();
1048         self.$fields_form.find('.oe_trad_field.touched').each(function() {
1049             var field = $(this).attr('name').split('-');
1050             if (!trads[field[0]]) {
1051                 trads[field[0]] = {};
1052             }
1053             trads[field[0]][field[1]] = $(this).val();
1054         });
1055         _.each(trads, function(data, code) {
1056             if (code === self.view_language) {
1057                 _.each(data, function(value, field) {
1058                     self.view.fields[field].set_value(value);
1059                 });
1060             }
1061             trads_mutex.exec(function() {
1062                 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1063             });
1064         });
1065         this.close();
1066     },
1067     on_button_Close: function() {
1068         this.close();
1069     }
1070 });
1071
1072 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
1073     template: "EmptyComponent",
1074     // name displayed in view switchers
1075     display_name: '',
1076     init: function(parent, dataset, view_id, options) {
1077         this._super(parent);
1078         this.dataset = dataset;
1079         this.view_id = view_id;
1080         this.set_default_options(options);
1081     },
1082     set_default_options: function(options) {
1083         this.options = options || {};
1084         _.defaults(this.options, {
1085             // All possible views options should be defaulted here
1086             sidebar_id: null,
1087             sidebar: true,
1088             action: null,
1089             action_views_ids: {}
1090         });
1091     },
1092     open_translate_dialog: function(field) {
1093         if (!this.translate_dialog) {
1094             this.translate_dialog = new session.web.TranslateDialog(this).start();
1095         }
1096         this.translate_dialog.open(field);
1097     },
1098     /**
1099      * Fetches and executes the action identified by ``action_data``.
1100      *
1101      * @param {Object} action_data the action descriptor data
1102      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1103      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1104      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1105      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1106      * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
1107      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1108      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1109      */
1110     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1111         var self = this;
1112         var result_handler = function () {
1113             if (on_closed) { on_closed.apply(null, arguments); }
1114             if (self.widget_parent && self.widget_parent.on_action_executed) {
1115                 return self.widget_parent.on_action_executed.apply(null, arguments);
1116             }
1117         };
1118         var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
1119
1120         var handler = function (r) {
1121             var action = r.result;
1122             if (action && action.constructor == Object) {
1123                 var ncontext = new session.web.CompoundContext(context);
1124                 if (record_id) {
1125                     ncontext.add({
1126                         active_id: record_id,
1127                         active_ids: [record_id],
1128                         active_model: dataset.model
1129                     });
1130                 }
1131                 ncontext.add(action.context || {});
1132                 return self.rpc('/web/session/eval_domain_and_context', {
1133                     contexts: [ncontext],
1134                     domains: []
1135                 }).pipe(function (results) {
1136                     action.context = results.context;
1137                     /* niv: previously we were overriding once more with action_data.context,
1138                      * I assumed this was not a correct behavior and removed it
1139                      */
1140                     return self.do_action(action, result_handler);
1141                 }, null);
1142             } else {
1143                 return result_handler();
1144             }
1145         };
1146
1147         if (action_data.special) {
1148             return handler({result: {"type":"ir.actions.act_window_close"}});
1149         } else if (action_data.type=="object") {
1150             var args = [[record_id]], additional_args = [];
1151             if (action_data.args) {
1152                 try {
1153                     // Warning: quotes and double quotes problem due to json and xml clash
1154                     // Maybe we should force escaping in xml or do a better parse of the args array
1155                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1156                     args = args.concat(additional_args);
1157                 } catch(e) {
1158                     console.error("Could not JSON.parse arguments", action_data.args);
1159                 }
1160             }
1161             args.push(context);
1162             return dataset.call_button(action_data.name, args, handler);
1163         } else if (action_data.type=="action") {
1164             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1165         } else  {
1166             return dataset.exec_workflow(record_id, action_data.name, handler);
1167         }
1168     },
1169     /**
1170      * Directly set a view to use instead of calling fields_view_get. This method must
1171      * be called before start(). When an embedded view is set, underlying implementations
1172      * of session.web.View must use the provided view instead of any other one.
1173      *
1174      * @param embedded_view A view.
1175      */
1176     set_embedded_view: function(embedded_view) {
1177         this.embedded_view = embedded_view;
1178         this.options.sidebar = false;
1179     },
1180     do_show: function () {
1181         this.$element.show();
1182     },
1183     do_hide: function () {
1184         this.$element.hide();
1185     },
1186     do_push_state: function(state) {
1187         if (this.widget_parent && this.widget_parent.do_push_state) {
1188             this.widget_parent.do_push_state(state);
1189         }
1190     },
1191     do_load_state: function(state, warm) {
1192     },
1193     /**
1194      * Switches to a specific view type
1195      *
1196      * @param {String} view view type to switch to
1197      */
1198     do_switch_view: function(view) { 
1199     },
1200     /**
1201      * Cancels the switch to the current view, switches to the previous one
1202      *
1203      * @param {Object} [options]
1204      * @param {Boolean} [options.created=false] resource was created
1205      * @param {String} [options.default=null] view to switch to if no previous view
1206      */
1207     do_prev_view: function (options) {
1208     },
1209     do_search: function(view) {
1210     },
1211     set_common_sidebar_sections: function(sidebar) {
1212         sidebar.add_default_sections();
1213     },
1214     on_sidebar_import: function() {
1215         var import_view = new session.web.DataImport(this, this.dataset);
1216         import_view.start();
1217     },
1218     on_sidebar_export: function() {
1219         var export_view = new session.web.DataExport(this, this.dataset);
1220         export_view.start();
1221     },
1222     on_sidebar_translate: function() {
1223         return this.do_action({
1224             res_model : 'ir.translation',
1225             domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1226             views: [[false, 'list'], [false, 'form']],
1227             type : 'ir.actions.act_window',
1228             view_type : "list",
1229             view_mode : "list"
1230         });
1231     },
1232     sidebar_context: function () {
1233         return $.when();
1234     },
1235     /**
1236      * Asks the view to reload itself, if the reloading is asynchronous should
1237      * return a {$.Deferred} indicating when the reloading is done.
1238      */
1239     reload: function () {
1240         return $.when();
1241     }
1242 });
1243
1244 session.web.json_node_to_xml = function(node, human_readable, indent) {
1245     // For debugging purpose, this function will convert a json node back to xml
1246     // Maybe useful for xml view editor
1247     indent = indent || 0;
1248     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1249         r = sindent + '<' + node.tag,
1250         cr = human_readable ? '\n' : '';
1251
1252     if (typeof(node) === 'string') {
1253         return sindent + node;
1254     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1255         throw("Node a json node");
1256     }
1257     for (var attr in node.attrs) {
1258         var vattr = node.attrs[attr];
1259         if (typeof(vattr) !== 'string') {
1260             // domains, ...
1261             vattr = JSON.stringify(vattr);
1262         }
1263         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1264         if (human_readable) {
1265             vattr = vattr.replace(/&quot;/g, "'");
1266         }
1267         r += ' ' + attr + '="' + vattr + '"';
1268     }
1269     if (node.children && node.children.length) {
1270         r += '>' + cr;
1271         var childs = [];
1272         for (var i = 0, ii = node.children.length; i < ii; i++) {
1273             childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1274         }
1275         r += childs.join(cr);
1276         r += cr + sindent + '</' + node.tag + '>';
1277         return r;
1278     } else {
1279         return r + '/>';
1280     }
1281 }
1282
1283 };
1284
1285 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: