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