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