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