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