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