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