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