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