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