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