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