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