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