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