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