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.destroy();
34 this.dialog_viewmanager = null;
35 this.dialog.destroy();
39 content_stop: function () {
40 if (this.inner_viewmanager) {
41 this.inner_viewmanager.destroy();
42 this.inner_viewmanager = null;
44 if (this.client_widget) {
45 this.client_widget.destroy();
46 this.client_widget = null;
49 do_push_state: function(state) {
50 if (this.getParent() && this.getParent().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.getParent().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);
68 session.webclient.menu.has_been_loaded.then(function() {
69 session.webclient.menu.open_action(state.action_id);
72 } else if (state.model && state.id) {
73 // TODO handle context & domain ?
76 res_model: state.model,
78 type: 'ir.actions.act_window',
79 views: [[false, 'page'], [false, 'form']]
81 action_loaded = this.do_action(action);
82 } else if (state.sa) {
83 // load session action
86 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
88 return self.do_action(action);
91 } else if (state.client_action) {
93 this.ir_actions_client(state.client_action);
96 $.when(action_loaded || null).then(function() {
97 if (self.inner_viewmanager) {
98 self.inner_viewmanager.do_load_state(state, warm);
102 do_action: function(action, on_close) {
103 if (_.isNumber(action)) {
105 return self.rpc("/web/action/load", { action_id: action }, function(result) {
106 self.do_action(result.result, on_close);
110 console.error("No type for action", action);
113 var type = action.type.replace(/\./g,'_');
114 var popup = action.target === 'new';
115 action.flags = _.extend({
116 views_switcher : !popup,
117 search_view : !popup,
118 action_buttons : !popup,
121 display_title : !popup
122 }, action.flags || {});
123 if (!(type in this)) {
124 console.error("Action manager can't handle action of type " + action.type, action);
127 return this[type](action, on_close);
129 null_action: function() {
133 ir_actions_act_window: function (action, on_close) {
135 if (_(['base.module.upgrade', 'base.setup.installer'])
136 .contains(action.res_model)) {
137 var old_close = on_close;
138 on_close = function () {
139 session.webclient.do_reload().then(old_close);
142 if (action.target === 'new') {
143 if (this.dialog == null) {
144 this.dialog = new session.web.Dialog(this, { width: '80%' });
146 this.dialog.on_close.add(on_close);
148 this.dialog_viewmanager.destroy();
150 this.dialog.dialog_title = action.name;
151 this.dialog_viewmanager = new session.web.ViewManagerAction(this, action);
152 this.dialog_viewmanager.appendTo(this.dialog.$element);
156 return this.getParent().do_action(action, function () {
157 session.webclient.menu.open_menu(action.menu_id);
162 this.inner_action = action;
163 this.inner_viewmanager = new session.web.ViewManagerAction(this, action);
164 this.inner_viewmanager.appendTo(this.$element);
167 ir_actions_act_window_close: function (action, on_closed) {
168 if (!this.dialog && on_closed) {
173 ir_actions_server: function (action, on_closed) {
175 this.rpc('/web/action/run', {
176 action_id: action.id,
177 context: action.context || {}
178 }).then(function (action) {
179 self.do_action(action, on_closed)
182 ir_actions_client: function (action) {
185 var ClientWidget = session.web.client_actions.get_object(action.tag);
186 (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
188 ir_actions_report_xml: function(action, on_closed) {
191 self.rpc("/web/session/eval_domain_and_context", {
192 contexts: [action.context],
194 }).then(function(res) {
195 action = _.clone(action);
196 action.context = res.context;
197 self.session.get_file({
199 data: {action: JSON.stringify(action)},
200 complete: $.unblockUI,
202 if (!self.dialog && on_closed) {
207 error: session.webclient.crashmanager.on_rpc_error
211 ir_actions_act_url: function (action) {
212 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
214 ir_ui_menu: function (action) {
215 this.getParent().do_action(action);
219 session.web.ViewManager = session.web.OldWidget.extend(/** @lends session.web.ViewManager# */{
220 template: "ViewManager",
222 * @constructs session.web.ViewManager
223 * @extends session.web.OldWidget
229 init: function(parent, dataset, views, flags) {
231 this.model = dataset ? dataset.model : undefined;
232 this.dataset = dataset;
233 this.searchview = null;
234 this.active_view = null;
235 this.views_src = _.map(views, function(x) {
236 if (x instanceof Array) {
237 var View = session.web.views.get_object(x[1], true);
241 label: View ? View.prototype.display_name : (void 'nope')
248 this.flags = flags || {};
249 this.registry = session.web.views;
250 this.views_history = [];
253 return session.web.qweb.render(this.template, {
255 prefix: this.element_id,
256 views: this.views_src});
259 * @returns {jQuery.Deferred} initial view loading promise
264 this.$element.find('.oe_vm_switch button').click(function() {
265 self.on_mode_switch($(this).data('view-type'));
268 _.each(this.views_src, function(view) {
269 self.views[view.view_type] = $.extend({}, view, {
270 deferred : $.Deferred(),
273 sidebar_id : self.element_id + '_sidebar_' + view.view_type,
274 action : self.action,
275 action_views_ids : views_ids
276 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
278 views_ids[view.view_type] = view.view_id;
280 if (this.flags.views_switcher === false) {
281 this.$element.find('.oe_vm_switch').hide();
283 // If no default view defined, switch to the first one in sequence
284 var default_view = this.flags.default_view || this.views_src[0].view_type;
285 return this.on_mode_switch(default_view);
288 * Asks the view manager to switch visualization mode.
290 * @param {String} view_type type of view to display
291 * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
292 * @returns {jQuery.Deferred} new view loading promise
294 on_mode_switch: function(view_type, no_store) {
296 view = this.views[view_type],
299 return $.Deferred().reject();
302 this.views_history.push(view_type);
304 this.active_view = view_type;
306 if (!view.controller) {
307 // Lazy loading of views
308 var controllerclass = this.registry.get_object(view_type);
309 var controller = new controllerclass(this, this.dataset, view.view_id, view.options);
310 if (view.embedded_view) {
311 controller.set_embedded_view(view.embedded_view);
313 controller.do_switch_view.add_last(this.on_mode_switch);
314 controller.do_prev_view.add_last(this.on_prev_view);
315 var container = $("#" + this.element_id + '_view_' + view_type);
316 view_promise = controller.appendTo(container);
317 this.views[view_type].controller = controller;
318 this.views[view_type].deferred.resolve(view_type);
319 $.when(view_promise).then(function() {
320 self.on_controller_inited(view_type, controller);
322 && self.flags.auto_search
323 && view.controller.searchable !== false) {
324 self.searchview.ready.then(self.searchview.do_search);
327 } else if (this.searchview
328 && self.flags.auto_search
329 && view.controller.searchable !== false) {
330 this.searchview.ready.then(this.searchview.do_search);
333 if (this.searchview) {
334 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
338 .find('.oe_vm_switch button').removeAttr('disabled')
339 .filter('[data-view-type="' + view_type + '"]')
340 .attr('disabled', true);
342 $.when(view_promise).then(function () {
343 _.each(_.keys(self.views), function(view_name) {
344 var controller = self.views[view_name].controller;
346 if (view_name === view_type) {
347 controller.do_show();
349 controller.do_hide();
354 self.$element.find('.oe_view_title_text:first').text(
355 self.display_title());
360 * Returns to the view preceding the caller view in this manager's
361 * navigation history (the navigation history is appended to via
364 * @param {Object} [options]
365 * @param {Boolean} [options.created=false] resource was created
366 * @param {String} [options.default=null] view to switch to if no previous view
367 * @returns {$.Deferred} switching end signal
369 on_prev_view: function (options) {
370 var current_view = this.views_history.pop();
371 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
372 if (options.created && current_view === 'form' && previous_view === 'list') {
373 // APR special case: "If creation mode from list (and only from a list),
374 // after saving, go to page view (don't come back in list)"
375 return this.on_mode_switch('page');
376 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
377 // APR special case: "If creation from dashboard, we have no previous view
378 return this.on_mode_switch('page');
380 return this.on_mode_switch(previous_view, true);
383 * Sets up the current viewmanager's search view.
385 * @param {Number|false} view_id the view to use or false for a default one
386 * @returns {jQuery.Deferred} search view startup deferred
388 setup_search_view: function(view_id, search_defaults) {
390 if (this.searchview) {
391 this.searchview.destroy();
393 this.searchview = new session.web.SearchView(
395 view_id, search_defaults, this.flags.search_view === false);
397 this.searchview.on_search.add(this.do_searchview_search);
398 return this.searchview.appendTo($("#" + this.element_id + "_search"));
400 do_searchview_search: function(domains, contexts, groupbys) {
402 controller = this.views[this.active_view].controller,
403 action_context = this.action.context || {};
404 this.rpc('/web/session/eval_domain_and_context', {
405 domains: [this.action.domain || []].concat(domains || []),
406 contexts: [action_context].concat(contexts || []),
407 group_by_seq: groupbys || []
408 }, function (results) {
409 self.dataset.context = results.context;
410 self.dataset.domain = results.domain;
411 var groupby = results.group_by.length
413 : action_context.group_by;
414 if (_.isString(groupby)) {
417 controller.do_search(results.domain, results.context, groupby || []);
421 * Event launched when a controller has been inited.
423 * @param {String} view_type type of view
424 * @param {String} view the inited controller
426 on_controller_inited: function(view_type, view) {
429 * Called when one of the view want to execute an action
431 on_action: function(action) {
433 on_create: function() {
435 on_remove: function() {
437 on_edit: function() {
440 * Called by children view after executing an action
442 on_action_executed: function () {
444 display_title: function () {
445 var view = this.views[this.active_view];
448 return view.controller.fields_view.arch.attrs.string;
454 session.web.ViewManagerAction = session.web.ViewManager.extend(/** @lends oepnerp.web.ViewManagerAction# */{
455 template:"ViewManagerAction",
457 * @constructs session.web.ViewManagerAction
458 * @extends session.web.ViewManager
460 * @param {session.web.ActionManager} parent parent object/widget
461 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
463 init: function(parent, action) {
464 // dataset initialization will take the session from ``this``, so if we
465 // do not have it yet (and we don't, because we've not called our own
466 // ``_super()``) rpc requests will blow up.
467 var flags = action.flags || {};
468 if (!('auto_search' in flags)) {
469 flags.auto_search = action.auto_search !== false;
471 if (action.res_model == 'board.board' && action.view_mode === 'form') {
472 // Special case for Dashboards
474 views_switcher : false,
475 display_title : false,
479 action_buttons : false
482 this._super(parent, null, action.views, flags);
483 this.session = parent.session;
484 this.action = action;
485 var dataset = new session.web.DataSetSearch(this, action.res_model, action.context, action.domain);
487 dataset.ids.push(action.res_id);
490 this.dataset = dataset;
492 // setup storage for session-wise menu hiding
493 if (this.session.hidden_menutips) {
496 this.session.hidden_menutips = {}
499 * Initializes the ViewManagerAction: sets up the searchview (if the
500 * searchview is enabled in the manager's action flags), calls into the
501 * parent to initialize the primary view and (if the VMA has a searchview)
502 * launches an initial search after both views are done rendering.
507 search_defaults = {};
508 _.each(this.action.context, function (value, key) {
509 var match = /^search_default_(.*)$/.exec(key);
511 search_defaults[match[1]] = value;
515 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
517 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
519 var main_view_loaded = this._super();
521 var manager_ready = $.when(searchview_loaded, main_view_loaded);
523 this.$element.find('.oe_debug_view').change(this.on_debug_changed);
525 if (this.action.help && !this.flags.low_profile) {
526 var Users = new session.web.DataSet(self, 'res.users'),
527 $tips = this.$element.find('.oe_view_manager_menu_tips');
528 $tips.delegate('blockquote button', 'click', function() {
530 //noinspection FallthroughInSwitchStatementJS
531 switch ($this.attr('name')) {
533 Users.write(self.session.uid, {menu_tips:false});
535 $this.closest('blockquote').hide();
536 self.session.hidden_menutips[self.action.id] = true;
539 if (!(self.action.id in self.session.hidden_menutips)) {
540 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
542 if (!(user && user.id === self.session.uid)) {
545 $tips.find('blockquote').toggle(user.menu_tips);
550 var $res_logs = this.$element.find('.oe-view-manager-logs:first');
551 $res_logs.delegate('a.oe-more-logs', 'click', function () {
552 $res_logs.removeClass('oe-folded');
554 }).delegate('a.oe-remove-everything', 'click', function () {
555 $res_logs.removeClass('oe-has-more').find('ul').empty();
556 $res_logs.css('display','none');
559 $res_logs.css('display','none');
561 return manager_ready;
563 on_debug_changed: function (evt) {
565 $sel = $(evt.currentTarget),
566 $option = $sel.find('option:selected'),
568 current_view = this.views[this.active_view].controller;
571 var dialog = new session.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
572 $('<pre>').text(session.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
575 var ids = current_view.get_selected_ids();
576 if (ids.length === 1) {
577 this.dataset.call('perm_read', [ids]).then(function(result) {
578 var dialog = new session.web.Dialog(this, {
579 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
581 }, QWeb.render('ViewManagerDebugViewLog', {
583 format : session.web.format_value
589 this.dataset.call_and_eval(
590 'fields_get', [false, {}], null, 1).then(function (fields) {
591 var $root = $('<dl>');
592 _(fields).each(function (attributes, name) {
593 $root.append($('<dt>').append($('<h4>').text(name)));
594 var $attrs = $('<dl>').appendTo(
595 $('<dd>').appendTo($root));
596 _(attributes).each(function (def, name) {
597 if (def instanceof Object) {
598 def = JSON.stringify(def);
601 .append($('<dt>').text(name))
602 .append($('<dd style="white-space: pre-wrap;">').text(def));
605 new session.web.Dialog(self, {
606 title: _.str.sprintf(_t("Model %s fields"),
608 width: '95%'}, $root).open();
612 if (current_view.fields_view && current_view.fields_view.arch) {
613 var view_editor = new session.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
616 this.do_warn(_t("Manage Views"),
617 _t("Could not find current view declaration"));
620 case 'edit_workflow':
621 return this.do_action({
622 res_model : 'workflow',
623 domain : [['osv', '=', this.dataset.model]],
624 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
625 type : 'ir.actions.act_window',
631 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
635 console.log("No debug handler for ", val);
638 evt.currentTarget.selectedIndex = 0;
640 do_edit_resource: function(model, id, action) {
641 var action = _.extend({
644 type : 'ir.actions.act_window',
647 views : [[false, 'form']],
650 action_buttons : true,
652 resize_textareas : true
656 this.do_action(action);
658 on_mode_switch: function (view_type, no_store) {
661 return $.when(this._super(view_type, no_store)).then(function () {
662 self.shortcut_check(self.views[view_type]);
664 self.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').removeClass('oe-has-more').css('display','none').find('ul').empty();
666 var controller = self.views[self.active_view].controller,
667 fvg = controller.fields_view,
668 view_id = (fvg && fvg.view_id) || '--';
669 self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
673 if (!self.action.name && fvg) {
674 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
677 var $title = self.$element.find('.oe_view_title_text'),
678 $search_prefix = $title.find('span.oe_searchable_view');
679 if (controller.searchable !== false && self.flags.search_view !== false) {
680 if (!$search_prefix.length) {
681 $title.prepend('<span class="oe_searchable_view">' + _t("Search: ") + '</span>');
684 $search_prefix.remove();
688 do_push_state: function(state) {
689 if (this.getParent() && this.getParent().do_push_state) {
690 state["view_type"] = this.active_view;
691 this.getParent().do_push_state(state);
694 do_load_state: function(state, warm) {
697 if (state.view_type && state.view_type !== this.active_view) {
699 this.views[this.active_view].deferred.pipe(function() {
700 return self.on_mode_switch(state.view_type, true);
705 $.when(defs).then(function() {
706 self.views[self.active_view].controller.do_load_state(state, warm);
709 shortcut_check : function(view) {
711 var grandparent = this.getParent() && this.getParent().getParent();
712 // display shortcuts if on the first view for the action
713 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
714 if (!this.action.name ||
715 !(view.view_type === this.views_src[0].view_type
716 && view.view_id === this.views_src[0].view_id)) {
717 $shortcut_toggle.hide();
720 $shortcut_toggle.removeClass('oe-shortcut-remove').show();
721 if (_(this.session.shortcuts).detect(function (shortcut) {
722 return shortcut.res_id === self.session.active_id; })) {
723 $shortcut_toggle.addClass("oe-shortcut-remove");
725 this.shortcut_add_remove();
727 shortcut_add_remove: function() {
729 var $shortcut_toggle = this.$element.find('.oe-shortcut-toggle');
733 if ($shortcut_toggle.hasClass("oe-shortcut-remove")) {
734 $(self.session.shortcuts.binding).trigger('remove-current');
735 $shortcut_toggle.removeClass("oe-shortcut-remove");
737 $(self.session.shortcuts.binding).trigger('add', {
738 'user_id': self.session.uid,
739 'res_id': self.session.active_id,
740 'resource': 'ir.ui.menu',
741 'name': self.action.name
743 $shortcut_toggle.addClass("oe-shortcut-remove");
748 * Intercept do_action resolution from children views
750 on_action_executed: function () {
751 return new session.web.DataSet(this, 'res.log')
752 .call('get', [], this.do_display_log);
755 * @param {Array<Object>} log_records
757 do_display_log: function (log_records) {
760 var $logs = this.$element.find('.oe-view-manager-logs:first').addClass('oe-folded').css('display', 'block');
761 var $logs_list = $logs.find('ul').empty();
762 $logs.toggleClass('oe-has-more', log_records.length > cutoff);
763 _(log_records.reverse()).each(function (record) {
765 if (record.context) {
766 try { context = py.eval(record.context); }
767 catch (e) { /* TODO: what do I do now? */ }
769 $(_.str.sprintf('<li><a href="#">%s</a></li>', record.name))
770 .appendTo($logs_list)
771 .delegate('a', 'click', function () {
773 type: 'ir.actions.act_window',
774 res_model: record.res_model,
775 res_id: record.res_id,
776 // TODO: need to have an evaluated context here somehow
778 views: [[context.view_id || false, 'form']]
784 display_title: function () {
785 return this.action.name;
789 session.web.Sidebar = session.web.Widget.extend({
791 init: function(parent) {
799 add_default_sections: function() {
801 var view = this.getParent();
802 var view_manager = view.getParent();
803 var action = view_manager.action;
804 if (this.session.uid === 1) {
805 this.add_section(_t('Customize'), 'customize');
806 this.add_items('customize', [{
807 label: _t("Translate"),
808 callback: view.on_sidebar_translate,
809 title: _t("Technical translation")
813 this.add_section(_t('Other Options'), 'other');
814 this.add_items('other', [
817 callback: view.on_sidebar_import
820 callback: view.on_sidebar_export
824 add_toolbar: function(toolbar) {
826 _.each([['print', _t("Reports")], ['action', _t("Actions")], ['relate', _t("Links")]], function(type) {
827 var items = toolbar[type[0]];
829 for (var i = 0; i < items.length; i++) {
831 label: items[i]['name'],
833 classname: 'oe_sidebar_' + type[0]
836 self.add_section(type[1], type[0]);
837 self.add_items(type[0], items);
841 add_section: function(name, code) {
842 if(!code) code = _.str.underscored(name);
843 var $section = this.sections[code];
846 var section_id = _.uniqueId(this.element_id + '_section_' + code + '_');
847 $section = $(session.web.qweb.render("Sidebar.section", {
848 section_id: section_id,
850 classname: 'oe_sidebar_' + code
852 $section.appendTo(this.$element.find('div.sidebar-actions'));
853 this.sections[code] = $section;
858 * For each item added to the section:
861 * will be used as the item's name in the sidebar
864 * descriptor for the action which will be executed, ``action`` and
865 * ``callback`` should be exclusive
868 * function to call when the item is clicked in the sidebar, called
869 * with the item descriptor as its first argument (so information
870 * can be stored as additional keys on the object passed to
873 * ``classname`` (optional)
874 * ``@class`` set on the sidebar serialization of the item
876 * ``title`` (optional)
877 * will be set as the item's ``@title`` (tooltip)
879 * @param {String} section_code
880 * @param {Array<{label, action | callback[, classname][, title]}>} items
882 add_items: function(section_code, items) {
884 $section = this.add_section(_.str.titleize(section_code.replace('_', ' ')), section_code),
885 section_id = $section.attr('id');
888 for (var i = 0; i < items.length; i++) {
889 items[i].element_id = _.uniqueId(section_id + '_item_');
890 this.items[items[i].element_id] = items[i];
893 var $items = $(session.web.qweb.render("Sidebar.section.items", {items: items}));
895 $items.find('a.oe_sidebar_action_a').click(function() {
896 var item = self.items[$(this).attr('id')];
898 item.callback.apply(self, [item]);
901 self.on_item_action_clicked(item);
906 var $ul = $section.find('ul');
908 $ul = $('<ul/>').appendTo($section);
910 $items.appendTo($ul);
913 on_item_action_clicked: function(item) {
915 self.getParent().sidebar_context().then(function (context) {
916 var ids = self.getParent().get_selected_ids();
917 if (ids.length == 0) {
918 //TODO: make prettier warning?
919 openerp.web.dialog($("<div />").text(_t("You must choose at least one record.")), {
920 title: _t("Warning"),
925 var additional_context = _.extend({
928 active_model: self.getParent().dataset.model
930 self.rpc("/web/action/load", {
931 action_id: item.action.id,
932 context: additional_context
933 }, function(result) {
934 result.result.context = _.extend(result.result.context || {},
936 result.result.flags = result.result.flags || {};
937 result.result.flags.new_window = true;
938 self.do_action(result.result, function () {
940 self.getParent().reload();
947 session.web.TranslateDialog = session.web.Dialog.extend({
948 dialog_title: {toString: function () { return _t("Translations"); }},
949 init: function(view) {
950 // TODO fme: should add the language to fields_view_get because between the fields view get
951 // and the moment the user opens the translation dialog, the user language could have been changed
952 this.view_language = view.session.user_context.lang;
953 this['on_button' + _t("Save")] = this.on_button_Save;
954 this['on_button' + _t("Close")] = this.on_button_Close;
960 this.view_type = view.fields_view.type || '';
961 this.$fields_form = null;
962 this.$view_form = null;
963 this.$sidebar_form = null;
964 this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
965 this.languages = null;
966 this.languages_loaded = $.Deferred();
967 (new session.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
968 [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
973 $.when(this.languages_loaded).then(function() {
974 self.$element.html(session.web.qweb.render('TranslateDialog', { widget: self }));
975 self.$fields_form = self.$element.find('.oe_translation_form');
976 self.$fields_form.find('.oe_trad_field').change(function() {
977 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
982 on_languages_loaded: function(langs) {
983 this.languages = langs;
984 this.languages_loaded.resolve();
986 do_load_fields_values: function(callback) {
989 this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
990 _.each(self.languages, function(lg) {
991 var deff = $.Deferred();
993 var callback = function(values) {
994 _.each(self.translatable_fields_keys, function(f) {
995 self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
999 if (lg.code === self.view_language) {
1001 _.each(self.translatable_fields_keys, function(field) {
1002 values[field] = self.view.fields[field].get_value();
1006 self.rpc('/web/dataset/get', {
1007 model: self.view.dataset.model,
1008 ids: [self.view.datarecord.id],
1009 fields: self.translatable_fields_keys,
1010 context: self.view.dataset.get_context({
1015 $.when.apply(null, deffered).then(callback);
1017 open: function(field) {
1020 $.when(this.languages_loaded).then(function() {
1021 if (self.view.translatable_fields && self.view.translatable_fields.length) {
1022 self.do_load_fields_values(function() {
1025 var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1026 self.$element.scrollTo($field_input);
1027 $field_input.focus();
1035 on_button_Save: function() {
1038 trads_mutex = new $.Mutex();
1039 self.$fields_form.find('.oe_trad_field.touched').each(function() {
1040 var field = $(this).attr('name').split('-');
1041 if (!trads[field[0]]) {
1042 trads[field[0]] = {};
1044 trads[field[0]][field[1]] = $(this).val();
1046 _.each(trads, function(data, code) {
1047 if (code === self.view_language) {
1048 _.each(data, function(value, field) {
1049 self.view.fields[field].set_value(value);
1052 trads_mutex.exec(function() {
1053 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1058 on_button_Close: function() {
1063 session.web.View = session.web.Widget.extend(/** @lends session.web.View# */{
1064 template: "EmptyComponent",
1065 // name displayed in view switchers
1067 init: function(parent, dataset, view_id, options) {
1068 this._super(parent);
1069 this.dataset = dataset;
1070 this.view_id = view_id;
1071 this.set_default_options(options);
1073 set_default_options: function(options) {
1074 this.options = options || {};
1075 _.defaults(this.options, {
1076 // All possible views options should be defaulted here
1080 action_views_ids: {}
1083 open_translate_dialog: function(field) {
1084 if (!this.translate_dialog) {
1085 this.translate_dialog = new session.web.TranslateDialog(this).start();
1087 this.translate_dialog.open(field);
1090 * Fetches and executes the action identified by ``action_data``.
1092 * @param {Object} action_data the action descriptor data
1093 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1094 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1095 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1096 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1097 * @param {session.web.DataSet} dataset a dataset object used to communicate with the server
1098 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1099 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1101 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1103 var result_handler = function () {
1104 if (on_closed) { on_closed.apply(null, arguments); }
1105 if (self.getParent() && self.getParent().on_action_executed) {
1106 return self.getParent().on_action_executed.apply(null, arguments);
1109 var context = new session.web.CompoundContext(dataset.get_context(), action_data.context || {});
1111 var handler = function (r) {
1112 var action = r.result;
1113 if (action && action.constructor == Object) {
1114 var ncontext = new session.web.CompoundContext(context);
1117 active_id: record_id,
1118 active_ids: [record_id],
1119 active_model: dataset.model
1122 ncontext.add(action.context || {});
1123 return self.rpc('/web/session/eval_domain_and_context', {
1124 contexts: [ncontext],
1126 }).pipe(function (results) {
1127 action.context = results.context;
1128 /* niv: previously we were overriding once more with action_data.context,
1129 * I assumed this was not a correct behavior and removed it
1131 return self.do_action(action, result_handler);
1134 return result_handler();
1138 if (action_data.special) {
1139 return handler({result: {"type":"ir.actions.act_window_close"}});
1140 } else if (action_data.type=="object") {
1141 var args = [[record_id]], additional_args = [];
1142 if (action_data.args) {
1144 // Warning: quotes and double quotes problem due to json and xml clash
1145 // Maybe we should force escaping in xml or do a better parse of the args array
1146 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1147 args = args.concat(additional_args);
1149 console.error("Could not JSON.parse arguments", action_data.args);
1153 return dataset.call_button(action_data.name, args, handler);
1154 } else if (action_data.type=="action") {
1155 return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1157 return dataset.exec_workflow(record_id, action_data.name, handler);
1161 * Directly set a view to use instead of calling fields_view_get. This method must
1162 * be called before start(). When an embedded view is set, underlying implementations
1163 * of session.web.View must use the provided view instead of any other one.
1165 * @param embedded_view A view.
1167 set_embedded_view: function(embedded_view) {
1168 this.embedded_view = embedded_view;
1169 this.options.sidebar = false;
1171 do_show: function () {
1172 this.$element.show();
1174 do_hide: function () {
1175 this.$element.hide();
1177 do_push_state: function(state) {
1178 if (this.getParent() && this.getParent().do_push_state) {
1179 this.getParent().do_push_state(state);
1182 do_load_state: function(state, warm) {
1185 * Switches to a specific view type
1187 * @param {String} view view type to switch to
1189 do_switch_view: function(view) {
1192 * Cancels the switch to the current view, switches to the previous one
1194 * @param {Object} [options]
1195 * @param {Boolean} [options.created=false] resource was created
1196 * @param {String} [options.default=null] view to switch to if no previous view
1198 do_prev_view: function (options) {
1200 do_search: function(view) {
1202 set_common_sidebar_sections: function(sidebar) {
1203 sidebar.add_default_sections();
1205 on_sidebar_import: function() {
1206 var import_view = new session.web.DataImport(this, this.dataset);
1207 import_view.start();
1209 on_sidebar_export: function() {
1210 var export_view = new session.web.DataExport(this, this.dataset);
1211 export_view.start();
1213 on_sidebar_translate: function() {
1214 return this.do_action({
1215 res_model : 'ir.translation',
1216 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1217 views: [[false, 'list'], [false, 'form']],
1218 type : 'ir.actions.act_window',
1223 sidebar_context: function () {
1227 * Asks the view to reload itself, if the reloading is asynchronous should
1228 * return a {$.Deferred} indicating when the reloading is done.
1230 reload: function () {
1235 session.web.xml_to_json = function(node) {
1236 switch (node.nodeType) {
1242 var attrs = $(node).getAttributes();
1243 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1246 attrs[key] = JSON.parse(attrs[key]);
1251 tag: node.tagName.toLowerCase(),
1253 children: _.map(node.childNodes, session.web.xml_to_json)
1257 session.web.json_node_to_xml = function(node, human_readable, indent) {
1258 // For debugging purpose, this function will convert a json node back to xml
1259 // Maybe useful for xml view editor
1260 indent = indent || 0;
1261 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1262 r = sindent + '<' + node.tag,
1263 cr = human_readable ? '\n' : '';
1265 if (typeof(node) === 'string') {
1266 return sindent + node;
1267 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1268 throw("Node a json node");
1270 for (var attr in node.attrs) {
1271 var vattr = node.attrs[attr];
1272 if (typeof(vattr) !== 'string') {
1274 vattr = JSON.stringify(vattr);
1276 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1277 if (human_readable) {
1278 vattr = vattr.replace(/"/g, "'");
1280 r += ' ' + attr + '="' + vattr + '"';
1282 if (node.children && node.children.length) {
1285 for (var i = 0, ii = node.children.length; i < ii; i++) {
1286 childs.push(session.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1288 r += childs.join(cr);
1289 r += cr + sindent + '</' + node.tag + '>';
1295 session.web.xml_to_str = function(node) {
1296 if (window.ActiveXObject) {
1299 return (new XMLSerializer()).serializeToString(node);
1305 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: