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