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