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