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