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