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