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