[FIX] Sidebar dropdown
[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_cropdown_menu li a', function(event) {
743             var section = $(this).data('section');
744             var index = $(this).data('index');
745             var item = self.items[section][index];
746             if (item.callback) {
747                 item.callback.apply(self, [item]);
748             } else if (item.action) {
749                 self.on_item_action_clicked(item);
750             } else if (item.url) {
751                 return true;
752             }
753             event.preventDefault();
754         });
755     },
756     redraw: function() {
757         var self = this;
758         self.$element.html(QWeb.render('Sidebar', {widget: self}));
759
760         // Hides Sidebar sections when item list is empty
761         this.$('.oe_form_dropdown_section').each(function() {
762             $(this).toggle(!!$(this).find('li').length);
763         });
764     },
765     /**
766      * For each item added to the section:
767      *
768      * ``label``
769      *     will be used as the item's name in the sidebar, can be html
770      *
771      * ``action``
772      *     descriptor for the action which will be executed, ``action`` and
773      *     ``callback`` should be exclusive
774      *
775      * ``callback``
776      *     function to call when the item is clicked in the sidebar, called
777      *     with the item descriptor as its first argument (so information
778      *     can be stored as additional keys on the object passed to
779      *     ``add_items``)
780      *
781      * ``classname`` (optional)
782      *     ``@class`` set on the sidebar serialization of the item
783      *
784      * ``title`` (optional)
785      *     will be set as the item's ``@title`` (tooltip)
786      *
787      * @param {String} section_code
788      * @param {Array<{label, action | callback[, classname][, title]}>} items
789      */
790     add_items: function(section_code, items) {
791         var self = this;
792         if (items) {
793             this.items[section_code].push.apply(this.items[section_code],items);
794             this.redraw();
795         }
796     },
797     add_toolbar: function(toolbar) {
798         var self = this;
799         _.each(['print','action','relate'], function(type) {
800             var items = toolbar[type];
801             if (items) {
802                 for (var i = 0; i < items.length; i++) {
803                     items[i] = {
804                         label: items[i]['name'],
805                         action: items[i],
806                         classname: 'oe_sidebar_' + type
807                     }
808                 }
809                 self.add_items(type=='print' ? 'print' : 'other', items);
810             }
811         });
812     },
813     on_item_action_clicked: function(item) {
814         var self = this;
815         self.getParent().sidebar_context().then(function (context) {
816             var ids = self.getParent().get_selected_ids();
817             if (ids.length == 0) {
818                 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
819                 return false;
820             }
821             var additional_context = _.extend({
822                 active_id: ids[0],
823                 active_ids: ids,
824                 active_model: self.getParent().dataset.model
825             }, context);
826             self.rpc("/web/action/load", {
827                 action_id: item.action.id,
828                 context: additional_context
829             }, function(result) {
830                 result.result.context = _.extend(result.result.context || {},
831                     additional_context);
832                 result.result.flags = result.result.flags || {};
833                 result.result.flags.new_window = true;
834                 self.do_action(result.result, function () {
835                     // reload view
836                     self.getParent().reload();
837                 });
838             });
839         });
840     },
841     do_attachement_update: function(dataset, model_id) {
842         this.dataset = dataset;
843         this.model_id = model_id;
844         if (!model_id) {
845             this.on_attachments_loaded([]);
846         } else {
847             var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
848             var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
849             ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
850         }
851     },
852     on_attachments_loaded: function(attachments) {
853         var self = this;
854         var items = [];
855         var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
856         _.each(attachments,function(a) {
857             a.label = a.name;
858             if(a.type === "binary") {
859                 a.url = prefix  + a.id + '&t=' + (new Date().getTime());
860             }
861         });
862         self.items['files'] = attachments;
863         self.redraw();
864         this.$('.oe_sidebar_add_attachment .oe-binary-file').change(this.on_attachment_changed);
865         this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
866     },
867     on_attachment_changed: function(e) {
868         var $e = $(e.target);
869         if ($e.val() !== '') {
870             this.$element.find('form.oe-binary-form').submit();
871             $e.parent().find('input[type=file]').prop('disabled', true);
872             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
873             this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
874             $.blockUI();
875         }
876     },
877     on_attachment_delete: function(e) {
878         var self = this;
879         e.preventDefault();
880         e.stopPropagation();
881         var self = this;
882         var $e = $(e.currentTarget);
883         if (confirm(_t("Do you really want to delete this attachment ?"))) {
884             (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
885                 self.do_attachement_update(self.dataset, self.model_id);
886             });
887         }
888     }
889 });
890
891 instance.web.TranslateDialog = instance.web.Dialog.extend({
892     dialog_title: {toString: function () { return _t("Translations"); }},
893     init: function(view) {
894         // TODO fme: should add the language to fields_view_get because between the fields view get
895         // and the moment the user opens the translation dialog, the user language could have been changed
896         this.view_language = view.session.user_context.lang;
897         this['on_button' + _t("Save")] = this.on_button_Save;
898         this['on_button' + _t("Close")] = this.on_button_Close;
899         this._super(view, {
900             width: '80%',
901             height: '80%'
902         });
903         this.view = view;
904         this.view_type = view.fields_view.type || '';
905         this.$fields_form = null;
906         this.$view_form = null;
907         this.$sidebar_form = null;
908         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
909         this.languages = null;
910         this.languages_loaded = $.Deferred();
911         (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
912             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
913     },
914     start: function() {
915         var self = this;
916         this._super();
917         $.when(this.languages_loaded).then(function() {
918             self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
919             self.$fields_form = self.$element.find('.oe_translation_form');
920             self.$fields_form.find('.oe_trad_field').change(function() {
921                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
922             });
923         });
924         return this;
925     },
926     on_languages_loaded: function(langs) {
927         this.languages = langs;
928         this.languages_loaded.resolve();
929     },
930     do_load_fields_values: function(callback) {
931         var self = this,
932             deffered = [];
933         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
934         _.each(self.languages, function(lg) {
935             var deff = $.Deferred();
936             deffered.push(deff);
937             var callback = function(values) {
938                 _.each(self.translatable_fields_keys, function(f) {
939                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
940                 });
941                 deff.resolve();
942             };
943             if (lg.code === self.view_language) {
944                 var values = {};
945                 _.each(self.translatable_fields_keys, function(field) {
946                     values[field] = self.view.fields[field].get_value();
947                 });
948                 callback([values]);
949             } else {
950                 self.rpc('/web/dataset/get', {
951                     model: self.view.dataset.model,
952                     ids: [self.view.datarecord.id],
953                     fields: self.translatable_fields_keys,
954                     context: self.view.dataset.get_context({
955                         'lang': lg.code
956                     })}, callback);
957             }
958         });
959         $.when.apply(null, deffered).then(callback);
960     },
961     open: function(field) {
962         var self = this,
963             sup = this._super;
964         $.when(this.languages_loaded).then(function() {
965             if (self.view.translatable_fields && self.view.translatable_fields.length) {
966                 self.do_load_fields_values(function() {
967                     sup.call(self);
968                     if (field) {
969                         var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
970                         self.$element.scrollTo($field_input);
971                         $field_input.focus();
972                     }
973                 });
974             } else {
975                 sup.call(self);
976             }
977         });
978     },
979     on_button_Save: function() {
980         var trads = {},
981             self = this,
982             trads_mutex = new $.Mutex();
983         self.$fields_form.find('.oe_trad_field.touched').each(function() {
984             var field = $(this).attr('name').split('-');
985             if (!trads[field[0]]) {
986                 trads[field[0]] = {};
987             }
988             trads[field[0]][field[1]] = $(this).val();
989         });
990         _.each(trads, function(data, code) {
991             if (code === self.view_language) {
992                 _.each(data, function(value, field) {
993                     self.view.fields[field].set_value(value);
994                 });
995             }
996             trads_mutex.exec(function() {
997                 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
998             });
999         });
1000         this.close();
1001     },
1002     on_button_Close: function() {
1003         this.close();
1004     }
1005 });
1006
1007 instance.web.View = instance.web.Widget.extend({
1008     template: "EmptyComponent",
1009     // name displayed in view switchers
1010     display_name: '',
1011     /**
1012      * Define a view type for each view to allow automatic call to fields_view_get.
1013      */
1014     view_type: undefined,
1015     init: function(parent, dataset, view_id, options) {
1016         this._super(parent);
1017         this.dataset = dataset;
1018         this.view_id = view_id;
1019         this.set_default_options(options);
1020     },
1021     start: function() {
1022         return this.load_view();
1023     },
1024     load_view: function() {
1025         if (this.embedded_view) {
1026             var def = $.Deferred();
1027             var self = this;
1028             $.async_when().then(function() {def.resolve(self.embedded_view);});
1029             return def.pipe(this.on_loaded);
1030         } else {
1031             var context = new instance.web.CompoundContext(this.dataset.get_context());
1032             if (! this.view_type)
1033                 console.warn("view_type is not defined", this);
1034             return this.rpc("/web/view/load", {
1035                 "model": this.dataset.model,
1036                 "view_id": this.view_id,
1037                 "view_type": this.view_type,
1038                 toolbar: !!this.options.$sidebar,
1039                 context: context
1040                 }).pipe(this.on_loaded);
1041         }
1042     },
1043     /**
1044      * Called after a successful call to fields_view_get.
1045      * Must return a promise.
1046      */
1047     on_loaded: function(fields_view_get) {
1048     },
1049     set_default_options: function(options) {
1050         this.options = options || {};
1051         _.defaults(this.options, {
1052             // All possible views options should be defaulted here
1053             $sidebar: null,
1054             sidebar_id: null,
1055             action: null,
1056             action_views_ids: {}
1057         });
1058     },
1059     open_translate_dialog: function(field) {
1060         if (!this.translate_dialog) {
1061             this.translate_dialog = new instance.web.TranslateDialog(this).start();
1062         }
1063         this.translate_dialog.open(field);
1064     },
1065     /**
1066      * Fetches and executes the action identified by ``action_data``.
1067      *
1068      * @param {Object} action_data the action descriptor data
1069      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1070      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1071      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1072      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1073      * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1074      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1075      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1076      */
1077     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1078         var self = this;
1079         var result_handler = function () {
1080             if (on_closed) { on_closed.apply(null, arguments); }
1081             if (self.getParent() && self.getParent().on_action_executed) {
1082                 return self.getParent().on_action_executed.apply(null, arguments);
1083             }
1084         };
1085         var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1086
1087         var handler = function (r) {
1088             var action = r.result;
1089             if (action && action.constructor == Object) {
1090                 var ncontext = new instance.web.CompoundContext(context);
1091                 if (record_id) {
1092                     ncontext.add({
1093                         active_id: record_id,
1094                         active_ids: [record_id],
1095                         active_model: dataset.model
1096                     });
1097                 }
1098                 ncontext.add(action.context || {});
1099                 return self.rpc('/web/session/eval_domain_and_context', {
1100                     contexts: [ncontext],
1101                     domains: []
1102                 }).pipe(function (results) {
1103                     action.context = results.context;
1104                     /* niv: previously we were overriding once more with action_data.context,
1105                      * I assumed this was not a correct behavior and removed it
1106                      */
1107                     return self.do_action(action, result_handler);
1108                 }, null);
1109             } else {
1110                 return result_handler();
1111             }
1112         };
1113
1114         if (action_data.special) {
1115             return handler({result: {"type":"ir.actions.act_window_close"}});
1116         } else if (action_data.type=="object") {
1117             var args = [[record_id]], additional_args = [];
1118             if (action_data.args) {
1119                 try {
1120                     // Warning: quotes and double quotes problem due to json and xml clash
1121                     // Maybe we should force escaping in xml or do a better parse of the args array
1122                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1123                     args = args.concat(additional_args);
1124                 } catch(e) {
1125                     console.error("Could not JSON.parse arguments", action_data.args);
1126                 }
1127             }
1128             args.push(context);
1129             return dataset.call_button(action_data.name, args, handler);
1130         } else if (action_data.type=="action") {
1131             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1132         } else  {
1133             return dataset.exec_workflow(record_id, action_data.name, handler);
1134         }
1135     },
1136     /**
1137      * Directly set a view to use instead of calling fields_view_get. This method must
1138      * be called before start(). When an embedded view is set, underlying implementations
1139      * of instance.web.View must use the provided view instead of any other one.
1140      *
1141      * @param embedded_view A view.
1142      */
1143     set_embedded_view: function(embedded_view) {
1144         this.embedded_view = embedded_view;
1145     },
1146     do_show: function () {
1147         this.$element.show();
1148     },
1149     do_hide: function () {
1150         this.$element.hide();
1151     },
1152     do_push_state: function(state) {
1153         if (this.getParent() && this.getParent().do_push_state) {
1154             this.getParent().do_push_state(state);
1155         }
1156     },
1157     do_load_state: function(state, warm) {
1158     },
1159     /**
1160      * Switches to a specific view type
1161      *
1162      * @param {String} view view type to switch to
1163      */
1164     do_switch_view: function(view) { 
1165     },
1166     /**
1167      * Cancels the switch to the current view, switches to the previous one
1168      *
1169      * @param {Object} [options]
1170      * @param {Boolean} [options.created=false] resource was created
1171      * @param {String} [options.default=null] view to switch to if no previous view
1172      */
1173     do_prev_view: function (options) {
1174     },
1175     do_search: function(view) {
1176     },
1177     on_sidebar_import: function() {
1178         var import_view = new instance.web.DataImport(this, this.dataset);
1179         import_view.start();
1180     },
1181     on_sidebar_export: function() {
1182         var export_view = new instance.web.DataExport(this, this.dataset);
1183         export_view.start();
1184     },
1185     on_sidebar_translate: function() {
1186         return this.do_action({
1187             res_model : 'ir.translation',
1188             domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1189             views: [[false, 'list'], [false, 'form']],
1190             type : 'ir.actions.act_window',
1191             view_type : "list",
1192             view_mode : "list"
1193         });
1194     },
1195     sidebar_context: function () {
1196         return $.when();
1197     },
1198     /**
1199      * Asks the view to reload itself, if the reloading is asynchronous should
1200      * return a {$.Deferred} indicating when the reloading is done.
1201      */
1202     reload: function () {
1203         return $.when();
1204     }
1205 });
1206
1207 instance.web.xml_to_json = function(node) {
1208     switch (node.nodeType) {
1209         case 3:
1210         case 4:
1211             return node.data;
1212         break;
1213         case 1:
1214             var attrs = $(node).getAttributes();
1215             _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1216                 if (attrs[key]) {
1217                     try {
1218                         attrs[key] = JSON.parse(attrs[key]);
1219                     } catch(e) { }
1220                 }
1221             });
1222             return {
1223                 tag: node.tagName.toLowerCase(),
1224                 attrs: attrs,
1225                 children: _.map(node.childNodes, instance.web.xml_to_json)
1226             }
1227     }
1228 }
1229 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1230     // For debugging purpose, this function will convert a json node back to xml
1231     // Maybe useful for xml view editor
1232     indent = indent || 0;
1233     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1234         r = sindent + '<' + node.tag,
1235         cr = human_readable ? '\n' : '';
1236
1237     if (typeof(node) === 'string') {
1238         return sindent + node;
1239     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1240         throw("Node a json node");
1241     }
1242     for (var attr in node.attrs) {
1243         var vattr = node.attrs[attr];
1244         if (typeof(vattr) !== 'string') {
1245             // domains, ...
1246             vattr = JSON.stringify(vattr);
1247         }
1248         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1249         if (human_readable) {
1250             vattr = vattr.replace(/&quot;/g, "'");
1251         }
1252         r += ' ' + attr + '="' + vattr + '"';
1253     }
1254     if (node.children && node.children.length) {
1255         r += '>' + cr;
1256         var childs = [];
1257         for (var i = 0, ii = node.children.length; i < ii; i++) {
1258             childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1259         }
1260         r += childs.join(cr);
1261         r += cr + sindent + '</' + node.tag + '>';
1262         return r;
1263     } else {
1264         return r + '/>';
1265     }
1266 }
1267 instance.web.xml_to_str = function(node) {
1268     if (window.ActiveXObject) {
1269         return node.xml;
1270     } else {
1271         return (new XMLSerializer()).serializeToString(node);
1272     }
1273 }
1274 instance.web.str_to_xml = function(s) {
1275     if (window.DOMParser) {
1276         var dp = new DOMParser();
1277         var r = dp.parseFromString(s, "text/xml");
1278         if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1279             throw new Error("Could not parse string to xml");
1280         }
1281         return r;
1282     }
1283     var xDoc;
1284     try {
1285         xDoc = new ActiveXObject("MSXML2.DOMDocument");
1286     } catch (e) {
1287         throw new Error("Could not find a DOM Parser: " + e.message);
1288     }
1289     xDoc.async = false;
1290     xDoc.preserveWhiteSpace = true;
1291     xDoc.loadXML(s);
1292     return xDoc;
1293 }
1294
1295 /**
1296  * Registry for all the main views
1297  */
1298 instance.web.views = new instance.web.Registry();
1299
1300 };
1301
1302 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: