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