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