[IMP] view: no message alias
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
7     _t = instance.web._t;
8
9 instance.web.ActionManager = instance.web.Widget.extend({
10     init: function(parent) {
11         this._super(parent);
12         this.inner_action = null;
13         this.inner_widget = null;
14         this.dialog = null;
15         this.dialog_widget = null;
16         this.breadcrumbs = [];
17         this.on('history_back', this, function() {
18             return this.history_back();
19         });
20     },
21     start: function() {
22         this._super.apply(this, arguments);
23         this.$el.on('click', 'a.oe_breadcrumb_item', this.on_breadcrumb_clicked);
24     },
25     dialog_stop: function () {
26         if (this.dialog) {
27             this.dialog.destroy();
28         }
29         this.dialog = null;
30     },
31     /**
32      * Add a new item to the breadcrumb
33      *
34      * If the title of an item is an array, the multiple title mode is in use.
35      * (eg: a widget with multiple views might need to display a title for each view)
36      * In multiple title mode, the show() callback can check the index it receives
37      * in order to detect which of its titles has been clicked on by the user.
38      *
39      * @param {Object} item breadcrumb item
40      * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
41      * @param {Function} [item.show] triggered whenever the widget should be shown back
42      * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
43      * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
44      * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
45      * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
46      */
47     push_breadcrumb: function(item) {
48         var last = this.breadcrumbs.slice(-1)[0];
49         if (last) {
50             last.hide();
51         }
52         var item = _.extend({
53             show: function(index) {
54                 this.widget.$el.show();
55             },
56             hide: function() {
57                 this.widget.$el.hide();
58             },
59             destroy: function() {
60                 this.widget.destroy();
61             },
62             get_title: function() {
63                 return this.title || this.widget.get('title');
64             }
65         }, item);
66         item.id = _.uniqueId('breadcrumb_');
67         this.breadcrumbs.push(item);
68     },
69     history_back: function() {
70         var last = this.breadcrumbs.slice(-1)[0];
71         if (!last) {
72             return false;
73         }
74         var title = last.get_title();
75         if (_.isArray(title) && title.length > 1) {
76             return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
77         } else if (this.breadcrumbs.length === 1) {
78             // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
79             return false;
80         } else {
81             var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
82             title = prev.get_title();
83             return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
84         }
85     },
86     on_breadcrumb_clicked: function(ev) {
87         var $e = $(ev.target);
88         var id = $e.data('id');
89         var index;
90         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
91             if (this.breadcrumbs[i].id == id) {
92                 index = i;
93                 break;
94             }
95         }
96         var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
97         this.select_breadcrumb(index, subindex);
98     },
99     select_breadcrumb: function(index, subindex) {
100         var next_item = this.breadcrumbs[index + 1];
101         if (next_item && next_item.on_reverse_breadcrumb) {
102             next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
103         }
104         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
105             if (i > index) {
106                 if (this.remove_breadcrumb(i) === false) {
107                     return false;
108                 }
109             }
110         }
111         var item = this.breadcrumbs[index];
112         item.show(subindex);
113         this.inner_widget = item.widget;
114         this.inner_action = item.action;
115         return true;
116     },
117     clear_breadcrumbs: function() {
118         for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
119             if (this.remove_breadcrumb(0) === false) {
120                 break;
121             }
122         }
123     },
124     remove_breadcrumb: function(index) {
125         var item = this.breadcrumbs.splice(index, 1)[0];
126         if (item) {
127             var dups = _.filter(this.breadcrumbs, function(it) {
128                 return item.widget === it.widget;
129             });
130             if (!dups.length) {
131                 if (this.getParent().has_uncommitted_changes()) {
132                     this.inner_widget = item.widget;
133                     this.inner_action = item.action;
134                     this.breadcrumbs.splice(index, 0, item);
135                     return false;
136                 } else {
137                     item.destroy();
138                 }
139             }
140         }
141         var last_widget = this.breadcrumbs.slice(-1)[0];
142         if (last_widget) {
143             this.inner_widget = last_widget.widget;
144             this.inner_action = last_widget.action;
145         }
146     },
147     get_title: function() {
148         var titles = [];
149         for (var i = 0; i < this.breadcrumbs.length; i += 1) {
150             var item = this.breadcrumbs[i];
151             var tit = item.get_title();
152             if (!_.isArray(tit)) {
153                 tit = [tit];
154             }
155             for (var j = 0; j < tit.length; j += 1) {
156                 var label = _.escape(tit[j]);
157                 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
158                     titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
159                 } else {
160                     titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
161                 }
162             }
163         }
164         return titles.join(' <span class="oe_fade">/</span> ');
165     },
166     do_push_state: function(state) {
167         state = state || {};
168         if (this.getParent() && this.getParent().do_push_state) {
169             if (this.inner_action) {
170                 if (this.inner_action._push_me === false) {
171                     // this action has been explicitly marked as not pushable
172                     return;
173                 }
174                 state['title'] = this.inner_action.name;
175                 if(this.inner_action.type == 'ir.actions.act_window') {
176                     state['model'] = this.inner_action.res_model;
177                 }
178                 if (this.inner_action.menu_id) {
179                     state['menu_id'] = this.inner_action.menu_id;
180                 }
181                 if (this.inner_action.id) {
182                     state['action'] = this.inner_action.id;
183                 } else if (this.inner_action.type == 'ir.actions.client') {
184                     state['action'] = this.inner_action.tag;
185                     var params = {};
186                     _.each(this.inner_action.params, function(v, k) {
187                         if(_.isString(v) || _.isNumber(v)) {
188                             params[k] = v;
189                         }
190                     });
191                     state = _.extend(params || {}, state);
192                 }
193             }
194             if(!this.dialog) {
195                 this.getParent().do_push_state(state);
196             }
197         }
198     },
199     do_load_state: function(state, warm) {
200         var self = this,
201             action_loaded;
202         if (state.action) {
203             if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
204                 var action_client = {
205                     type: "ir.actions.client",
206                     tag: state.action,
207                     params: state,
208                     _push_me: state._push_me,
209                 };
210                 this.null_action();
211                 action_loaded = this.do_action(action_client);
212             } else {
213                 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
214                 if (run_action) {
215                     this.null_action();
216                     action_loaded = this.do_action(state.action);
217                     $.when(action_loaded || null).done(function() {
218                         instance.webclient.menu.has_been_loaded.done(function() {
219                             if (self.inner_action && self.inner_action.id) {
220                                 instance.webclient.menu.open_action(self.inner_action.id);
221                             }
222                         });
223                     });
224                 }
225             }
226         } else if (state.model && state.id) {
227             // TODO handle context & domain ?
228             this.null_action();
229             var action = {
230                 res_model: state.model,
231                 res_id: state.id,
232                 type: 'ir.actions.act_window',
233                 views: [[false, 'form']]
234             };
235             action_loaded = this.do_action(action);
236         } else if (state.sa) {
237             // load session action
238             this.null_action();
239             action_loaded = this.rpc('/web/session/get_session_action',  {key: state.sa}).then(function(action) {
240                 if (action) {
241                     return self.do_action(action);
242                 }
243             });
244         }
245
246         $.when(action_loaded || null).done(function() {
247             if (self.inner_widget && self.inner_widget.do_load_state) {
248                 self.inner_widget.do_load_state(state, warm);
249             }
250         });
251     },
252     do_action: function(action, options) {
253         options = _.defaults(options || {}, {
254             clear_breadcrumbs: false,
255             on_reverse_breadcrumb: function() {},
256             on_close: function() {},
257             action_menu_id: null,
258         });
259         if (action === false) {
260             action = { type: 'ir.actions.act_window_close' };
261         } else if (_.isString(action) && instance.web.client_actions.contains(action)) {
262             var action_client = { type: "ir.actions.client", tag: action, params: {} };
263             return this.do_action(action_client, options);
264         } else if (_.isNumber(action) || _.isString(action)) {
265             var self = this;
266             return self.rpc("/web/action/load", { action_id: action }).then(function(result) {
267                 return self.do_action(result, options);
268             });
269         }
270
271         // Ensure context & domain are evaluated and can be manipulated/used
272         if (action.context) {
273             action.context = instance.web.pyeval.eval(
274                 'context', action.context);
275         }
276         if (action.domain) {
277             action.domain = instance.web.pyeval.eval(
278                 'domain', action.domain, action.context || {});
279         }
280
281         if (!action.type) {
282             console.error("No type for action", action);
283             return $.Deferred().reject();
284         }
285         var type = action.type.replace(/\./g,'_');
286         var popup = action.target === 'new';
287         var inline = action.target === 'inline' || action.target === 'inlineview';
288         action.flags = _.defaults(action.flags || {}, {
289             views_switcher : !popup && !inline,
290             search_view : !popup && !inline,
291             action_buttons : !popup && !inline,
292             sidebar : !popup && !inline,
293             pager : !popup && !inline,
294             display_title : !popup,
295             search_disable_custom_filters: action.context && action.context.search_disable_custom_filters
296         });
297         action.menu_id = options.action_menu_id;
298         if (!(type in this)) {
299             console.error("Action manager can't handle action of type " + action.type, action);
300             return $.Deferred().reject();
301         }
302         return this[type](action, options);
303     },
304     null_action: function() {
305         this.dialog_stop();
306         this.clear_breadcrumbs();
307     },
308     /**
309      *
310      * @param {Object} executor
311      * @param {Object} executor.action original action
312      * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
313      * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
314      * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
315      * @param {Object} options
316      * @return {*}
317      */
318     ir_actions_common: function(executor, options) {
319         if (this.inner_widget && executor.action.target !== 'new') {
320             if (this.getParent().has_uncommitted_changes()) {
321                 return $.Deferred().reject();
322             } else if (options.clear_breadcrumbs) {
323                 this.clear_breadcrumbs();
324             }
325         }
326         var widget = executor.widget();
327         if (executor.action.target === 'new') {
328             if (this.dialog_widget && !this.dialog_widget.isDestroyed()) {
329                 this.dialog_widget.destroy();
330             }
331             this.dialog_stop();
332             this.dialog = new instance.web.Dialog(this, {
333                 dialogClass: executor.klass,
334             });
335             this.dialog.on("closing", null, options.on_close);
336             this.dialog.dialog_title = executor.action.name;
337             if (widget instanceof instance.web.ViewManager) {
338                 _.extend(widget.flags, {
339                     $buttons: this.dialog.$buttons,
340                     footer_to_buttons: true,
341                 });
342             }
343             this.dialog_widget = widget;
344             this.dialog_widget.setParent(this.dialog);
345             var initialized = this.dialog_widget.appendTo(this.dialog.$el);
346             this.dialog.open();
347             return initialized;
348         } else  {
349             this.dialog_stop();
350             this.inner_action = executor.action;
351             this.inner_widget = widget;
352             executor.post_process(widget);
353             return this.inner_widget.appendTo(this.$el);
354         }
355     },
356     ir_actions_act_window: function (action, options) {
357         var self = this;
358
359         return this.ir_actions_common({
360             widget: function () { return new instance.web.ViewManagerAction(self, action); },
361             action: action,
362             klass: 'oe_act_window',
363             post_process: function (widget) { widget.add_breadcrumb(options.on_reverse_breadcrumb); }
364         }, options);
365     },
366     ir_actions_client: function (action, options) {
367         var self = this;
368         var ClientWidget = instance.web.client_actions.get_object(action.tag);
369
370         if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
371             var next;
372             if (next = ClientWidget(this, action)) {
373                 return this.do_action(next, options);
374             }
375             return $.when();
376         }
377
378         return this.ir_actions_common({
379             widget: function () { return new ClientWidget(self, action); },
380             action: action,
381             klass: 'oe_act_client',
382             post_process: function(widget) {
383                 self.push_breadcrumb({
384                     widget: widget,
385                     title: action.name,
386                     on_reverse_breadcrumb: options.on_reverse_breadcrumb,
387                 });
388                 if (action.tag !== 'reload') {
389                     self.do_push_state({});
390                 }
391             }
392         }, options);
393     },
394     ir_actions_act_window_close: function (action, options) {
395         if (!this.dialog) {
396             options.on_close();
397         }
398         this.dialog_stop();
399         return $.when();
400     },
401     ir_actions_server: function (action, options) {
402         var self = this;
403         this.rpc('/web/action/run', {
404             action_id: action.id,
405             context: action.context || {}
406         }).done(function (action) {
407             self.do_action(action, options)
408         });
409     },
410     ir_actions_report_xml: function(action, options) {
411         var self = this;
412         instance.web.blockUI();
413         return instance.web.pyeval.eval_domains_and_contexts({
414             contexts: [action.context],
415             domains: []
416         }).then(function(res) {
417             action = _.clone(action);
418             action.context = res.context;
419             var c = instance.webclient.crashmanager;
420             return $.Deferred(function (d) {
421                 self.session.get_file({
422                     url: '/web/report',
423                     data: {action: JSON.stringify(action)},
424                     complete: instance.web.unblockUI,
425                     success: function(){
426                         if (!self.dialog) {
427                             options.on_close();
428                         }
429                         self.dialog_stop();
430                         d.resolve();
431                     },
432                     error: function () {
433                         c.rpc_error.apply(c, arguments);
434                         d.reject();
435                     }
436                 })
437             });
438         });
439     },
440     ir_actions_act_url: function (action) {
441         window.open(action.url, action.target === 'self' ? '_self' : '_blank');
442         return $.when();
443     },
444 });
445
446 instance.web.ViewManager =  instance.web.Widget.extend({
447     template: "ViewManager",
448     init: function(parent, dataset, views, flags) {
449         this._super(parent);
450         this.url_states = {};
451         this.model = dataset ? dataset.model : undefined;
452         this.dataset = dataset;
453         this.searchview = null;
454         this.active_view = null;
455         this.views_src = _.map(views, function(x) {
456             if (x instanceof Array) {
457                 var view_type = x[1];
458                 var View = instance.web.views.get_object(view_type, true);
459                 var view_label = View ? View.prototype.display_name : (void 'nope');
460                 return {
461                     view_id: x[0],
462                     view_type: view_type,
463                     label: view_label,
464                     button_label: View ? _.str.sprintf(_t('%(view_type)s view'), {'view_type': (view_label || view_type)}) : (void 'nope'),
465                 };
466             } else {
467                 return x;
468             }
469         });
470         this.views = {};
471         this.flags = flags || {};
472         this.registry = instance.web.views;
473         this.views_history = [];
474         this.view_completely_inited = $.Deferred();
475     },
476     /**
477      * @returns {jQuery.Deferred} initial view loading promise
478      */
479     start: function() {
480         this._super();
481         var self = this;
482         this.$el.find('.oe_view_manager_switch a').click(function() {
483             self.switch_mode($(this).data('view-type'));
484         }).tipsy();
485         var views_ids = {};
486         _.each(this.views_src, function(view) {
487             self.views[view.view_type] = $.extend({}, view, {
488                 deferred : $.Deferred(),
489                 controller : null,
490                 options : _.extend({
491                     $buttons : self.$el.find('.oe_view_manager_buttons'),
492                     $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
493                     $pager : self.$el.find('.oe_view_manager_pager'),
494                     action : self.action,
495                     action_views_ids : views_ids
496                 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
497             });
498             views_ids[view.view_type] = view.view_id;
499         });
500         if (this.flags.views_switcher === false) {
501             this.$el.find('.oe_view_manager_switch').hide();
502         }
503         // If no default view defined, switch to the first one in sequence
504         var default_view = this.flags.default_view || this.views_src[0].view_type;
505         return this.switch_mode(default_view);
506     },
507     switch_mode: function(view_type, no_store, view_options) {
508         var self = this;
509         var view = this.views[view_type];
510         var view_promise;
511         var form = this.views['form'];
512         if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
513             self.trigger('switch_mode', view_type, no_store, view_options);
514             return $.Deferred().reject();
515         }
516         if (!no_store) {
517             this.views_history.push(view_type);
518         }
519         this.active_view = view_type;
520
521         if (!view.controller) {
522             view_promise = this.do_create_view(view_type);
523         } else if (this.searchview
524                 && self.flags.auto_search
525                 && view.controller.searchable !== false) {
526             this.searchview.ready.done(this.searchview.do_search);
527         }
528
529         if (this.searchview) {
530             this.searchview[(view.controller.searchable === false || this.searchview.options.hidden) ? 'hide' : 'show']();
531         }
532
533         this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
534         this.$el
535             .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
536             .parent().addClass('active');
537
538         return $.when(view_promise).done(function () {
539             _.each(_.keys(self.views), function(view_name) {
540                 var controller = self.views[view_name].controller;
541                 if (controller) {
542                     var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
543                     if (view_name === view_type) {
544                         container.show();
545                         controller.do_show(view_options || {});
546                     } else {
547                         container.hide();
548                         controller.do_hide();
549                     }
550                 }
551             });
552             self.trigger('switch_mode', view_type, no_store, view_options);
553         });
554     },
555     do_create_view: function(view_type) {
556         // Lazy loading of views
557         var self = this;
558         var view = this.views[view_type];
559         var viewclass = this.registry.get_object(view_type);
560         var options = _.clone(view.options);
561         if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
562             options.initial_mode = 'edit';
563         }
564         var controller = new viewclass(this, this.dataset, view.view_id, options);
565
566         controller.on('history_back', this, function() {
567             var am = self.getParent();
568             if (am && am.trigger) {
569                 return am.trigger('history_back');
570             }
571         });
572
573         controller.on("change:title", this, function() {
574             if (self.active_view === view_type) {
575                 self.set_title(controller.get('title'));
576             }
577         });
578
579         if (view.embedded_view) {
580             controller.set_embedded_view(view.embedded_view);
581         }
582         controller.on('switch_mode', self, this.switch_mode);
583         controller.on('previous_view', self, this.prev_view);
584         
585         var container = this.$el.find(".oe_view_manager_view_" + view_type);
586         var view_promise = controller.appendTo(container);
587         this.views[view_type].controller = controller;
588         this.views[view_type].deferred.resolve(view_type);
589         return $.when(view_promise).done(function() {
590             if (self.searchview
591                     && self.flags.auto_search
592                     && view.controller.searchable !== false) {
593                 self.searchview.ready.done(self.searchview.do_search);
594             } else {
595                 self.view_completely_inited.resolve();
596             }
597             self.trigger("controller_inited",view_type,controller);
598         });
599     },
600     set_title: function(title) {
601         this.$el.find('.oe_view_title_text:first').text(title);
602     },
603     add_breadcrumb: function(on_reverse_breadcrumb) {
604         var self = this;
605         var views = [this.active_view || this.views_src[0].view_type];
606         this.on('switch_mode', self, function(mode) {
607             var last = views.slice(-1)[0];
608             if (mode !== last) {
609                 if (mode !== 'form') {
610                     views.length = 0;
611                 }
612                 views.push(mode);
613             }
614         });
615         this.getParent().push_breadcrumb({
616             widget: this,
617             action: this.action,
618             show: function(index) {
619                 var view_to_select = views[index];
620                 var state = self.url_states[view_to_select];
621                 self.do_push_state(state || {});
622                 $.when(self.switch_mode(view_to_select)).done(function() {
623                     self.$el.show();
624                 });
625             },
626             get_title: function() {
627                 var id;
628                 var currentIndex;
629                 _.each(self.getParent().breadcrumbs, function(bc, i) {
630                     if (bc.widget === self) {
631                         currentIndex = i;
632                     }
633                 });
634                 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
635                 var titles = _.map(views, function(v) {
636                     var controller = self.views[v].controller;
637                     if (v === 'form') {
638                         id = controller.datarecord.id;
639                     }
640                     return controller.get('title');
641                 });
642                 if (next && next.action && next.action.res_id && self.dataset &&
643                     self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
644                     // If the current active view is a formview and the next item in the breadcrumbs
645                     // is an action on same object (model / res_id), then we omit the current formview's title
646                     titles.pop();
647                 }
648                 return titles;
649             },
650             on_reverse_breadcrumb: on_reverse_breadcrumb,
651         });
652     },
653     /**
654      * Returns to the view preceding the caller view in this manager's
655      * navigation history (the navigation history is appended to via
656      * switch_mode)
657      *
658      * @param {Object} [options]
659      * @param {Boolean} [options.created=false] resource was created
660      * @param {String} [options.default=null] view to switch to if no previous view
661      * @returns {$.Deferred} switching end signal
662      */
663     prev_view: function (options) {
664         options = options || {};
665         var current_view = this.views_history.pop();
666         var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
667         if (options.created && current_view === 'form' && previous_view === 'list') {
668             // APR special case: "If creation mode from list (and only from a list),
669             // after saving, go to page view (don't come back in list)"
670             return this.switch_mode('form');
671         } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
672             // APR special case: "If creation from dashboard, we have no previous view
673             return this.switch_mode('form');
674         }
675         return this.switch_mode(previous_view, true);
676     },
677     /**
678      * Sets up the current viewmanager's search view.
679      *
680      * @param {Number|false} view_id the view to use or false for a default one
681      * @returns {jQuery.Deferred} search view startup deferred
682      */
683     setup_search_view: function(view_id, search_defaults) {
684         var self = this;
685         if (this.searchview) {
686             this.searchview.destroy();
687         }
688         var options = {
689             hidden: this.flags.search_view === false,
690             disable_custom_filters: this.flags.search_disable_custom_filters,
691         };
692         this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, options);
693
694         this.searchview.on('search_data', self, this.do_searchview_search);
695         return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
696     },
697     do_searchview_search: function(domains, contexts, groupbys) {
698         var self = this,
699             controller = this.views[this.active_view].controller,
700             action_context = this.action.context || {};
701         instance.web.pyeval.eval_domains_and_contexts({
702             domains: [this.action.domain || []].concat(domains || []),
703             contexts: [action_context].concat(contexts || []),
704             group_by_seq: groupbys || []
705         }).done(function (results) {
706             self.dataset._model = new instance.web.Model(
707                 self.dataset.model, results.context, results.domain);
708             var groupby = results.group_by.length
709                         ? results.group_by
710                         : action_context.group_by;
711             if (_.isString(groupby)) {
712                 groupby = [groupby];
713             }
714             $.when(controller.do_search(results.domain, results.context, groupby || [])).then(function() {
715                 self.view_completely_inited.resolve();
716             });
717         });
718     },
719     /**
720      * Called when one of the view want to execute an action
721      */
722     on_action: function(action) {
723     },
724     on_create: function() {
725     },
726     on_remove: function() {
727     },
728     on_edit: function() {
729     },
730     /**
731      * Called by children view after executing an action
732      */
733     on_action_executed: function () {
734     },
735 });
736
737 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
738     template:"ViewManagerAction",
739     /**
740      * @constructs instance.web.ViewManagerAction
741      * @extends instance.web.ViewManager
742      *
743      * @param {instance.web.ActionManager} parent parent object/widget
744      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
745      */
746     init: function(parent, action) {
747         // dataset initialization will take the session from ``this``, so if we
748         // do not have it yet (and we don't, because we've not called our own
749         // ``_super()``) rpc requests will blow up.
750         var flags = action.flags || {};
751         if (!('auto_search' in flags)) {
752             flags.auto_search = action.auto_search !== false;
753         }
754         if (action.res_model == 'board.board' && action.view_mode === 'form') {
755             // Special case for Dashboards
756             _.extend(flags, {
757                 views_switcher : false,
758                 display_title : false,
759                 search_view : false,
760                 pager : false,
761                 sidebar : false,
762                 action_buttons : false
763             });
764         }
765         this._super(parent, null, action.views, flags);
766         this.session = parent.session;
767         this.action = action;
768         var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
769         if (action.res_id) {
770             dataset.ids.push(action.res_id);
771             dataset.index = 0;
772         }
773         this.dataset = dataset;
774     },
775     /**
776      * Initializes the ViewManagerAction: sets up the searchview (if the
777      * searchview is enabled in the manager's action flags), calls into the
778      * parent to initialize the primary view and (if the VMA has a searchview)
779      * launches an initial search after both views are done rendering.
780      */
781     start: function() {
782         var self = this,
783             searchview_loaded,
784             search_defaults = {};
785         _.each(this.action.context, function (value, key) {
786             var match = /^search_default_(.*)$/.exec(key);
787             if (match) {
788                 search_defaults[match[1]] = value;
789             }
790         });
791         // init search view
792         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
793
794         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
795
796         var main_view_loaded = this._super();
797
798         var manager_ready = $.when(searchview_loaded, main_view_loaded, this.view_completely_inited);
799
800         this.$el.find('.oe_debug_view').change(this.on_debug_changed);
801         this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
802         return manager_ready;
803     },
804     on_debug_changed: function (evt) {
805         var self = this,
806             $sel = $(evt.currentTarget),
807             $option = $sel.find('option:selected'),
808             val = $sel.val(),
809             current_view = this.views[this.active_view].controller;
810         switch (val) {
811             case 'fvg':
812                 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
813                 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
814                 break;
815             case 'tests':
816                 this.do_action({
817                     name: _t("JS Tests"),
818                     target: 'new',
819                     type : 'ir.actions.act_url',
820                     url: '/web/tests?mod=*'
821                 });
822                 break;
823             case 'perm_read':
824                 var ids = current_view.get_selected_ids();
825                 if (ids.length === 1) {
826                     this.dataset.call('perm_read', [ids]).done(function(result) {
827                         var dialog = new instance.web.Dialog(this, {
828                             title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
829                             width: 400
830                         }, QWeb.render('ViewManagerDebugViewLog', {
831                             perm : result[0],
832                             format : instance.web.format_value
833                         })).open();
834                     });
835                 }
836                 break;
837             case 'toggle_layout_outline':
838                 current_view.rendering_engine.toggle_layout_debugging();
839                 break;
840             case 'set_defaults':
841                 current_view.open_defaults_dialog();
842                 break;
843             case 'translate':
844                 this.do_action({
845                     name: _t("Technical Translation"),
846                     res_model : 'ir.translation',
847                     domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
848                     views: [[false, 'list'], [false, 'form']],
849                     type : 'ir.actions.act_window',
850                     view_type : "list",
851                     view_mode : "list"
852                 });
853                 break;
854             case 'fields':
855                 this.dataset.call('fields_get', [false, {}]).done(function (fields) {
856                     var $root = $('<dl>');
857                     _(fields).each(function (attributes, name) {
858                         $root.append($('<dt>').append($('<h4>').text(name)));
859                         var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
860                         _(attributes).each(function (def, name) {
861                             if (def instanceof Object) {
862                                 def = JSON.stringify(def);
863                             }
864                             $attrs
865                                 .append($('<dt>').text(name))
866                                 .append($('<dd style="white-space: pre-wrap;">').text(def));
867                         });
868                     });
869                     new instance.web.Dialog(self, {
870                         title: _.str.sprintf(_t("Model %s fields"),
871                                              self.dataset.model),
872                         width: '95%'}, $root).open();
873                 });
874                 break;
875             case 'edit_workflow':
876                 return this.do_action({
877                     res_model : 'workflow',
878                     domain : [['osv', '=', this.dataset.model]],
879                     views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
880                     type : 'ir.actions.act_window',
881                     view_type : 'list',
882                     view_mode : 'list'
883                 });
884                 break;
885             case 'edit':
886                 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
887                 break;
888             case 'manage_filters':
889                 this.do_action({
890                     res_model: 'ir.filters',
891                     views: [[false, 'list'], [false, 'form']],
892                     type: 'ir.actions.act_window',
893                     context: {
894                         search_default_my_filters: true,
895                         search_default_model_id: this.dataset.model
896                     }
897                 });
898                 break;
899             case 'print_workflow':
900                 if (current_view.get_selected_ids  && current_view.get_selected_ids().length == 1) {
901                     instance.web.blockUI();
902                     var action = {
903                         context: { active_ids: current_view.get_selected_ids() },
904                         report_name: "workflow.instance.graph",
905                         datas: {
906                             model: this.dataset.model,
907                             id: current_view.get_selected_ids()[0],
908                             nested: true,
909                         }
910                     };
911                     this.session.get_file({
912                         url: '/web/report',
913                         data: {action: JSON.stringify(action)},
914                         complete: instance.web.unblockUI
915                     });
916                 }
917                 break;
918             default:
919                 if (val) {
920                     console.log("No debug handler for ", val);
921                 }
922         }
923         evt.currentTarget.selectedIndex = 0;
924     },
925     do_edit_resource: function(model, id, action) {
926         var action = _.extend({
927             res_model : model,
928             res_id : id,
929             type : 'ir.actions.act_window',
930             view_type : 'form',
931             view_mode : 'form',
932             views : [[false, 'form']],
933             target : 'new',
934             flags : {
935                 action_buttons : true,
936                 form : {
937                     resize_textareas : true
938                 }
939             }
940         }, action || {});
941         this.do_action(action);
942     },
943     switch_mode: function (view_type, no_store, options) {
944         var self = this;
945
946         return $.when(this._super.apply(this, arguments)).done(function () {
947             var controller = self.views[self.active_view].controller;
948             self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
949                 view: controller,
950                 view_manager: self
951             }));
952             self.set_title();
953         });
954     },
955     do_create_view: function(view_type) {
956         var r = this._super.apply(this, arguments);
957         var view = this.views[view_type].controller;
958         view.set({ 'title': this.action.name });
959         return r;
960     },
961     get_action_manager: function() {
962         var cur = this;
963         while (cur = cur.getParent()) {
964             if (cur instanceof instance.web.ActionManager) {
965                 return cur;
966             }
967         }
968         return undefined;
969     },
970     set_title: function(title) {
971         this.$el.find('.oe_breadcrumb_title:first').html(this.get_action_manager().get_title());
972     },
973     do_push_state: function(state) {
974         if (this.getParent() && this.getParent().do_push_state) {
975             state["view_type"] = this.active_view;
976             this.url_states[this.active_view] = state;
977             this.getParent().do_push_state(state);
978         }
979     },
980     do_load_state: function(state, warm) {
981         var self = this,
982             defs = [];
983         if (state.view_type && state.view_type !== this.active_view) {
984             defs.push(
985                 this.views[this.active_view].deferred.then(function() {
986                     return self.switch_mode(state.view_type, true);
987                 })
988             );
989         } 
990
991         $.when(defs).done(function() {
992             self.views[self.active_view].controller.do_load_state(state, warm);
993         });
994     },
995 });
996
997 instance.web.Sidebar = instance.web.Widget.extend({
998     init: function(parent) {
999         var self = this;
1000         this._super(parent);
1001         var view = this.getParent();
1002         this.sections = [
1003             { 'name' : 'print', 'label' : _t('Print'), },
1004             { 'name' : 'other', 'label' : _t('More'), }
1005         ];
1006         this.items = {
1007             'print' : [],
1008             'other' : []
1009         };
1010         this.fileupload_id = _.uniqueId('oe_fileupload');
1011         $(window).on(this.fileupload_id, function() {
1012             var args = [].slice.call(arguments).slice(1);
1013             self.do_attachement_update(self.dataset, self.model_id,args);
1014             instance.web.unblockUI();
1015         });
1016     },
1017     start: function() {
1018         var self = this;
1019         this._super(this);
1020         this.redraw();
1021         this.$el.on('click','.oe_dropdown_menu li a', function(event) {
1022             var section = $(this).data('section');
1023             var index = $(this).data('index');
1024             var item = self.items[section][index];
1025             if (item.callback) {
1026                 item.callback.apply(self, [item]);
1027             } else if (item.action) {
1028                 self.on_item_action_clicked(item);
1029             } else if (item.url) {
1030                 return true;
1031             }
1032             event.preventDefault();
1033         });
1034     },
1035     redraw: function() {
1036         var self = this;
1037         self.$el.html(QWeb.render('Sidebar', {widget: self}));
1038
1039         // Hides Sidebar sections when item list is empty
1040         this.$('.oe_form_dropdown_section').each(function() {
1041             $(this).toggle(!!$(this).find('li').length);
1042         });
1043
1044         self.$("[title]").tipsy({
1045             'html': true,
1046             'delayIn': 500,
1047         })
1048     },
1049     /**
1050      * For each item added to the section:
1051      *
1052      * ``label``
1053      *     will be used as the item's name in the sidebar, can be html
1054      *
1055      * ``action``
1056      *     descriptor for the action which will be executed, ``action`` and
1057      *     ``callback`` should be exclusive
1058      *
1059      * ``callback``
1060      *     function to call when the item is clicked in the sidebar, called
1061      *     with the item descriptor as its first argument (so information
1062      *     can be stored as additional keys on the object passed to
1063      *     ``add_items``)
1064      *
1065      * ``classname`` (optional)
1066      *     ``@class`` set on the sidebar serialization of the item
1067      *
1068      * ``title`` (optional)
1069      *     will be set as the item's ``@title`` (tooltip)
1070      *
1071      * @param {String} section_code
1072      * @param {Array<{label, action | callback[, classname][, title]}>} items
1073      */
1074     add_items: function(section_code, items) {
1075         var self = this;
1076         if (items) {
1077             this.items[section_code].push.apply(this.items[section_code],items);
1078             this.redraw();
1079         }
1080     },
1081     add_toolbar: function(toolbar) {
1082         var self = this;
1083         _.each(['print','action','relate'], function(type) {
1084             var items = toolbar[type];
1085             if (items) {
1086                 for (var i = 0; i < items.length; i++) {
1087                     items[i] = {
1088                         label: items[i]['name'],
1089                         action: items[i],
1090                         classname: 'oe_sidebar_' + type
1091                     }
1092                 }
1093                 self.add_items(type=='print' ? 'print' : 'other', items);
1094             }
1095         });
1096     },
1097     on_item_action_clicked: function(item) {
1098         var self = this;
1099         self.getParent().sidebar_eval_context().done(function (sidebar_eval_context) {
1100             var ids = self.getParent().get_selected_ids();
1101             if (ids.length == 0) {
1102                 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1103                 return false;
1104             }
1105             var active_ids_context = {
1106                 active_id: ids[0],
1107                 active_ids: ids,
1108                 active_model: self.getParent().dataset.model
1109             }; 
1110             var c = instance.web.pyeval.eval('context',
1111                 new instance.web.CompoundContext(
1112                     sidebar_eval_context, active_ids_context));
1113             self.rpc("/web/action/load", {
1114                 action_id: item.action.id,
1115                 context: c
1116             }).done(function(result) {
1117                 result.context = new instance.web.CompoundContext(
1118                     result.context || {}, active_ids_context)
1119                         .set_eval_context(c);
1120                 result.flags = result.flags || {};
1121                 result.flags.new_window = true;
1122                 self.do_action(result, {
1123                     on_close: function() {
1124                         // reload view
1125                         self.getParent().reload();
1126                     },
1127                 });
1128             });
1129         });
1130     },
1131     do_attachement_update: function(dataset, model_id, args) {
1132         var self = this;
1133         this.dataset = dataset;
1134         this.model_id = model_id;
1135         if (args && args[0].error) {
1136             this.do_warn( instance.web.qweb.render('message_error_uploading'), args[0].error);
1137         }
1138         if (!model_id) {
1139             this.on_attachments_loaded([]);
1140         } else {
1141             var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1142             var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1143             ds.read_slice(['name', 'url', 'type', 'create_uid', 'create_date', 'write_uid', 'write_date'], {}).done(this.on_attachments_loaded);
1144         }
1145     },
1146     on_attachments_loaded: function(attachments) {
1147         var self = this;
1148         var items = [];
1149         var prefix = this.session.url('/web/binary/saveas', {model: 'ir.attachment', field: 'datas', filename_field: 'name'});
1150         _.each(attachments,function(a) {
1151             a.label = a.name;
1152             if(a.type === "binary") {
1153                 a.url = prefix  + '&id=' + a.id + '&t=' + (new Date().getTime());
1154             }
1155         });
1156         self.items['files'] = attachments;
1157         self.redraw();
1158         this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1159         this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1160     },
1161     on_attachment_changed: function(e) {
1162         var $e = $(e.target);
1163         if ($e.val() !== '') {
1164             this.$el.find('form.oe_form_binary_form').submit();
1165             $e.parent().find('input[type=file]').prop('disabled', true);
1166             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1167             this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1168             instance.web.blockUI();
1169         }
1170     },
1171     on_attachment_delete: function(e) {
1172         e.preventDefault();
1173         e.stopPropagation();
1174         var self = this;
1175         var $e = $(e.currentTarget);
1176         if (confirm(_t("Do you really want to delete this attachment ?"))) {
1177             (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).done(function() {
1178                 self.do_attachement_update(self.dataset, self.model_id);
1179             });
1180         }
1181     }
1182 });
1183
1184 instance.web.View = instance.web.Widget.extend({
1185     // name displayed in view switchers
1186     display_name: '',
1187     /**
1188      * Define a view type for each view to allow automatic call to fields_view_get.
1189      */
1190     view_type: undefined,
1191     init: function(parent, dataset, view_id, options) {
1192         this._super(parent);
1193         this.dataset = dataset;
1194         this.view_id = view_id;
1195         this.set_default_options(options);
1196     },
1197     start: function () {
1198         return this.load_view();
1199     },
1200     load_view: function(context) {
1201         var self = this;
1202         var view_loaded_def;
1203         if (this.embedded_view) {
1204             view_loaded_def = $.Deferred();
1205             $.async_when().done(function() {
1206                 view_loaded_def.resolve(self.embedded_view);
1207             });
1208         } else {
1209             if (! this.view_type)
1210                 console.warn("view_type is not defined", this);
1211             view_loaded_def = instance.web.fields_view_get({
1212                 "model": this.dataset._model,
1213                 "view_id": this.view_id,
1214                 "view_type": this.view_type,
1215                 "toolbar": !!this.options.$sidebar,
1216             });
1217         }
1218         return view_loaded_def.then(function(r) {
1219             self.fields_view = r;
1220             // add css classes that reflect the (absence of) access rights
1221             self.$el.addClass('oe_view')
1222                 .toggleClass('oe_cannot_create', !self.is_action_enabled('create'))
1223                 .toggleClass('oe_cannot_edit', !self.is_action_enabled('edit'))
1224                 .toggleClass('oe_cannot_delete', !self.is_action_enabled('delete'));
1225             return $.when(self.view_loading(r)).then(function() {
1226                 self.trigger('view_loaded', r);
1227             });
1228         });
1229     },
1230     view_loading: function(r) {
1231     },
1232     set_default_options: function(options) {
1233         this.options = options || {};
1234         _.defaults(this.options, {
1235             // All possible views options should be defaulted here
1236             $sidebar: null,
1237             sidebar_id: null,
1238             action: null,
1239             action_views_ids: {}
1240         });
1241     },
1242     /**
1243      * Fetches and executes the action identified by ``action_data``.
1244      *
1245      * @param {Object} action_data the action descriptor data
1246      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1247      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1248      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1249      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1250      * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1251      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1252      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1253      */
1254     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1255         var self = this;
1256         var result_handler = function () {
1257             if (on_closed) { on_closed.apply(null, arguments); }
1258             if (self.getParent() && self.getParent().on_action_executed) {
1259                 return self.getParent().on_action_executed.apply(null, arguments);
1260             }
1261         };
1262         var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1263
1264         var handler = function (action) {
1265             if (action && action.constructor == Object) {
1266                 var ncontext = new instance.web.CompoundContext(context);
1267                 if (record_id) {
1268                     ncontext.add({
1269                         active_id: record_id,
1270                         active_ids: [record_id],
1271                         active_model: dataset.model
1272                     });
1273                     if (("" + action.context).match(/\bactive_id\b/)) {
1274                         // Special case: when the context is evaluted using
1275                         // the active_id, we want to disable the custom filters.
1276                         ncontext.add({ search_disable_custom_filters: true });
1277                     }
1278                 }
1279                 ncontext.add(action.context || {});
1280                 action.context = ncontext;
1281                 return self.do_action(action, {
1282                     on_close: result_handler,
1283                 });
1284             } else {
1285                 self.do_action({"type":"ir.actions.act_window_close"});
1286                 return result_handler();
1287             }
1288         };
1289
1290         if (action_data.special === 'cancel') {
1291             return handler({"type":"ir.actions.act_window_close"});
1292         } else if (action_data.type=="object") {
1293             var args = [[record_id]], additional_args = [];
1294             if (action_data.args) {
1295                 try {
1296                     // Warning: quotes and double quotes problem due to json and xml clash
1297                     // Maybe we should force escaping in xml or do a better parse of the args array
1298                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1299                     args = args.concat(additional_args);
1300                 } catch(e) {
1301                     console.error("Could not JSON.parse arguments", action_data.args);
1302                 }
1303             }
1304             args.push(context);
1305             return dataset.call_button(action_data.name, args).then(handler);
1306         } else if (action_data.type=="action") {
1307             return this.rpc('/web/action/load', {
1308                 action_id: action_data.name,
1309                 context: instance.web.pyeval.eval('context', context),
1310                 do_not_eval: true
1311             }).then(handler);
1312         } else  {
1313             return dataset.exec_workflow(record_id, action_data.name).then(handler);
1314         }
1315     },
1316     /**
1317      * Directly set a view to use instead of calling fields_view_get. This method must
1318      * be called before start(). When an embedded view is set, underlying implementations
1319      * of instance.web.View must use the provided view instead of any other one.
1320      *
1321      * @param embedded_view A view.
1322      */
1323     set_embedded_view: function(embedded_view) {
1324         this.embedded_view = embedded_view;
1325     },
1326     do_show: function () {
1327         this.$el.show();
1328     },
1329     do_hide: function () {
1330         this.$el.hide();
1331     },
1332     is_active: function () {
1333         var manager = this.getParent();
1334         return !manager || !manager.active_view
1335              || manager.views[manager.active_view].controller === this;
1336     }, /**
1337      * Wraps fn to only call it if the current view is the active one. If the
1338      * current view is not active, doesn't call fn.
1339      *
1340      * fn can not return anything, as a non-call to fn can't return anything
1341      * either
1342      *
1343      * @param {Function} fn function to wrap in the active guard
1344      */
1345     guard_active: function (fn) {
1346         var self = this;
1347         return function () {
1348             if (self.is_active()) {
1349                 fn.apply(self, arguments);
1350             }
1351         }
1352     },
1353     do_push_state: function(state) {
1354         if (this.getParent() && this.getParent().do_push_state) {
1355             this.getParent().do_push_state(state);
1356         }
1357     },
1358     do_load_state: function(state, warm) {
1359     },
1360     /**
1361      * Switches to a specific view type
1362      */
1363     do_switch_view: function() { 
1364         this.trigger.apply(this, ['switch_mode'].concat(_.toArray(arguments)));
1365     },
1366     /**
1367      * Cancels the switch to the current view, switches to the previous one
1368      *
1369      * @param {Object} [options]
1370      * @param {Boolean} [options.created=false] resource was created
1371      * @param {String} [options.default=null] view to switch to if no previous view
1372      */
1373
1374     do_search: function(view) {
1375     },
1376     on_sidebar_export: function() {
1377         new instance.web.DataExport(this, this.dataset).open();
1378     },
1379     sidebar_eval_context: function () {
1380         return $.when({});
1381     },
1382     /**
1383      * Asks the view to reload itself, if the reloading is asynchronous should
1384      * return a {$.Deferred} indicating when the reloading is done.
1385      */
1386     reload: function () {
1387         return $.when();
1388     },
1389     /**
1390      * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1391      * An action is disabled by setting the corresponding attribute in the view's main element,
1392      * like: <form string="" create="false" edit="false" delete="false">
1393      */
1394     is_action_enabled: function(action) {
1395         var attrs = this.fields_view.arch.attrs;
1396         return (action in attrs) ? JSON.parse(attrs[action]) : true;
1397     },
1398     /**
1399      * insert alias into the dom
1400      */
1401     insert_alias: function ($dom) {
1402         var self = this;
1403         var context = this.options.action.context || {};
1404         if (context && context.alias) {
1405             new instance.web.Model('mail.alias').call("get_alias", [], {'alias': context.alias}).then(function (alias_ids) {
1406                 if (alias_ids.length) {
1407                     var $alias = $('<p class="oe_view_nocontent_alias"></p>');
1408                     var global = false;
1409                     var inc = 0;
1410                     _.each(alias_ids, function (alias_id) {
1411                         if (alias_id.email.match(/@.+/)) {
1412                             if (inc && global != alias_id.global) {
1413                                 $alias.append('<br/>' + _t("or"));
1414                                 global = alias_id.global;
1415                             }
1416                             $alias.append((inc? '<br/>': '') + '<a href="mailto:' + alias_id.email + '">' + alias_id.email + '</a>');
1417                             inc++;
1418                         }
1419                     })
1420                     $dom.append($alias);
1421                 }
1422             });
1423         }
1424     },
1425 });
1426
1427 /**
1428  * Performs a fields_view_get and apply postprocessing.
1429  * return a {$.Deferred} resolved with the fvg
1430  *
1431  * @param {Object} [args]
1432  * @param {String|Object} args.model instance.web.Model instance or string repr of the model
1433  * @param {null|Object} args.context context if args.model is a string
1434  * @param {null|Number} args.view_id id of the view to be loaded, default view if null
1435  * @param {null|String} args.view_type type of view to be loaded if view_id is null
1436  * @param {Boolean} [args.toolbar=false] get the toolbar definition
1437  */
1438 instance.web.fields_view_get = function(args) {
1439     function postprocess(fvg) {
1440         var doc = $.parseXML(fvg.arch).documentElement;
1441         fvg.arch = instance.web.xml_to_json(doc, (doc.nodeName.toLowerCase() !== 'kanban'));
1442         if ('id' in fvg.fields) {
1443             // Special case for id's
1444             var id_field = fvg.fields['id'];
1445             id_field.original_type = id_field.type;
1446             id_field.type = 'id';
1447         }
1448         _.each(fvg.fields, function(field) {
1449             _.each(field.views || {}, function(view) {
1450                 postprocess(view);
1451             });
1452         });
1453         return fvg;
1454     }
1455     args = _.defaults(args, {
1456         toolbar: false,
1457     });
1458     var model = args.model;
1459     if (typeof model === 'string') {
1460         model = new instance.web.Model(args.model, args.context);
1461     }
1462     return args.model.call('fields_view_get', [args.view_id, args.view_type, model.context(), args.toolbar]).then(function(fvg) {
1463         return postprocess(fvg);
1464     });
1465 };
1466
1467 instance.web.xml_to_json = function(node, strip_whitespace) {
1468     switch (node.nodeType) {
1469         case 9:
1470             return instance.web.xml_to_json(node.documentElement, strip_whitespace);
1471         case 3:
1472         case 4:
1473             return (strip_whitespace && node.data.trim() === '') ? undefined : node.data;
1474         case 1:
1475             var attrs = $(node).getAttributes();
1476             _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1477                 if (attrs[key]) {
1478                     try {
1479                         attrs[key] = JSON.parse(attrs[key]);
1480                     } catch(e) { }
1481                 }
1482             });
1483             return {
1484                 tag: node.tagName.toLowerCase(),
1485                 attrs: attrs,
1486                 children: _.compact(_.map(node.childNodes, function(node) {
1487                     return instance.web.xml_to_json(node, strip_whitespace);
1488                 })),
1489             }
1490     }
1491 }
1492 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1493     // For debugging purpose, this function will convert a json node back to xml
1494     indent = indent || 0;
1495     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1496         r = sindent + '<' + node.tag,
1497         cr = human_readable ? '\n' : '';
1498
1499     if (typeof(node) === 'string') {
1500         return sindent + node;
1501     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1502         throw new Error(
1503             _.str.sprintf(_t("Node [%s] is not a JSONified XML node"),
1504                           JSON.stringify(node)));
1505     }
1506     for (var attr in node.attrs) {
1507         var vattr = node.attrs[attr];
1508         if (typeof(vattr) !== 'string') {
1509             // domains, ...
1510             vattr = JSON.stringify(vattr);
1511         }
1512         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1513         if (human_readable) {
1514             vattr = vattr.replace(/&quot;/g, "'");
1515         }
1516         r += ' ' + attr + '="' + vattr + '"';
1517     }
1518     if (node.children && node.children.length) {
1519         r += '>' + cr;
1520         var childs = [];
1521         for (var i = 0, ii = node.children.length; i < ii; i++) {
1522             childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1523         }
1524         r += childs.join(cr);
1525         r += cr + sindent + '</' + node.tag + '>';
1526         return r;
1527     } else {
1528         return r + '/>';
1529     }
1530 };
1531 instance.web.xml_to_str = function(node) {
1532     if (window.XMLSerializer) {
1533         return (new XMLSerializer()).serializeToString(node);
1534     } else if (window.ActiveXObject) {
1535         return node.xml;
1536     } else {
1537         throw new Error(_t("Could not serialize XML"));
1538     }
1539 };
1540
1541 /**
1542  * Registry for all the main views
1543  */
1544 instance.web.views = new instance.web.Registry();
1545
1546 };
1547
1548 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: