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