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