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