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