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