1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
5 openerp.web.views = function(session) {
6 var QWeb = session.web.qweb,
10 * Registry for all the client actions key: tag value: widget
12 session.web.client_actions = new session.web.Registry();
15 * Registry for all the main views
17 session.web.views = new session.web.Registry();
19 session.web.ActionManager = session.web.OldWidget.extend({
20 init: function(parent) {
22 this.inner_action = null;
23 this.inner_viewmanager = null;
25 this.dialog_viewmanager = null;
26 this.client_widget = null;
29 return '<div id="' + this.element_id + '" style="height: 100%;"></div>';
31 dialog_stop: function () {
33 this.dialog_viewmanager.stop();
34 this.dialog_viewmanager = null;
39 content_stop: function () {
40 if (this.inner_viewmanager) {
41 this.inner_viewmanager.stop();
42 this.inner_viewmanager = null;
44 if (this.client_widget) {
45 this.client_widget.stop();
46 this.client_widget = null;
49 do_push_state: function(state) {
50 if (this.widget_parent && this.widget_parent.do_push_state) {
51 if (this.inner_action) {
52 state['model'] = this.inner_action.res_model;
53 if (this.inner_action.id) {
54 state['action_id'] = this.inner_action.id;
57 this.widget_parent.do_push_state(state);
60 do_load_state: function(state, warm) {
63 if (state.action_id) {
64 var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
67 action_loaded = this.do_action(state.action_id);
69 } else if (state.model && state.id) {
70 // TODO handle context & domain ?
73 res_model: state.model,
75 type: 'ir.actions.act_window',
76 views: [[false, 'page'], [false, 'form']]
78 action_loaded = this.do_action(action);
79 } else if (state.sa) {
80 // load session action
83 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
85 return self.do_action(action);
88 } else if (state.client_action) {
90 this.ir_actions_client(state.client_action);
93 $.when(action_loaded || null).then(function() {
94 if (self.inner_viewmanager) {
95 self.inner_viewmanager.do_load_state(state, warm);
99 do_action: function(action, on_close) {
100 if (_.isNumber(action)) {
102 return self.rpc("/web/action/load", { action_id: action }, function(result) {
103 self.do_action(result.result, on_close);
107 console.error("No type for action", action);
110 var type = action.type.replace(/\./g,'_');
111 var popup = action.target === 'new';
112 action.flags = _.extend({
113 views_switcher : !popup,
114 search_view : !popup,
115 action_buttons : !popup,
118 display_title : !popup
119 }, action.flags || {});
120 if (!(type in this)) {
121 console.error("Action manager can't handle action of type " + action.type, action);
124 return this[type](action, on_close);
126 null_action: function() {
130 ir_actions_act_window: function (action, on_close) {
132 if (_(['base.module.upgrade', 'base.setup.installer'])
133 .contains(action.res_model)) {
134 var old_close = on_close;
135 on_close = function () {
136 session.webclient.do_reload().then(old_close);
139 if (action.target === 'new') {
140 if (this.dialog == null) {
141 this.dialog = new session.web.Dialog(this, { width: '80%' });
143 this.dialog.on_close.add(on_close);
145 this.dialog_viewmanager.stop();
147 this.dialog.dialog_title = action.name;
148 this.dialog_viewmanager = new session.web.ViewManagerAction(this, action);
149 this.dialog_viewmanager.appendTo(this.dialog.$element);
153 return this.widget_parent.do_action(action, function () {
154 session.webclient.menu.open_menu(action.menu_id);
159 this.inner_action = action;
160 this.inner_viewmanager = new session.web.ViewManagerAction(this, action);
161 this.inner_viewmanager.appendTo(this.$element);
164 ir_actions_act_window_close: function (action, on_closed) {
165 if (!this.dialog && on_closed) {
170 ir_actions_server: function (action, on_closed) {
172 this.rpc('/web/action/run', {
173 action_id: action.id,
174 context: action.context || {}
175 }).then(function (action) {
176 self.do_action(action, on_closed)
179 ir_actions_client: function (action) {
182 var ClientWidget = session.web.client_actions.get_object(action.tag);
183 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this);
185 ir_actions_report_xml: function(action, on_closed) {
188 self.rpc("/web/session/eval_domain_and_context", {
189 contexts: [action.context],
191 }).then(function(res) {
192 action = _.clone(action);
193 action.context = res.context;
194 self.session.get_file({
196 data: {action: JSON.stringify(action)},
197 complete: $.unblockUI,
199 if (!self.dialog && on_closed) {
204 error: session.webclient.crashmanager.on_rpc_error
208 ir_actions_act_url: function (action) {
209 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
211 ir_ui_menu: function (action) {
212 this.widget_parent.do_action(action);
216 session.web.ViewManager = session.web.OldWidget.extend(/** @lends session.web.ViewManager# */{
217 template: "ViewManager",
219 * @constructs session.web.ViewManager
220 * @extends session.web.OldWidget
226 init: function(parent, dataset, views, flags) {
228 this.model = dataset ? dataset.model : undefined;
229 this.dataset = dataset;
230 this.searchview = null;
231 this.active_view = null;
232 this.views_src = _.map(views, function(x) {
233 if (x instanceof Array) {
234 var View = session.web.views.get_object(x[1], true);
238 label: View ? View.prototype.display_name : (void 'nope')
245 this.flags = flags || {};
246 this.registry = session.web.views;
247 this.views_history = [];
250 return session.web.qweb.render(this.template, {
252 prefix: this.element_id,
253 views: this.views_src});
256 * @returns {jQuery.Deferred} initial view loading promise
261 this.$element.find('.oe_vm_switch button').click(function() {
262 self.on_mode_switch($(this).data('view-type'));
265 _.each(this.views_src, function(view) {
266 self.views[view.view_type] = $.extend({}, view, {
267 deferred : $.Deferred(),
270 sidebar_id : self.element_id + '_sidebar_' + view.view_type,
271 action : self.action,
272 action_views_ids : views_ids
273 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
275 views_ids[view.view_type] = view.view_id;
277 if (this.flags.views_switcher === false) {
278 this.$element.find('.oe_vm_switch').hide();
280 // If no default view defined, switch to the first one in sequence
281 var default_view = this.flags.default_view || this.views_src[0].view_type;
282 return this.on_mode_switch(default_view);
285 * Asks the view manager to switch visualization mode.
287 * @param {String} view_type type of view to display
288 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
289 * @returns {jQuery.Deferred} new view loading promise
291 on_mode_switch: function(view_type, no_store) {
293 view = this.views[view_type],
296 return $.Deferred().reject();
299 this.views_history.push(view_type);
301 this.active_view = view_type;
303 if (!view.controller) {
304 // Lazy loading of views
305 var controllerclass = this.registry.get_object(view_type);
306 var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
307 if (view.embedded_view) {
308 controller.set_embedded_view(view.embedded_view);
310 controller.do_switch_view.add_last(this.on_mode_switch);
311 controller.do_prev_view.add_last(this.on_prev_view);
312 var container = $("#" + this.element_id + '_view_' + view_type);
313 view_promise = controller.appendTo(container);
314 this.views[view_type].controller = controller;
315 this.views[view_type].deferred.resolve(view_type);
316 $.when(view_promise).then(function() {
317 self.on_controller_inited(view_type, controller);
319 && self.flags.auto_search
320 && view.controller.searchable !== false) {
321 self.searchview.ready.then(self.searchview.do_search);
324 } else if (this.searchview
325 && self.flags.auto_search
326 && view.controller.searchable !== false) {
327 this.searchview.ready.then(this.searchview.do_search);
330 if (this.searchview) {
331 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
335 .find('.oe_vm_switch button').removeAttr('disabled')
336 .filter('[data-view-type="' + view_type + '"]')
337 .attr('disabled', true);
339 $.when(view_promise).then(function () {
340 _.each(_.keys(self.views), function(view_name) {
341 var controller = self.views[view_name].controller;
343 if (view_name === view_type) {
344 controller.do_show();
346 controller.do_hide();
351 self.$element.find('.oe_view_title_text:first').text(
352 self.display_title());
357 * Returns to the view preceding the caller view in this manager's
358 * navigation history (the navigation history is appended to via
361 * @param {Object} [options]
362 * @param {Boolean} [options.created=false] resource was created
363 * @param {String} [options.default=null] view to switch to if no previous view
364 * @returns {$.Deferred} switching end signal
366 on_prev_view: function (options) {
367 options = options || {};
368 var current_view = this.views_history.pop();
369 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
370 if (options.created && current_view === 'form' && previous_view === 'list') {
371 // APR special case: "If creation mode from list (and only from a list),
372 // after saving, go to page view (don't come back in list)"
373 return this.on_mode_switch('page');
374 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
375 // APR special case: "If creation from dashboard, we have no previous view
376 return this.on_mode_switch('page');
378 return this.on_mode_switch(previous_view, true);
381 * Sets up the current viewmanager's search view.
383 * @param {Number|false} view_id the view to use or false for a default one
384 * @returns {jQuery.Deferred} search view startup deferred
386 setup_search_view: function(view_id, search_defaults) {
388 if (this.searchview) {
389 this.searchview.stop();
391 this.searchview = new session.web.SearchView(
393 view_id, search_defaults, this.flags.search_view === false);
395 this.searchview.on_search.add(this.do_searchview_search);
396 return this.searchview.appendTo($("#" + this.element_id + "_search"));
398 do_searchview_search: function(domains, contexts, groupbys) {
400 controller = this.views[this.active_view].controller,
401 action_context = this.action.context || {};
402 this.rpc('/web/session/eval_domain_and_context', {
403 domains: [this.action.domain || []].concat(domains || []),
404 contexts: [action_context].concat(contexts || []),
405 group_by_seq: groupbys || []
406 }, function (results) {
407 self.dataset.context = results.context;
408 self.dataset.domain = results.domain;
409 var groupby = results.group_by.length
411 : action_context.group_by;
412 if (_.isString(groupby)) {
415 controller.do_search(results.domain, results.context, groupby || []);
419 * Event launched when a controller has been inited.
421 * @param {String} view_type type of view
422 * @param {String} view the inited controller
424 on_controller_inited: function(view_type, view) {
427 * Called when one of the view want to execute an action
429 on_action: function(action) {
431 on_create: function() {
433 on_remove: function() {
435 on_edit: function() {
438 * Called by children view after executing an action
440 on_action_executed: function () {
442 display_title: function () {
443 var view = this.views[this.active_view];
446 return view.controller.fields_view.arch.attrs.string;
452 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
453 template:"ViewManagerAction",
455 * @constructs session.web.ViewManagerAction
456 * @extends session.web.ViewManager
458 * @param {session.web.ActionManager} parent parent object/widget
459 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
461 init: function(parent, action) {
462 // dataset initialization will take the session from ``this``, so if we
463 // do not have it yet (and we don't, because we've not called our own
464 // ``_super()``) rpc requests will blow up.
465 var flags = action.flags || {};
466 if (!('auto_search' in flags)) {
467 flags.auto_search = action.auto_search !== false;
469 if (action.res_model == 'board.board' && action.view_mode === 'form') {
470 // Special case for Dashboards
472 views_switcher : false,
473 display_title : false,
477 action_buttons : false
480 this._super(parent, null, action.views, flags);
481 this.session = parent.session;
482 this.action = action;
483 var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
485 dataset.ids.push(action.res_id);
488 this.dataset = dataset;
490 // setup storage for session-wise menu hiding
491 if (this.session.hidden_menutips) {
494 this.session.hidden_menutips = {}
497 * Initializes the ViewManagerAction: sets up the searchview (if the
498 * searchview is enabled in the manager's action flags), calls into the
499 * parent to initialize the primary view and (if the VMA has a searchview)
500 * launches an initial search after both views are done rendering.
505 search_defaults = {};
506 _.each(this.action.context, function (value, key) {
507 var match = /^search_default_(.*)$/.exec(key);
509 search_defaults[match[1]] = value;
513 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
515 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
517 var main_view_loaded = this._super();
519 var manager_ready = $.when(searchview_loaded, main_view_loaded);
521 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
523 if (this.action.help && !this.flags.low_profile) {
524 var Users = new session.web.DataSet(self, 'res.users'),
525 $tips = this.$element.find('.oe_view_manager_menu_tips');
526 $tips.delegate('blockquote button', 'click', function() {
528 //noinspection FallthroughInSwitchStatementJS
529 switch ($this.attr('name')) {
531 Users.write(self.session.uid, {menu_tips:false});
533 $this.closest('blockquote').hide();
534 self.session.hidden_menutips[self.action.id] = true;
537 if (!(self.action.id in self.session.hidden_menutips)) {
538 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
540 if (!(user && user.id === self.session.uid)) {
543 $tips.find('blockquote').toggle(user.menu_tips);
548 var $res_logs = this.$element.find('.oe-view-manager-logs:first');
549 $res_logs.delegate('a.oe-more-logs', 'click', function () {
550 $res_logs.removeClass('oe-folded');
552 }).delegate('a.oe-remove-everything', 'click', function () {
553 $res_logs.removeClass('oe-has-more').find('ul').empty();
554 $res_logs.css('display','none');
557 $res_logs.css('display','none');
559 return manager_ready;
561 on_debug_changed: function (evt) {
563 $sel = $(evt.currentTarget),
564 $option = $sel.find('option:selected'),
566 current_view = this.views[this.active_view].controller;
569 var dialog = new session.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
570 $('<pre>').text(session.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
573 var ids = current_view.get_selected_ids();
574 if (ids.length === 1) {
575 this.dataset.call('perm_read', [ids]).then(function(result) {
576 var dialog = new session.web.Dialog(this, {
577 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
579 }, QWeb.render('ViewManagerDebugViewLog', {
581 format : session.web.format_value
587 this.dataset.call_and_eval(
588 'fields_get', [false, {}], null, 1).then(function (fields) {
589 var $root = $('<dl>');
590 _(fields).each(function (attributes, name) {
591 $root.append($('<dt>').append($('<h4>').text(name)));
592 var $attrs = $('<dl>').appendTo(
593 $('<dd>').appendTo($root));
594 _(attributes).each(function (def, name) {
595 if (def instanceof Object) {
596 def = JSON.stringify(def);
599 .append($('<dt>').text(name))
600 .append($('<dd style="white-space: pre-wrap;">').text(def));
603 new session.web.Dialog(self, {
604 title: _.str.sprintf(_t("Model %s fields"),
606 width: '95%'}, $root).open();
610 if (current_view.fields_view && current_view.fields_view.arch) {
611 var view_editor = new session.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
614 this.do_warn(_t("Manage Views"),
615 _t("Could not find current view declaration"));
618 case 'edit_workflow':
619 return this.do_action({
620 res_model : 'workflow',
621 domain : [['osv', '=', this.dataset.model]],
622 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
623 type : 'ir.actions.act_window',
629 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
633 console.log("No debug handler for ", val);
636 evt.currentTarget.selectedIndex = 0;
638 do_edit_resource: function(model, id, action) {
639 var action = _.extend({
642 type : 'ir.actions.act_window',
645 views : [[false, 'form']],
648 action_buttons : true,
650 resize_textareas : true
654 this.do_action(action);
656 on_mode_switch: function (view_type, no_store) {
659 return $.when(this._super(view_type, no_store)).then(function () {
660 self.shortcut_check(self.views[view_type]);
662 self.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').removeClass('oe-has-more').css('display','none').find('ul').empty();
664 var controller = self.views[self.active_view].controller,
665 fvg = controller.fields_view,
666 view_id = (fvg && fvg.view_id) || '--';
667 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
671 if (!self.action.name && fvg) {
672 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
675 var $title = self.$element.find('.oe_view_title_text'),
676 $search_prefix = $title.find('span.oe_searchable_view');
677 if (controller.searchable !== false && self.flags.search_view !== false) {
678 if (!$search_prefix.length) {
679 $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
682 $search_prefix.remove();
686 do_push_state: function(state) {
687 if (this.widget_parent && this.widget_parent.do_push_state) {
688 state["view_type"] = this.active_view;
689 this.widget_parent.do_push_state(state);
692 do_load_state: function(state, warm) {
695 if (state.view_type && state.view_type !== this.active_view) {
697 this.views[this.active_view].deferred.pipe(function() {
698 return self.on_mode_switch(state.view_type, true);
703 $.when(defs).then(function() {
704 self.views[self.active_view].controller.do_load_state(state, warm);
707 shortcut_check : function(view) {
709 var grandparent = this.widget_parent && this.widget_parent.widget_parent;
710 // display shortcuts if on the first view for the action
711 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
712 if (!this.action.name ||
713 !(view.view_type === this.views_src[0].view_type
714 && view.view_id === this.views_src[0].view_id)) {
715 $shortcut_toggle.hide();
718 $shortcut_toggle.removeClass('oe-shortcut-remove').show();
719 if (_(this.session.shortcuts).detect(function (shortcut) {
720 return shortcut.res_id === self.session.active_id; })) {
721 $shortcut_toggle.addClass("oe-shortcut-remove");
723 this.shortcut_add_remove();
725 shortcut_add_remove: function() {
727 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
731 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
732 $(self.session.shortcuts.binding).trigger('remove-current');
733 $shortcut_toggle.removeClass("oe-shortcut-remove");
735 $(self.session.shortcuts.binding).trigger('add', {
736 'user_id': self.session.uid,
737 'res_id': self.session.active_id,
738 'resource': 'ir.ui.menu',
739 'name': self.action.name
741 $shortcut_toggle.addClass("oe-shortcut-remove");
746 * Intercept do_action resolution from children views
748 on_action_executed: function () {
749 return new session.web.DataSet(this, 'res.log')
750 .call('get', [], this.do_display_log);
753 * @param {Array<Object>} log_records
755 do_display_log: function (log_records) {
758 var $logs = this.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').css('display', 'block');
759 var $logs_list = $logs.find('ul').empty();
760 $logs.toggleClass('oe-has-more', log_records.length > cutoff);
761 _(log_records.reverse()).each(function (record) {
763 if (record.context) {
764 try { context = py.eval(record.context).toJSON(); }
765 catch (e) { /* TODO: what do I do now? */ }
767 $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
768 .appendTo($logs_list)
769 .delegate('a', 'click', function () {
771 type: 'ir.actions.act_window',
772 res_model: record.res_model,
773 res_id: record.res_id,
774 // TODO: need to have an evaluated context here somehow
776 views: [[context.view_id || false, 'form']]
782 display_title: function () {
783 return this.action.name;
787 session.web.Sidebar = session.web.OldWidget.extend({
788 init: function(parent, element_id) {
789 this._super(parent, element_id);
796 this.$element.html(session.web.qweb.render('Sidebar'));
797 this.$element.find(".toggle-sidebar").click(function(e) {
801 add_default_sections: function() {
803 view = this.widget_parent,
804 view_manager = view.widget_parent,
805 action = view_manager.action;
806 if (this.session.uid === 1) {
807 this.add_section(_t('Customize'), 'customize');
808 this.add_items('customize', [{
809 label: _t("Translate"),
810 callback: view.on_sidebar_translate,
811 title: _t("Technical translation")
815 this.add_section(_t('Other Options'), 'other');
816 this.add_items('other', [
819 callback: view.on_sidebar_import
822 callback: view.on_sidebar_export
827 add_toolbar: function(toolbar) {
829 _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
830 var items = toolbar[type[0]];
832 for (var i = 0; i < items.length; i++) {
834 label: items[i]['name'],
836 classname: 'oe_sidebar_' + type[0]
839 self.add_section(type[1], type[0]);
840 self.add_items(type[0], items);
845 add_section: function(name, code) {
846 if(!code) code = _.str.underscored(name);
847 var $section = this.sections[code];
850 var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
851 $section = $(session.web.qweb.render("Sidebar.section", {
852 section_id: section_id,
854 classname: 'oe_sidebar_' + code
856 $section.appendTo(this.$element.find('div.sidebar-actions'));
857 this.sections[code] = $section;
862 * For each item added to the section:
865 * will be used as the item's name in the sidebar
868 * descriptor for the action which will be executed, ``action`` and
869 * ``callback`` should be exclusive
872 * function to call when the item is clicked in the sidebar, called
873 * with the item descriptor as its first argument (so information
874 * can be stored as additional keys on the object passed to
877 * ``classname`` (optional)
878 * ``@class`` set on the sidebar serialization of the item
880 * ``title`` (optional)
881 * will be set as the item's ``@title`` (tooltip)
883 * @param {String} section_code
884 * @param {Array<{label, action | callback[, classname][, title]}>} items
886 add_items: function(section_code, items) {
888 $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
889 section_id = $section.attr('id');
892 for (var i = 0; i < items.length; i++) {
893 items[i].element_id = _.uniqueId(section_id + '_item_');
894 this.items[items[i].element_id] = items[i];
897 var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
899 $items.find('a.oe_sidebar_action_a').click(function() {
900 var item = self.items[$(this).attr('id')];
902 item.callback.apply(self, [item]);
905 self.on_item_action_clicked(item);
910 var $ul = $section.find('ul');
912 $ul = $('<ul/>').appendTo($section);
914 $items.appendTo($ul);
917 on_item_action_clicked: function(item) {
919 self.widget_parent.sidebar_context().then(function (context) {
920 var ids = self.widget_parent.get_selected_ids();
921 if (ids.length == 0) {
922 //TODO: make prettier warning?
923 $("<div />").text(_t("You must choose at least one record.")).dialog({
924 title: _t("Warning"),
929 var additional_context = _.extend({
932 active_model: self.widget_parent.dataset.model
934 self.rpc("/web/action/load", {
935 action_id: item.action.id,
936 context: additional_context
937 }, function(result) {
938 result.result.context = _.extend(result.result.context || {},
940 result.result.flags = result.result.flags || {};
941 result.result.flags.new_window = true;
942 self.do_action(result.result, function () {
944 self.widget_parent.reload();
949 do_fold: function() {
950 this.$element.addClass('closed-sidebar').removeClass('open-sidebar');
952 do_unfold: function() {
953 this.$element.addClass('open-sidebar').removeClass('closed-sidebar');
955 do_toggle: function() {
956 this.$element.toggleClass('open-sidebar closed-sidebar');
960 session.web.TranslateDialog = session.web.Dialog.extend({
961 dialog_title: {toString: function () { return _t("Translations"); }},
962 init: function(view) {
963 // TODO fme: should add the language to fields_view_get because between the fields view get
964 // and the moment the user opens the translation dialog, the user language could have been changed
965 this.view_language = view.session.user_context.lang;
966 this['on_button_' + _t("Save")] = this.on_btn_save;
967 this['on_button_' + _t("Close")] = this.on_btn_close;
973 this.view_type = view.fields_view.type || '';
974 this.$fields_form = null;
975 this.$view_form = null;
976 this.$sidebar_form = null;
977 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
978 this.languages = null;
979 this.languages_loaded = $.Deferred();
980 (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
981 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
986 $.when(this.languages_loaded).then(function() {
987 self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
988 self.$fields_form = self.$element.find('.oe_translation_form');
989 self.$fields_form.find('.oe_trad_field').change(function() {
990 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
995 on_languages_loaded: function(langs) {
996 this.languages = langs;
997 this.languages_loaded.resolve();
999 do_load_fields_values: function(callback) {
1002 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1003 _.each(self.languages, function(lg) {
1004 var deff = $.Deferred();
1005 deffered.push(deff);
1006 var callback = function(values) {
1007 _.each(self.translatable_fields_keys, function(f) {
1008 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1012 if (lg.code === self.view_language) {
1014 _.each(self.translatable_fields_keys, function(field) {
1015 values[field] = self.view.fields[field].get_value();
1019 self.rpc('/web/dataset/get', {
1020 model: self.view.dataset.model,
1021 ids: [self.view.datarecord.id],
1022 fields: self.translatable_fields_keys,
1023 context: self.view.dataset.get_context({
1028 $.when.apply(null, deffered).then(callback);
1030 open: function(field) {
1033 $.when(this.languages_loaded).then(function() {
1034 if (self.view.translatable_fields && self.view.translatable_fields.length) {
1035 self.do_load_fields_values(function() {
1038 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1039 self.$element.scrollTo($field_input);
1040 $field_input.focus();
1048 on_btn_save: function() {
1051 trads_mutex = new $.Mutex();
1052 self.$fields_form.find('.oe_trad_field.touched').each(function() {
1053 var field = $(this).attr('name').split('-');
1054 if (!trads[field[0]]) {
1055 trads[field[0]] = {};
1057 trads[field[0]][field[1]] = $(this).val();
1059 _.each(trads, function(data, code) {
1060 if (code === self.view_language) {
1061 _.each(data, function(value, field) {
1062 self.view.fields[field].set_value(value);
1065 trads_mutex.exec(function() {
1066 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1071 on_btn_close: function() {
1076 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
1077 template: "EmptyComponent",
1078 // name displayed in view switchers
1080 init: function(parent, dataset, view_id, options) {
1081 this._super(parent);
1082 this.dataset = dataset;
1083 this.view_id = view_id;
1084 this.set_default_options(options);
1086 set_default_options: function(options) {
1087 this.options = options || {};
1088 _.defaults(this.options, {
1089 // All possible views options should be defaulted here
1093 action_views_ids: {}
1096 open_translate_dialog: function(field) {
1097 if (!this.translate_dialog) {
1098 this.translate_dialog = new session.web.TranslateDialog(this).start();
1100 this.translate_dialog.open(field);
1103 * Fetches and executes the action identified by ``action_data``.
1105 * @param {Object} action_data the action descriptor data
1106 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1107 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1108 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1109 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1110 * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
1111 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1112 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1114 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1116 var result_handler = function () {
1117 if (on_closed) { on_closed.apply(null, arguments); }
1118 if (self.widget_parent && self.widget_parent.on_action_executed) {
1119 return self.widget_parent.on_action_executed.apply(null, arguments);
1122 var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
1124 var handler = function (r) {
1125 var action = r.result;
1126 if (action && action.constructor == Object) {
1127 var ncontext = new session.web.CompoundContext(context);
1130 active_id: record_id,
1131 active_ids: [record_id],
1132 active_model: dataset.model
1135 ncontext.add(action.context || {});
1136 return self.rpc('/web/session/eval_domain_and_context', {
1137 contexts: [ncontext],
1139 }).pipe(function (results) {
1140 action.context = results.context;
1141 /* niv: previously we were overriding once more with action_data.context,
1142 * I assumed this was not a correct behavior and removed it
1144 return self.do_action(action, result_handler);
1147 return result_handler();
1151 if (action_data.special) {
1152 return handler({result: {"type":"ir.actions.act_window_close"}});
1153 } else if (action_data.type=="object") {
1154 var args = [[record_id]], additional_args = [];
1155 if (action_data.args) {
1157 // Warning: quotes and double quotes problem due to json and xml clash
1158 // Maybe we should force escaping in xml or do a better parse of the args array
1159 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1160 args = args.concat(additional_args);
1162 console.error("Could not JSON.parse arguments", action_data.args);
1166 return dataset.call_button(action_data.name, args, handler);
1167 } else if (action_data.type=="action") {
1168 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1170 return dataset.exec_workflow(record_id, action_data.name, handler);
1174 * Directly set a view to use instead of calling fields_view_get. This method must
1175 * be called before start(). When an embedded view is set, underlying implementations
1176 * of session.web.View must use the provided view instead of any other one.
1178 * @param embedded_view A view.
1180 set_embedded_view: function(embedded_view) {
1181 this.embedded_view = embedded_view;
1182 this.options.sidebar = false;
1184 do_show: function () {
1185 this.$element.show();
1187 do_hide: function () {
1188 this.$element.hide();
1190 do_push_state: function(state) {
1191 if (this.widget_parent && this.widget_parent.do_push_state) {
1192 this.widget_parent.do_push_state(state);
1195 do_load_state: function(state, warm) {
1198 * Switches to a specific view type
1200 * @param {String} view view type to switch to
1202 do_switch_view: function(view) {
1205 * Cancels the switch to the current view, switches to the previous one
1207 * @param {Object} [options]
1208 * @param {Boolean} [options.created=false] resource was created
1209 * @param {String} [options.default=null] view to switch to if no previous view
1211 do_prev_view: function (options) {
1213 do_search: function(view) {
1215 set_common_sidebar_sections: function(sidebar) {
1216 sidebar.add_default_sections();
1218 on_sidebar_import: function() {
1219 var import_view = new session.web.DataImport(this, this.dataset);
1220 import_view.start();
1222 on_sidebar_export: function() {
1223 var export_view = new session.web.DataExport(this, this.dataset);
1224 export_view.start();
1226 on_sidebar_translate: function() {
1227 return this.do_action({
1228 res_model : 'ir.translation',
1229 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1230 views: [[false, 'list'], [false, 'form']],
1231 type : 'ir.actions.act_window',
1236 sidebar_context: function () {
1240 * Asks the view to reload itself, if the reloading is asynchronous should
1241 * return a {$.Deferred} indicating when the reloading is done.
1243 reload: function () {
1248 session.web.json_node_to_xml = function(node, human_readable, indent) {
1249 // For debugging purpose, this function will convert a json node back to xml
1250 // Maybe useful for xml view editor
1251 indent = indent || 0;
1252 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1253 r = sindent + '<' + node.tag,
1254 cr = human_readable ? '\n' : '';
1256 if (typeof(node) === 'string') {
1257 return sindent + node;
1258 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1259 throw("Node a json node");
1261 for (var attr in node.attrs) {
1262 var vattr = node.attrs[attr];
1263 if (typeof(vattr) !== 'string') {
1265 vattr = JSON.stringify(vattr);
1267 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1268 if (human_readable) {
1269 vattr = vattr.replace(/"/g, "'");
1271 r += ' ' + attr + '="' + vattr + '"';
1273 if (node.children && node.children.length) {
1276 for (var i = 0, ii = node.children.length; i < ii; i++) {
1277 childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1279 r += childs.join(cr);
1280 r += cr + sindent + '</' + node.tag + '>';
1289 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: