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