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