1 /*---------------------------------------------------------
3 *---------------------------------------------------------*/
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
9 instance.web.ActionManager = instance.web.Widget.extend({
10 init: function(parent) {
12 this.inner_action = null;
13 this.inner_widget = null;
15 this.dialog_widget = null;
16 this.breadcrumbs = [];
17 this.on('history_back', this, function() {
18 return this.history_back();
22 this._super.apply(this, arguments);
23 this.$el.on('click', 'a.oe_breadcrumb_item', this.on_breadcrumb_clicked);
25 dialog_stop: function () {
27 this.dialog_widget.destroy();
28 this.dialog_widget = null;
29 this.dialog.destroy();
34 * Add a new item to the breadcrumb
36 * If the title of an item is an array, the multiple title mode is in use.
37 * (eg: a widget with multiple views might need to display a title for each view)
38 * In multiple title mode, the show() callback can check the index it receives
39 * in order to detect which of its titles has been clicked on by the user.
41 * @param {Object} item breadcrumb item
42 * @param {Object} item.widget widget containing the view(s) to be added to the breadcrumb added
43 * @param {Function} [item.show] triggered whenever the widget should be shown back
44 * @param {Function} [item.hide] triggered whenever the widget should be shown hidden
45 * @param {Function} [item.destroy] triggered whenever the widget should be destroyed
46 * @param {String|Array} [item.title] title(s) of the view(s) to be displayed in the breadcrumb
47 * @param {Function} [item.get_title] should return the title(s) of the view(s) to be displayed in the breadcrumb
49 push_breadcrumb: function(item) {
50 var last = this.breadcrumbs.slice(-1)[0];
55 show: function(index) {
56 this.widget.$el.show();
59 this.widget.$el.hide();
62 this.widget.destroy();
64 get_title: function() {
65 return this.title || this.widget.get('title');
68 item.id = _.uniqueId('breadcrumb_');
69 this.breadcrumbs.push(item);
71 history_back: function() {
72 var last = this.breadcrumbs.slice(-1)[0];
76 var title = last.get_title();
77 if (_.isArray(title) && title.length > 1) {
78 return this.select_breadcrumb(this.breadcrumbs.length - 1, title.length - 2);
79 } else if (this.breadcrumbs.length === 1) {
80 // Only one single titled item in breadcrumb, most of the time you want to trigger back to home
83 var prev = this.breadcrumbs[this.breadcrumbs.length - 2];
84 title = prev.get_title();
85 return this.select_breadcrumb(this.breadcrumbs.length - 2, _.isArray(title) ? title.length - 1 : undefined);
88 on_breadcrumb_clicked: function(ev) {
89 var $e = $(ev.target);
90 var id = $e.data('id');
92 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
93 if (this.breadcrumbs[i].id == id) {
98 var subindex = $e.parent().find('a.oe_breadcrumb_item[data-id=' + $e.data('id') + ']').index($e);
99 this.select_breadcrumb(index, subindex);
101 select_breadcrumb: function(index, subindex) {
102 var next_item = this.breadcrumbs[index + 1];
103 if (next_item && next_item.on_reverse_breadcrumb) {
104 next_item.on_reverse_breadcrumb(this.breadcrumbs[index].widget);
106 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
108 if (this.remove_breadcrumb(i) === false) {
113 var item = this.breadcrumbs[index];
115 this.inner_widget = item.widget;
118 clear_breadcrumbs: function() {
119 for (var i = this.breadcrumbs.length - 1; i >= 0; i--) {
120 if (this.remove_breadcrumb(0) === false) {
125 remove_breadcrumb: function(index) {
126 var item = this.breadcrumbs.splice(index, 1)[0];
128 var dups = _.filter(this.breadcrumbs, function(it) {
129 return item.widget === it.widget;
132 if (this.getParent().has_uncommitted_changes()) {
133 this.inner_widget = item.widget;
134 this.breadcrumbs.splice(index, 0, item);
141 var last_widget = this.breadcrumbs.slice(-1)[0];
142 this.inner_widget = last_widget && last_widget.widget;
144 get_title: function() {
146 for (var i = 0; i < this.breadcrumbs.length; i += 1) {
147 var item = this.breadcrumbs[i];
148 var tit = item.get_title();
149 if (!_.isArray(tit)) {
152 for (var j = 0; j < tit.length; j += 1) {
153 var label = _.escape(tit[j]);
154 if (i === this.breadcrumbs.length - 1 && j === tit.length - 1) {
155 titles.push(_.str.sprintf('<span class="oe_breadcrumb_item">%s</span>', label));
157 titles.push(_.str.sprintf('<a href="#" class="oe_breadcrumb_item" data-id="%s">%s</a>', item.id, label));
161 return titles.join(' <span class="oe_fade">/</span> ');
163 do_push_state: function(state) {
165 if (this.getParent() && this.getParent().do_push_state) {
166 if (this.inner_action) {
167 if (this.inner_action._push_me === false) {
168 // this action has been explicitly marked as not pushable
171 state['title'] = this.inner_action.name;
172 if(this.inner_action.type == 'ir.actions.act_window') {
173 state['model'] = this.inner_action.res_model;
175 if (this.inner_action.id) {
176 state['action'] = this.inner_action.id;
177 } else if (this.inner_action.type == 'ir.actions.client') {
178 state['action'] = this.inner_action.tag;
180 _.each(this.inner_action.params, function(v, k) {
181 if(_.isString(v) || _.isNumber(v)) {
185 state = _.extend(params || {}, state);
189 this.getParent().do_push_state(state);
193 do_load_state: function(state, warm) {
197 if (_.isString(state.action) && instance.web.client_actions.contains(state.action)) {
198 var action_client = {type: "ir.actions.client", tag: state.action, params: state};
200 action_loaded = this.do_action(action_client);
202 var run_action = (!this.inner_widget || !this.inner_widget.action) || this.inner_widget.action.id !== state.action;
205 action_loaded = this.do_action(state.action);
206 instance.webclient.menu.has_been_loaded.then(function() {
207 instance.webclient.menu.open_action(state.action);
211 } else if (state.model && state.id) {
212 // TODO handle context & domain ?
215 res_model: state.model,
217 type: 'ir.actions.act_window',
218 views: [[false, 'form']]
220 action_loaded = this.do_action(action);
221 } else if (state.sa) {
222 // load session action
224 action_loaded = this.rpc('/web/session/get_session_action', {key: state.sa}).pipe(function(action) {
226 return self.do_action(action);
231 $.when(action_loaded || null).then(function() {
232 if (self.inner_widget && self.inner_widget.do_load_state) {
233 self.inner_widget.do_load_state(state, warm);
237 do_action: function(action, on_close, clear_breadcrumbs, on_reverse_breadcrumb) {
238 if (_.isString(action) && instance.web.client_actions.contains(action)) {
239 var action_client = { type: "ir.actions.client", tag: action };
240 return this.do_action(action_client, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
241 } else if (_.isNumber(action) || _.isString(action)) {
243 return self.rpc("/web/action/load", { action_id: action }).pipe(function(result) {
244 return self.do_action(result, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
248 console.error("No type for action", action);
249 return $.Deferred().reject();
251 var type = action.type.replace(/\./g,'_');
252 var popup = action.target === 'new';
253 var inline = action.target === 'inline' || action.target === 'inlineview';
254 action.flags = _.extend({
255 views_switcher : !popup && !inline,
256 search_view : !popup && !inline,
257 action_buttons : !popup && !inline,
258 sidebar : !popup && !inline,
259 pager : !popup && !inline,
260 display_title : !popup
261 }, action.flags || {});
262 if (!(type in this)) {
263 console.error("Action manager can't handle action of type " + action.type, action);
264 return $.Deferred().reject();
266 return this[type](action, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
268 null_action: function() {
270 this.clear_breadcrumbs();
274 * @param {Object} executor
275 * @param {Object} executor.action original action
276 * @param {Function<instance.web.Widget>} executor.widget function used to fetch the widget instance
277 * @param {String} executor.klass CSS class to add on the dialog root, if action.target=new
278 * @param {Function<instance.web.Widget, undefined>} executor.post_process cleanup called after a widget has been added as inner_widget
280 * @param clear_breadcrumbs
283 ir_actions_common: function(executor, on_close, clear_breadcrumbs) {
284 if (this.inner_widget && executor.action.target !== 'new') {
285 if (this.getParent().has_uncommitted_changes()) {
286 return $.Deferred().reject();
287 } else if (clear_breadcrumbs) {
288 this.clear_breadcrumbs();
291 var widget = executor.widget();
292 if (executor.action.target === 'new') {
293 if (this.dialog === null || this.dialog.isDestroyed()) {
294 this.dialog = new instance.web.Dialog(this, {
295 buttons: {"Close": function() {$(this).dialog("close")}},
296 dialogClass: executor.klass,
299 this.dialog.on("closing", null, on_close);
300 this.dialog.init_dialog();
302 this.dialog_widget.destroy();
304 this.dialog.dialog_title = executor.action.name;
305 if (widget instanceof instance.web.ViewManager) {
306 _.extend(widget.flags, {
307 $buttons: this.dialog.$buttons,
308 footer_to_buttons: true,
311 this.dialog_widget = widget;
312 var initialized = this.dialog_widget.appendTo(this.dialog.$el);
317 this.inner_action = executor.action;
318 this.inner_widget = widget;
319 executor.post_process(widget);
320 return this.inner_widget.appendTo(this.$el);
323 ir_actions_act_window: function (action, on_close, clear_breadcrumbs, on_reverse_breadcrumb) {
326 return this.ir_actions_common({
327 widget: function () { return new instance.web.ViewManagerAction(self, action); },
329 klass: 'oe_act_window',
330 post_process: function (widget) { widget.add_breadcrumb(on_reverse_breadcrumb); }
331 }, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
333 ir_actions_client: function (action, on_close, clear_breadcrumbs, on_reverse_breadcrumb) {
335 var ClientWidget = instance.web.client_actions.get_object(action.tag);
337 if (!(ClientWidget.prototype instanceof instance.web.Widget)) {
339 if (next = ClientWidget(this, action.params)) {
340 return this.do_action(next, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
345 return this.ir_actions_common({
346 widget: function () { return new ClientWidget(self, action.params); },
348 klass: 'oe_act_client',
349 post_process: function(widget) {
350 self.push_breadcrumb({
353 on_reverse_breadcrumb: on_reverse_breadcrumb,
355 if (action.tag !== 'reload') {
356 self.do_push_state({});
359 }, on_close, clear_breadcrumbs, on_reverse_breadcrumb);
361 ir_actions_act_window_close: function (action, on_closed) {
362 if (!this.dialog && on_closed) {
367 ir_actions_server: function (action, on_closed, clear_breadcrumbs, on_reverse_breadcrumb) {
369 this.rpc('/web/action/run', {
370 action_id: action.id,
371 context: action.context || {}
372 }).then(function (action) {
373 self.do_action(action, on_closed, clear_breadcrumbs, on_reverse_breadcrumb)
376 ir_actions_report_xml: function(action, on_closed) {
378 instance.web.blockUI();
379 self.rpc("/web/session/eval_domain_and_context", {
380 contexts: [action.context],
382 }).then(function(res) {
383 action = _.clone(action);
384 action.context = res.context;
385 self.session.get_file({
387 data: {action: JSON.stringify(action)},
388 complete: instance.web.unblockUI,
390 if (!self.dialog && on_closed) {
395 error: instance.webclient.crashmanager.on_rpc_error
399 ir_actions_act_url: function (action) {
400 window.open(action.url, action.target === 'self' ? '_self' : '_blank');
404 instance.web.ViewManager = instance.web.Widget.extend({
405 template: "ViewManager",
406 init: function(parent, dataset, views, flags) {
408 this.model = dataset ? dataset.model : undefined;
409 this.dataset = dataset;
410 this.searchview = null;
411 this.active_view = null;
412 this.views_src = _.map(views, function(x) {
413 if (x instanceof Array) {
414 var View = instance.web.views.get_object(x[1], true);
418 label: View ? View.prototype.display_name : (void 'nope')
425 this.flags = flags || {};
426 this.registry = instance.web.views;
427 this.views_history = [];
430 * @returns {jQuery.Deferred} initial view loading promise
435 this.$el.find('.oe_view_manager_switch a').click(function() {
436 self.switch_mode($(this).data('view-type'));
439 _.each(this.views_src, function(view) {
440 self.views[view.view_type] = $.extend({}, view, {
441 deferred : $.Deferred(),
444 $buttons : self.$el.find('.oe_view_manager_buttons'),
445 $sidebar : self.flags.sidebar ? self.$el.find('.oe_view_manager_sidebar') : undefined,
446 $pager : self.$el.find('.oe_view_manager_pager'),
447 action : self.action,
448 action_views_ids : views_ids
449 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
451 views_ids[view.view_type] = view.view_id;
453 if (this.flags.views_switcher === false) {
454 this.$el.find('.oe_view_manager_switch').hide();
456 // If no default view defined, switch to the first one in sequence
457 var default_view = this.flags.default_view || this.views_src[0].view_type;
458 return this.switch_mode(default_view);
460 switch_mode: function(view_type, no_store, view_options) {
462 var view = this.views[view_type];
464 var form = this.views['form'];
465 if (!view || (form && form.controller && !form.controller.can_be_discarded())) {
466 self.trigger('switch_mode', view_type, no_store, view_options);
467 return $.Deferred().reject();
470 this.views_history.push(view_type);
472 this.active_view = view_type;
474 if (!view.controller) {
475 view_promise = this.do_create_view(view_type);
476 } else if (this.searchview
477 && self.flags.auto_search
478 && view.controller.searchable !== false) {
479 this.searchview.ready.then(this.searchview.do_search);
482 if (this.searchview) {
483 this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
486 this.$el.find('.oe_view_manager_switch a').parent().removeClass('active');
488 .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
489 .parent().addClass('active');
491 r = $.when(view_promise).then(function () {
492 _.each(_.keys(self.views), function(view_name) {
493 var controller = self.views[view_name].controller;
495 var container = self.$el.find(".oe_view_manager_view_" + view_name + ":first");
496 if (view_name === view_type) {
498 controller.do_show(view_options || {});
501 controller.do_hide();
505 self.trigger('switch_mode', view_type, no_store, view_options);
509 do_create_view: function(view_type) {
510 // Lazy loading of views
512 var view = this.views[view_type];
513 var viewclass = this.registry.get_object(view_type);
514 var options = _.clone(view.options);
515 if (view_type === "form" && this.action && (this.action.target == 'new' || this.action.target == 'inline')) {
516 options.initial_mode = 'edit';
518 var controller = new viewclass(this, this.dataset, view.view_id, options);
520 controller.on('history_back', this, function() {
521 var am = self.getParent();
522 if (am && am.trigger) {
523 return am.trigger('history_back');
527 controller.on("change:title", this, function() {
528 if (self.active_view === view_type) {
529 self.set_title(controller.get('title'));
533 if (view.embedded_view) {
534 controller.set_embedded_view(view.embedded_view);
536 controller.on('switch_mode', self, this.switch_mode);
537 controller.on('previous_view', self, this.prev_view);
539 var container = this.$el.find(".oe_view_manager_view_" + view_type);
540 var view_promise = controller.appendTo(container);
541 this.views[view_type].controller = controller;
542 this.views[view_type].deferred.resolve(view_type);
543 return $.when(view_promise).then(function() {
545 && self.flags.auto_search
546 && view.controller.searchable !== false) {
547 self.searchview.ready.then(self.searchview.do_search);
549 self.trigger("controller_inited",view_type,controller);
552 set_title: function(title) {
553 this.$el.find('.oe_view_title_text:first').text(title);
555 add_breadcrumb: function(on_reverse_breadcrumb) {
557 var views = [this.active_view || this.views_src[0].view_type];
558 this.on('switch_mode', self, function(mode) {
559 var last = views.slice(-1)[0];
561 if (mode !== 'form') {
567 this.getParent().push_breadcrumb({
570 show: function(index) {
571 var view_to_select = views[index];
573 if (self.active_view !== view_to_select) {
574 self.switch_mode(view_to_select);
577 get_title: function() {
580 _.each(self.getParent().breadcrumbs, function(bc, i) {
581 if (bc.widget === self) {
585 var next = self.getParent().breadcrumbs.slice(currentIndex + 1)[0];
586 var titles = _.map(views, function(v) {
587 var controller = self.views[v].controller;
589 id = controller.datarecord.id;
591 return controller.get('title');
593 if (next && next.action && next.action.res_id && self.dataset &&
594 self.active_view === 'form' && self.dataset.model === next.action.res_model && id === next.action.res_id) {
595 // If the current active view is a formview and the next item in the breadcrumbs
596 // is an action on same object (model / res_id), then we omit the current formview's title
601 on_reverse_breadcrumb: on_reverse_breadcrumb,
605 * Returns to the view preceding the caller view in this manager's
606 * navigation history (the navigation history is appended to via
609 * @param {Object} [options]
610 * @param {Boolean} [options.created=false] resource was created
611 * @param {String} [options.default=null] view to switch to if no previous view
612 * @returns {$.Deferred} switching end signal
614 prev_view: function (options) {
615 options = options || {};
616 var current_view = this.views_history.pop();
617 var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
618 if (options.created && current_view === 'form' && previous_view === 'list') {
619 // APR special case: "If creation mode from list (and only from a list),
620 // after saving, go to page view (don't come back in list)"
621 return this.switch_mode('form');
622 } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
623 // APR special case: "If creation from dashboard, we have no previous view
624 return this.switch_mode('form');
626 return this.switch_mode(previous_view, true);
629 * Sets up the current viewmanager's search view.
631 * @param {Number|false} view_id the view to use or false for a default one
632 * @returns {jQuery.Deferred} search view startup deferred
634 setup_search_view: function(view_id, search_defaults) {
636 if (this.searchview) {
637 this.searchview.destroy();
639 this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
641 this.searchview.on_search.add(this.do_searchview_search);
642 return this.searchview.appendTo(this.$el.find(".oe_view_manager_view_search"));
644 do_searchview_search: function(domains, contexts, groupbys) {
646 controller = this.views[this.active_view].controller,
647 action_context = this.action.context || {};
648 this.rpc('/web/session/eval_domain_and_context', {
649 domains: [this.action.domain || []].concat(domains || []),
650 contexts: [action_context].concat(contexts || []),
651 group_by_seq: groupbys || []
652 }).then(function (results) {
653 self.dataset._model = new instance.web.Model(
654 self.dataset.model, results.context, results.domain);
655 var groupby = results.group_by.length
657 : action_context.group_by;
658 if (_.isString(groupby)) {
661 controller.do_search(results.domain, results.context, groupby || []);
665 * Called when one of the view want to execute an action
667 on_action: function(action) {
669 on_create: function() {
671 on_remove: function() {
673 on_edit: function() {
676 * Called by children view after executing an action
678 on_action_executed: function () {
682 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
683 template:"ViewManagerAction",
685 * @constructs instance.web.ViewManagerAction
686 * @extends instance.web.ViewManager
688 * @param {instance.web.ActionManager} parent parent object/widget
689 * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
691 init: function(parent, action) {
692 // dataset initialization will take the session from ``this``, so if we
693 // do not have it yet (and we don't, because we've not called our own
694 // ``_super()``) rpc requests will blow up.
695 var flags = action.flags || {};
696 if (!('auto_search' in flags)) {
697 flags.auto_search = action.auto_search !== false;
699 if (action.res_model == 'board.board' && action.view_mode === 'form') {
700 // Special case for Dashboards
702 views_switcher : false,
703 display_title : false,
707 action_buttons : false
710 this._super(parent, null, action.views, flags);
711 this.session = parent.session;
712 this.action = action;
713 var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
715 dataset.ids.push(action.res_id);
718 this.dataset = dataset;
720 // setup storage for session-wise menu hiding
721 if (this.session.hidden_menutips) {
724 this.session.hidden_menutips = {};
727 * Initializes the ViewManagerAction: sets up the searchview (if the
728 * searchview is enabled in the manager's action flags), calls into the
729 * parent to initialize the primary view and (if the VMA has a searchview)
730 * launches an initial search after both views are done rendering.
735 search_defaults = {};
736 _.each(this.action.context, function (value, key) {
737 var match = /^search_default_(.*)$/.exec(key);
739 search_defaults[match[1]] = value;
743 var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
745 searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
747 var main_view_loaded = this._super();
749 var manager_ready = $.when(searchview_loaded, main_view_loaded);
751 this.$el.find('.oe_debug_view').change(this.on_debug_changed);
752 this.$el.addClass("oe_view_manager_" + (this.action.target || 'current'));
753 return manager_ready;
755 on_debug_changed: function (evt) {
757 $sel = $(evt.currentTarget),
758 $option = $sel.find('option:selected'),
760 current_view = this.views[this.active_view].controller;
763 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
764 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$el);
770 type : 'ir.actions.act_url',
771 url: '/web/static/test/test.html'
775 var ids = current_view.get_selected_ids();
776 if (ids.length === 1) {
777 this.dataset.call('perm_read', [ids]).then(function(result) {
778 var dialog = new instance.web.Dialog(this, {
779 title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
781 }, QWeb.render('ViewManagerDebugViewLog', {
783 format : instance.web.format_value
788 case 'toggle_layout_outline':
789 current_view.rendering_engine.toggle_layout_debugging();
793 name: "Technical Translation",
794 res_model : 'ir.translation',
795 domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
796 views: [[false, 'list'], [false, 'form']],
797 type : 'ir.actions.act_window',
803 this.dataset.call('fields_get', [false, {}]).then(function (fields) {
804 var $root = $('<dl>');
805 _(fields).each(function (attributes, name) {
806 $root.append($('<dt>').append($('<h4>').text(name)));
807 var $attrs = $('<dl>').appendTo($('<dd>').appendTo($root));
808 _(attributes).each(function (def, name) {
809 if (def instanceof Object) {
810 def = JSON.stringify(def);
813 .append($('<dt>').text(name))
814 .append($('<dd style="white-space: pre-wrap;">').text(def));
817 new instance.web.Dialog(self, {
818 title: _.str.sprintf(_t("Model %s fields"),
820 width: '95%'}, $root).open();
823 case 'edit_workflow':
824 return this.do_action({
825 res_model : 'workflow',
826 domain : [['osv', '=', this.dataset.model]],
827 views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
828 type : 'ir.actions.act_window',
834 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
836 case 'manage_filters':
838 res_model: 'ir.filters',
839 views: [[false, 'list'], [false, 'form']],
840 type: 'ir.actions.act_window',
842 search_default_my_filters: true,
843 search_default_model_id: this.dataset.model
847 case 'print_workflow':
848 if (current_view.get_selected_ids && current_view.get_selected_ids().length == 1) {
849 instance.web.blockUI();
851 context: { active_ids: current_view.get_selected_ids() },
852 report_name: "workflow.instance.graph",
854 model: this.dataset.model,
855 id: current_view.get_selected_ids()[0],
859 this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI });
864 console.log("No debug handler for ", val);
867 evt.currentTarget.selectedIndex = 0;
869 do_edit_resource: function(model, id, action) {
870 var action = _.extend({
873 type : 'ir.actions.act_window',
876 views : [[false, 'form']],
879 action_buttons : true,
881 resize_textareas : true
885 this.do_action(action);
887 switch_mode: function (view_type, no_store, options) {
890 return $.when(this._super.apply(this, arguments)).then(function () {
891 var controller = self.views[self.active_view].controller,
892 fvg = controller.fields_view,
893 view_id = (fvg && fvg.view_id) || '--';
894 self.$el.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
901 do_create_view: function(view_type) {
902 var r = this._super.apply(this, arguments);
903 var view = this.views[view_type].controller;
904 view.set({ 'title': this.action.name });
907 set_title: function(title) {
908 this.$el.find('.oe_breadcrumb_title:first').html(this.getParent().get_title());
910 do_push_state: function(state) {
911 if (this.getParent() && this.getParent().do_push_state) {
912 state["view_type"] = this.active_view;
913 this.getParent().do_push_state(state);
916 do_load_state: function(state, warm) {
919 if (state.view_type && state.view_type !== this.active_view) {
921 this.views[this.active_view].deferred.pipe(function() {
922 return self.switch_mode(state.view_type, true);
927 $.when(defs).then(function() {
928 self.views[self.active_view].controller.do_load_state(state, warm);
933 instance.web.Sidebar = instance.web.Widget.extend({
934 init: function(parent) {
937 var view = this.getParent();
939 { 'name' : 'print', 'label' : _t('Print'), },
940 { 'name' : 'other', 'label' : _t('More'), }
946 this.fileupload_id = _.uniqueId('oe_fileupload');
947 $(window).on(this.fileupload_id, function() {
948 var args = [].slice.call(arguments).slice(1);
949 if (args[0] && args[0].error) {
950 alert(args[0].error);
952 self.do_attachement_update(self.dataset, self.model_id);
954 instance.web.unblockUI();
961 this.$el.on('click','.oe_dropdown_menu li a', function(event) {
962 var section = $(this).data('section');
963 var index = $(this).data('index');
964 var item = self.items[section][index];
966 item.callback.apply(self, [item]);
967 } else if (item.action) {
968 self.on_item_action_clicked(item);
969 } else if (item.url) {
972 event.preventDefault();
977 self.$el.html(QWeb.render('Sidebar', {widget: self}));
979 // Hides Sidebar sections when item list is empty
980 this.$('.oe_form_dropdown_section').each(function() {
981 $(this).toggle(!!$(this).find('li').length);
985 * For each item added to the section:
988 * will be used as the item's name in the sidebar, can be html
991 * descriptor for the action which will be executed, ``action`` and
992 * ``callback`` should be exclusive
995 * function to call when the item is clicked in the sidebar, called
996 * with the item descriptor as its first argument (so information
997 * can be stored as additional keys on the object passed to
1000 * ``classname`` (optional)
1001 * ``@class`` set on the sidebar serialization of the item
1003 * ``title`` (optional)
1004 * will be set as the item's ``@title`` (tooltip)
1006 * @param {String} section_code
1007 * @param {Array<{label, action | callback[, classname][, title]}>} items
1009 add_items: function(section_code, items) {
1012 this.items[section_code].push.apply(this.items[section_code],items);
1016 add_toolbar: function(toolbar) {
1018 _.each(['print','action','relate'], function(type) {
1019 var items = toolbar[type];
1021 for (var i = 0; i < items.length; i++) {
1023 label: items[i]['name'],
1025 classname: 'oe_sidebar_' + type
1028 self.add_items(type=='print' ? 'print' : 'other', items);
1032 on_item_action_clicked: function(item) {
1034 self.getParent().sidebar_context().then(function (context) {
1035 var ids = self.getParent().get_selected_ids();
1036 if (ids.length == 0) {
1037 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
1040 var additional_context = _.extend({
1043 active_model: self.getParent().dataset.model
1045 self.rpc("/web/action/load", {
1046 action_id: item.action.id,
1047 context: additional_context
1048 }).then(function(result) {
1049 result.context = _.extend(result.context || {},
1050 additional_context);
1051 result.flags = result.flags || {};
1052 result.flags.new_window = true;
1053 self.do_action(result, function () {
1055 self.getParent().reload();
1060 do_attachement_update: function(dataset, model_id) {
1061 this.dataset = dataset;
1062 this.model_id = model_id;
1064 this.on_attachments_loaded([]);
1066 var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
1067 var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
1068 ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
1071 on_attachments_loaded: function(attachments) {
1074 var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
1075 _.each(attachments,function(a) {
1077 if(a.type === "binary") {
1078 a.url = prefix + a.id + '&t=' + (new Date().getTime());
1081 self.items['files'] = attachments;
1083 this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
1084 this.$el.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
1086 on_attachment_changed: function(e) {
1087 var $e = $(e.target);
1088 if ($e.val() !== '') {
1089 this.$el.find('form.oe_form_binary_form').submit();
1090 $e.parent().find('input[type=file]').prop('disabled', true);
1091 $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
1092 this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
1093 instance.web.blockUI();
1096 on_attachment_delete: function(e) {
1099 e.stopPropagation();
1101 var $e = $(e.currentTarget);
1102 if (confirm(_t("Do you really want to delete this attachment ?"))) {
1103 (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1104 self.do_attachement_update(self.dataset, self.model_id);
1110 instance.web.View = instance.web.Widget.extend({
1111 // name displayed in view switchers
1114 * Define a view type for each view to allow automatic call to fields_view_get.
1116 view_type: undefined,
1117 init: function(parent, dataset, view_id, options) {
1118 this._super(parent);
1119 this.dataset = dataset;
1120 this.view_id = view_id;
1121 this.set_default_options(options);
1123 start: function () {
1124 return this.load_view();
1126 load_view: function() {
1127 if (this.embedded_view) {
1128 var def = $.Deferred();
1130 $.async_when().then(function() {def.resolve(self.embedded_view);});
1131 return def.pipe(this.on_loaded);
1133 var context = new instance.web.CompoundContext(this.dataset.get_context());
1134 if (! this.view_type)
1135 console.warn("view_type is not defined", this);
1136 return this.rpc("/web/view/load", {
1137 "model": this.dataset.model,
1138 "view_id": this.view_id,
1139 "view_type": this.view_type,
1140 toolbar: !!this.options.$sidebar,
1142 }).pipe(this.on_loaded);
1146 * Called after a successful call to fields_view_get.
1147 * Must return a promise.
1149 on_loaded: function(fields_view_get) {
1151 set_default_options: function(options) {
1152 this.options = options || {};
1153 _.defaults(this.options, {
1154 // All possible views options should be defaulted here
1158 action_views_ids: {}
1162 * Fetches and executes the action identified by ``action_data``.
1164 * @param {Object} action_data the action descriptor data
1165 * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1166 * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1167 * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1168 * @param {Object} [action_data.context=null] additional action context, to add to the current context
1169 * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1170 * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1171 * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1173 do_execute_action: function (action_data, dataset, record_id, on_closed) {
1175 var result_handler = function () {
1176 if (on_closed) { on_closed.apply(null, arguments); }
1177 if (self.getParent() && self.getParent().on_action_executed) {
1178 return self.getParent().on_action_executed.apply(null, arguments);
1181 var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1183 var handler = function (r) {
1185 if (action && action.constructor == Object) {
1186 var ncontext = new instance.web.CompoundContext(context);
1189 active_id: record_id,
1190 active_ids: [record_id],
1191 active_model: dataset.model
1194 ncontext.add(action.context || {});
1195 return self.rpc('/web/session/eval_domain_and_context', {
1196 contexts: [ncontext],
1198 }).pipe(function (results) {
1199 action.context = results.context;
1200 /* niv: previously we were overriding once more with action_data.context,
1201 * I assumed this was not a correct behavior and removed it
1203 return self.do_action(action, result_handler);
1206 return result_handler();
1210 if (action_data.special) {
1211 return handler({"type":"ir.actions.act_window_close"});
1212 } else if (action_data.type=="object") {
1213 var args = [[record_id]], additional_args = [];
1214 if (action_data.args) {
1216 // Warning: quotes and double quotes problem due to json and xml clash
1217 // Maybe we should force escaping in xml or do a better parse of the args array
1218 additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1219 args = args.concat(additional_args);
1221 console.error("Could not JSON.parse arguments", action_data.args);
1225 return dataset.call_button(action_data.name, args).then(handler);
1226 } else if (action_data.type=="action") {
1227 return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).then(handler);
1229 return dataset.exec_workflow(record_id, action_data.name).then(handler);
1233 * Directly set a view to use instead of calling fields_view_get. This method must
1234 * be called before start(). When an embedded view is set, underlying implementations
1235 * of instance.web.View must use the provided view instead of any other one.
1237 * @param embedded_view A view.
1239 set_embedded_view: function(embedded_view) {
1240 this.embedded_view = embedded_view;
1242 do_show: function () {
1245 do_hide: function () {
1248 do_push_state: function(state) {
1249 if (this.getParent() && this.getParent().do_push_state) {
1250 this.getParent().do_push_state(state);
1253 do_load_state: function(state, warm) {
1256 * Switches to a specific view type
1258 * @param {String} view view type to switch to
1260 do_switch_view: function(view) {
1261 this.trigger('switch_mode',view);
1264 * Cancels the switch to the current view, switches to the previous one
1266 * @param {Object} [options]
1267 * @param {Boolean} [options.created=false] resource was created
1268 * @param {String} [options.default=null] view to switch to if no previous view
1271 do_search: function(view) {
1273 on_sidebar_export: function() {
1274 new instance.web.DataExport(this, this.dataset).open();
1276 sidebar_context: function () {
1280 * Asks the view to reload itself, if the reloading is asynchronous should
1281 * return a {$.Deferred} indicating when the reloading is done.
1283 reload: function () {
1287 * Return whether the user can perform the action ('create', 'edit', 'delete') in this view.
1288 * An action is disabled by setting the corresponding attribute in the view's main element,
1289 * like: <form string="" create="false" edit="false" delete="false">
1291 is_action_enabled: function(action) {
1292 var attrs = this.fields_view.arch.attrs;
1293 return (action in attrs) ? JSON.parse(attrs[action]) : true;
1297 instance.web.xml_to_json = function(node) {
1298 switch (node.nodeType) {
1304 var attrs = $(node).getAttributes();
1305 _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1308 attrs[key] = JSON.parse(attrs[key]);
1313 tag: node.tagName.toLowerCase(),
1315 children: _.map(node.childNodes, instance.web.xml_to_json)
1319 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1320 // For debugging purpose, this function will convert a json node back to xml
1321 indent = indent || 0;
1322 var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1323 r = sindent + '<' + node.tag,
1324 cr = human_readable ? '\n' : '';
1326 if (typeof(node) === 'string') {
1327 return sindent + node;
1328 } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1330 _.str.sprintf("Node [%s] is not a JSONified XML node",
1331 JSON.stringify(node)));
1333 for (var attr in node.attrs) {
1334 var vattr = node.attrs[attr];
1335 if (typeof(vattr) !== 'string') {
1337 vattr = JSON.stringify(vattr);
1339 vattr = vattr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
1340 if (human_readable) {
1341 vattr = vattr.replace(/"/g, "'");
1343 r += ' ' + attr + '="' + vattr + '"';
1345 if (node.children && node.children.length) {
1348 for (var i = 0, ii = node.children.length; i < ii; i++) {
1349 childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1351 r += childs.join(cr);
1352 r += cr + sindent + '</' + node.tag + '>';
1358 instance.web.xml_to_str = function(node) {
1359 if (window.ActiveXObject) {
1362 return (new XMLSerializer()).serializeToString(node);
1365 instance.web.str_to_xml = function(s) {
1366 if (window.DOMParser) {
1367 var dp = new DOMParser();
1368 var r = dp.parseFromString(s, "text/xml");
1369 if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1370 throw new Error("Could not parse string to xml");
1376 xDoc = new ActiveXObject("MSXML2.DOMDocument");
1378 throw new Error("Could not find a DOM Parser: " + e.message);
1381 xDoc.preserveWhiteSpace = true;
1387 * Registry for all the main views
1389 instance.web.views = new instance.web.Registry();
1393 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: