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