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