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