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