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