[WIP] Breakpoint commit. Gonna refactor everything
[odoo/odoo.git] / addons / web / static / src / js / views.js
1 /*---------------------------------------------------------
2  * OpenERP web library
3  *---------------------------------------------------------*/
4
5 openerp.web.views = function(instance) {
6 var QWeb = instance.web.qweb,
7     _t = instance.web._t;
8
9 instance.web.ActionManager = instance.web.Widget.extend({
10     init: function(parent) {
11         this._super(parent);
12         this.inner_action = null;
13         this.inner_viewmanager = null;
14         this.dialog = null;
15         this.dialog_viewmanager = null;
16         this.client_widget = null;
17     },
18     start: function() {
19         this._super.apply(this, arguments);
20         this.breadcrumb = new instance.web.BreadCrumb(this);
21     },
22     dialog_stop: function () {
23         if (this.dialog) {
24             this.dialog_viewmanager.destroy();
25             this.dialog_viewmanager = null;
26             this.dialog.destroy();
27             this.dialog = null;
28         }
29     },
30     content_stop: function () {
31         // TODO: problem with bread crumb here. Check if those references are needed
32         if (this.inner_viewmanager) {
33             this.inner_viewmanager.destroy();
34             this.inner_viewmanager = null;
35         }
36         if (this.client_widget) {
37             this.client_widget.destroy();
38             this.client_widget = null;
39         }
40     },
41     do_push_state: function(state) {
42         if (this.getParent() && this.getParent().do_push_state) {
43             if (this.inner_action) {
44                 state['title'] = this.inner_action.name;
45                 state['model'] = this.inner_action.res_model;
46                 if (this.inner_action.id) {
47                     state['action_id'] = this.inner_action.id;
48                 }
49             }
50             this.getParent().do_push_state(state);
51         }
52     },
53     do_load_state: function(state, warm) {
54         var self = this,
55             action_loaded;
56         if (state.action_id) {
57             var run_action = (!this.inner_viewmanager) || this.inner_viewmanager.action.id !== state.action_id;
58             if (run_action) {
59                 this.null_action();
60                 action_loaded = this.do_action(state.action_id);
61                 instance.webclient.menu.has_been_loaded.then(function() {
62                     instance.webclient.menu.open_action(state.action_id);
63                 });
64             }
65         } else if (state.model && state.id) {
66             // TODO handle context & domain ?
67             this.null_action();
68             var action = {
69                 res_model: state.model,
70                 res_id: state.id,
71                 type: 'ir.actions.act_window',
72                 views: [[false, 'form']]
73             };
74             action_loaded = this.do_action(action);
75         } else if (state.sa) {
76             // load session action
77             var self = this;
78             this.null_action();
79             action_loaded = this.rpc('/web/session/get_session_action',  {key: state.sa}).pipe(function(action) {
80                 if (action) {
81                     return self.do_action(action);
82                 }
83             });
84         } else if (state.client_action) {
85             this.null_action();
86             var action = state.client_action;
87             if(_.isString(action)) {
88                 action = {
89                     tag: action,
90                     params: state,
91                 };
92             }
93             this.ir_actions_client(action);
94         }
95
96         $.when(action_loaded || null).then(function() {
97             if (self.inner_viewmanager) {
98                 self.inner_viewmanager.do_load_state(state, warm);
99             }
100         });
101     },
102     do_action: function(action, on_close) {
103         if (_.isNumber(action)) {
104             var self = this;
105             return self.rpc("/web/action/load", { action_id: action }, function(result) {
106                 self.do_action(result.result, on_close);
107             });
108         }
109         if (!action.type) {
110             console.error("No type for action", action);
111             return;
112         }
113         var type = action.type.replace(/\./g,'_');
114         var popup = action.target === 'new';
115         var inline = action.target === 'inline';
116         action.flags = _.extend({
117             views_switcher : !popup && !inline,
118             search_view : !popup && !inline,
119             action_buttons : !popup && !inline,
120             sidebar : !popup && !inline,
121             pager : !popup && !inline,
122             display_title : !popup
123         }, action.flags || {});
124         if (!(type in this)) {
125             console.error("Action manager can't handle action of type " + action.type, action);
126             return;
127         }
128         return this[type](action, on_close);
129     },
130     null_action: function() {
131         this.dialog_stop();
132         this.content_stop();
133     },
134     ir_actions_act_window: function (action, on_close) {
135         var self = this;
136         if (_(['base.module.upgrade', 'base.setup.installer'])
137                 .contains(action.res_model)) {
138             var old_close = on_close;
139             on_close = function () {
140                 instance.webclient.do_reload().then(old_close);
141             };
142         }
143         if (action.target === 'new') {
144             if (this.dialog === null) {
145                 this.dialog = new instance.web.Dialog(this, { width: '80%' });
146                 if(on_close)
147                     this.dialog.on_close.add(on_close);
148             } else {
149                 this.dialog_viewmanager.destroy();
150             }
151             this.dialog.dialog_title = action.name;
152             this.dialog_viewmanager = new instance.web.ViewManagerAction(this.dialog, action);
153             this.dialog_viewmanager.appendTo(this.dialog.$element);
154             this.dialog_viewmanager.$element.addClass("oe_view_manager_" + action.target);
155             this.dialog.open();
156         } else  {
157             this.dialog_stop();
158             //this.content_stop();
159             this.breadcrumb.hide_items();
160             if(action.menu_id) {
161                 return this.getParent().do_action(action, function () {
162                     instance.webclient.menu.open_menu(action.menu_id);
163                 });
164             }
165             this.inner_action = action;
166             var inner_viewmanager = this.inner_viewmanager = new instance.web.ViewManagerAction(this, action);
167             this.inner_viewmanager.appendTo(this.$element);
168             this.inner_viewmanager.$element.addClass("oe_view_manager_" + action.target);
169             this.breadcrumb.push_actionmanager(inner_viewmanager);
170         }
171     },
172     ir_actions_act_window_close: function (action, on_closed) {
173         if (!this.dialog && on_closed) {
174             on_closed();
175         }
176         this.dialog_stop();
177     },
178     ir_actions_server: function (action, on_closed) {
179         var self = this;
180         this.rpc('/web/action/run', {
181             action_id: action.id,
182             context: action.context || {}
183         }).then(function (action) {
184             self.do_action(action, on_closed)
185         });
186     },
187     ir_actions_client: function (action) {
188         //this.content_stop();
189         this.dialog_stop();
190         this.breadcrumb.hide_items();
191         var ClientWidget = instance.web.client_actions.get_object(action.tag);
192         (this.client_widget = new ClientWidget(this, action.params)).appendTo(this.$element);
193         this.breadcrumb.push({
194             widget: this.client_widget,
195             title: action.name
196         });
197     },
198     ir_actions_report_xml: function(action, on_closed) {
199         var self = this;
200         $.blockUI();
201         self.rpc("/web/session/eval_domain_and_context", {
202             contexts: [action.context],
203             domains: []
204         }).then(function(res) {
205             action = _.clone(action);
206             action.context = res.context;
207             self.session.get_file({
208                 url: '/web/report',
209                 data: {action: JSON.stringify(action)},
210                 complete: $.unblockUI,
211                 success: function(){
212                     if (!self.dialog && on_closed) {
213                         on_closed();
214                     }
215                     self.dialog_stop();
216                 },
217                 error: instance.webclient.crashmanager.on_rpc_error
218             })
219         });
220     },
221     ir_actions_act_url: function (action) {
222         window.open(action.url, action.target === 'self' ? '_self' : '_blank');
223     },
224     ir_ui_menu: function (action) {
225         this.getParent().do_action(action);
226     }
227 });
228
229 instance.web.BreadCrumb = instance.web.CallbackEnabled.extend({
230     init: function(parent) {
231         this._super(parent);
232         this.action_manager = parent;
233         this.items = [];
234         this.action_manager.$element.on('click', '.oe_breadcrumb_item', this.on_item_clicked);
235     },
236     push: function(item) {
237         if (!item.show) {
238             item.show = function() {
239                 item.widget.$element.show();
240             };
241         }
242         if (!item.hide) {
243             item.hide = function() {
244                 item.widget.$element.hide();
245             };
246         }
247         if (!item.destroy) {
248             item.destroy = function() {
249                 item.widget.destroy();
250             };
251         }
252         if (!item.get_title) {
253             item.get_title = function() {
254                 return item.title || item.widget.get('title');
255             };
256         }
257         this.items.push(item);
258     },
259     push_actionmanager: function(am) {
260         var self = this;
261         var bookmarked_view = am.active_view;
262         this.push({
263             widget: am,
264             show: function() {
265                 am.$element.show();
266                 am.on_mode_switch(current_view);
267             }
268         });
269         am.on_mode_switch.add_first(function(mode) {
270             if (mode === 'form' && !am.views[mode].controller) {
271                 self.push({
272                     widget: am,
273                     show: function() {
274                         am.$element.show();
275                         inner_viewmanager.on_mode_switch('form');
276                     },
277                     action: action,
278                     get_title: function() {
279                         var form = inner_viewmanager.views['form'].controller;
280                         if (form) {
281                             return form.get('title');
282                         }
283                     }
284                 });
285             }
286         });
287     },
288     pop: function() {
289         this.remove_item(this.items.length - 1);
290         this.select_item(this.items.length - 1);
291     },
292     get_title: function() {
293         return QWeb.render('BreadCrumb', { widget: this });
294     },
295     hide_items: function() {
296         _.each(this.items, function(i) {
297             i.hide();
298         });
299     },
300     on_item_clicked: function(ev) {
301         var $e = $(ev.target);
302         var index = $e.data('index');
303         this.select_item(index);
304     },
305     select_item: function(index) {
306         for (var i = index + 1; i < this.items.length; i += 1) {
307             this.remove_item(i);
308         }
309         var item = this.items[index];
310         if (item) {
311             item.show();
312         } else {
313             console.warn("Breadcrumb: Can't select item at index", index);
314         }
315     },
316     remove_item: function(index) {
317         var item = this.items.splice(index, 1)[0];
318         if (item) {
319             item.destroy();
320         } else {
321             console.warn("Breadcrumb: Can't remove item at index", index);
322         }
323     },
324     clear: function() {
325         while (this.items.length) {
326             this.remove_item(0);
327         }
328     },
329 });
330
331 instance.web.ViewManager =  instance.web.Widget.extend({
332     template: "ViewManager",
333     init: function(parent, dataset, views, flags) {
334         this._super(parent);
335         this.model = dataset ? dataset.model : undefined;
336         this.dataset = dataset;
337         this.searchview = null;
338         this.active_view = null;
339         this.views_src = _.map(views, function(x) {
340             if (x instanceof Array) {
341                 var View = instance.web.views.get_object(x[1], true);
342                 return {
343                     view_id: x[0],
344                     view_type: x[1],
345                     label: View ? View.prototype.display_name : (void 'nope')
346                 };
347             } else {
348                 return x;
349             }
350         });
351         this.views = {};
352         this.flags = flags || {};
353         this.registry = instance.web.views;
354         this.views_history = [];
355     },
356     /**
357      * @returns {jQuery.Deferred} initial view loading promise
358      */
359     start: function() {
360         this._super();
361         var self = this;
362         this.$element.find('.oe_view_manager_switch a').click(function() {
363             self.on_mode_switch($(this).data('view-type'));
364         }).tipsy();
365         var views_ids = {};
366         _.each(this.views_src, function(view) {
367             self.views[view.view_type] = $.extend({}, view, {
368                 deferred : $.Deferred(),
369                 controller : null,
370                 options : _.extend({
371                     $buttons : self.$element.find('.oe_view_manager_buttons'),
372                     $sidebar : self.flags.sidebar ? self.$element.find('.oe_view_manager_sidebar') : undefined,
373                     $pager : self.$element.find('.oe_view_manager_pager'),
374                     action : self.action,
375                     action_views_ids : views_ids
376                 }, self.flags, self.flags[view.view_type] || {}, view.options || {})
377             });
378             views_ids[view.view_type] = view.view_id;
379         });
380         if (this.flags.views_switcher === false) {
381             this.$element.find('.oe_view_manager_switch').hide();
382         }
383         this.on('change:title', this, function() {
384             var breadcrumb = self.getParent().breadcrumb;
385             if (breadcrumb) {
386                 self.$element.find('.oe_view_title_text:first').html(breadcrumb.get_title());
387             } else {
388                 self.$element.find('.oe_view_title_text:first').text(self.get('title'));
389             }
390         });
391         // If no default view defined, switch to the first one in sequence
392         var default_view = this.flags.default_view || this.views_src[0].view_type;
393         return this.on_mode_switch(default_view);
394     },
395     /**
396      * Asks the view manager to switch visualization mode.
397      *
398      * @param {String} view_type type of view to display
399      * @param {Boolean} [no_store=false] don't store the view being switched to on the switch stack
400      * @returns {jQuery.Deferred} new view loading promise
401      */
402     on_mode_switch: function(view_type, no_store, view_options) {
403         var self = this;
404         var view = this.views[view_type];
405         var view_promise;
406         if(!view)
407             return $.Deferred().reject();
408
409         if (!no_store) {
410             this.views_history.push(view_type);
411         }
412         this.active_view = view_type;
413
414         if (!view.controller) {
415             // Lazy loading of views
416             var controllerclass = this.registry.get_object(view_type);
417             var options = _.clone(view.options);
418             if (view_type === "form" && this.action) {
419                 switch (this.action.target) {
420                     case 'new':
421                     case 'inline':
422                         options.initial_mode = 'edit';
423                         break;
424                 }
425             }
426             var controller = new controllerclass(this, this.dataset, view.view_id, options);
427             controller.on("change:title", this, function() {
428                 if (self.active_view === view_type) {
429                     self.set({ 'title' : controller.get('title') });
430                 }
431             });
432             if (view.embedded_view) {
433                 controller.set_embedded_view(view.embedded_view);
434             }
435             controller.do_switch_view.add_last(_.bind(this.switch_view, this));
436
437             controller.do_prev_view.add_last(this.on_prev_view);
438             var container = this.$element.find(".oe_view_manager_view_" + view_type);
439             view_promise = controller.appendTo(container);
440             this.views[view_type].controller = controller;
441             this.views[view_type].deferred.resolve(view_type);
442             $.when(view_promise).then(function() {
443                 self.on_controller_inited(view_type, controller);
444                 if (self.searchview
445                         && self.flags.auto_search
446                         && view.controller.searchable !== false) {
447                     self.searchview.ready.then(self.searchview.do_search);
448                 }
449             });
450         } else if (this.searchview
451                 && self.flags.auto_search
452                 && view.controller.searchable !== false) {
453             this.searchview.ready.then(this.searchview.do_search);
454         }
455
456         if (this.searchview) {
457             this.searchview[(view.controller.searchable === false || this.searchview.hidden) ? 'hide' : 'show']();
458         }
459
460         this.$element
461             .find('.oe_view_manager_switch a').parent().removeClass('active');
462         this.$element
463             .find('.oe_view_manager_switch a').filter('[data-view-type="' + view_type + '"]')
464             .parent().addClass('active');
465
466         $.when(view_promise).then(function () {
467             _.each(_.keys(self.views), function(view_name) {
468                 var controller = self.views[view_name].controller;
469                 if (controller) {
470                     var container = self.$element.find(".oe_view_manager_view_" + view_name + ":first");
471                     if (view_name === view_type) {
472                         container.show();
473                         controller.do_show(view_options || {});
474                     } else {
475                         container.hide();
476                         controller.do_hide();
477                     }
478                 }
479             });
480         });
481         return view_promise;
482     },
483     /**
484      * Method used internally when a view asks to switch view. This method is meant
485      * to be extended by child classes to change the default behavior, which simply
486      * consist to switch to the asked view.
487      */
488     switch_view: function(view_type, no_store, options) {
489         return this.on_mode_switch(view_type, no_store, options);
490     },
491     /**
492      * Returns to the view preceding the caller view in this manager's
493      * navigation history (the navigation history is appended to via
494      * on_mode_switch)
495      *
496      * @param {Object} [options]
497      * @param {Boolean} [options.created=false] resource was created
498      * @param {String} [options.default=null] view to switch to if no previous view
499      * @returns {$.Deferred} switching end signal
500      */
501     on_prev_view: function (options) {
502         options = options || {};
503         var current_view = this.views_history.pop();
504         var previous_view = this.views_history[this.views_history.length - 1] || options['default'];
505         if (options.created && current_view === 'form' && previous_view === 'list') {
506             // APR special case: "If creation mode from list (and only from a list),
507             // after saving, go to page view (don't come back in list)"
508             return this.on_mode_switch('form');
509         } else if (options.created && !previous_view && this.action && this.action.flags.default_view === 'form') {
510             // APR special case: "If creation from dashboard, we have no previous view
511             return this.on_mode_switch('form');
512         }
513         return this.on_mode_switch(previous_view, true);
514     },
515     /**
516      * Sets up the current viewmanager's search view.
517      *
518      * @param {Number|false} view_id the view to use or false for a default one
519      * @returns {jQuery.Deferred} search view startup deferred
520      */
521     setup_search_view: function(view_id, search_defaults) {
522         var self = this;
523         if (this.searchview) {
524             this.searchview.destroy();
525         }
526         this.searchview = new instance.web.SearchView(this, this.dataset, view_id, search_defaults, this.flags.search_view === false);
527
528         this.searchview.on_search.add(this.do_searchview_search);
529         return this.searchview.appendTo(this.$element.find(".oe_view_manager_view_search"));
530     },
531     do_searchview_search: function(domains, contexts, groupbys) {
532         var self = this,
533             controller = this.views[this.active_view].controller,
534             action_context = this.action.context || {};
535         this.rpc('/web/session/eval_domain_and_context', {
536             domains: [this.action.domain || []].concat(domains || []),
537             contexts: [action_context].concat(contexts || []),
538             group_by_seq: groupbys || []
539         }, function (results) {
540             self.dataset._model = new instance.web.Model(
541                 self.dataset.model, results.context, results.domain);
542             var groupby = results.group_by.length
543                         ? results.group_by
544                         : action_context.group_by;
545             if (_.isString(groupby)) {
546                 groupby = [groupby];
547             }
548             controller.do_search(results.domain, results.context, groupby || []);
549         });
550     },
551     /**
552      * Event launched when a controller has been inited.
553      *
554      * @param {String} view_type type of view
555      * @param {String} view the inited controller
556      */
557     on_controller_inited: function(view_type, view) {
558     },
559     /**
560      * Called when one of the view want to execute an action
561      */
562     on_action: function(action) {
563     },
564     on_create: function() {
565     },
566     on_remove: function() {
567     },
568     on_edit: function() {
569     },
570     /**
571      * Called by children view after executing an action
572      */
573     on_action_executed: function () {
574     },
575 });
576
577 instance.web.ViewManagerAction = instance.web.ViewManager.extend({
578     template:"ViewManagerAction",
579     /**
580      * @constructs instance.web.ViewManagerAction
581      * @extends instance.web.ViewManager
582      *
583      * @param {instance.web.ActionManager} parent parent object/widget
584      * @param {Object} action descriptor for the action this viewmanager needs to manage its views.
585      */
586     init: function(parent, action) {
587         // dataset initialization will take the session from ``this``, so if we
588         // do not have it yet (and we don't, because we've not called our own
589         // ``_super()``) rpc requests will blow up.
590         var flags = action.flags || {};
591         if (!('auto_search' in flags)) {
592             flags.auto_search = action.auto_search !== false;
593         }
594         if (action.res_model == 'board.board' && action.view_mode === 'form') {
595             // Special case for Dashboards
596             _.extend(flags, {
597                 views_switcher : false,
598                 display_title : false,
599                 search_view : false,
600                 pager : false,
601                 sidebar : false,
602                 action_buttons : false
603             });
604         }
605         this._super(parent, null, action.views, flags);
606         this.session = parent.session;
607         this.action = action;
608         var dataset = new instance.web.DataSetSearch(this, action.res_model, action.context, action.domain);
609         if (action.res_id) {
610             dataset.ids.push(action.res_id);
611             dataset.index = 0;
612         }
613         this.dataset = dataset;
614
615         // setup storage for session-wise menu hiding
616         if (this.session.hidden_menutips) {
617             return;
618         }
619         this.session.hidden_menutips = {};
620     },
621     /**
622      * Initializes the ViewManagerAction: sets up the searchview (if the
623      * searchview is enabled in the manager's action flags), calls into the
624      * parent to initialize the primary view and (if the VMA has a searchview)
625      * launches an initial search after both views are done rendering.
626      */
627     start: function() {
628         var self = this,
629             searchview_loaded,
630             search_defaults = {};
631         _.each(this.action.context, function (value, key) {
632             var match = /^search_default_(.*)$/.exec(key);
633             if (match) {
634                 search_defaults[match[1]] = value;
635             }
636         });
637         // init search view
638         var searchview_id = this.action['search_view_id'] && this.action['search_view_id'][0];
639
640         searchview_loaded = this.setup_search_view(searchview_id || false, search_defaults);
641
642         var main_view_loaded = this._super();
643
644         var manager_ready = $.when(searchview_loaded, main_view_loaded);
645
646         this.$element.find('.oe_debug_view').change(this.on_debug_changed);
647
648         if (this.action.help && !this.flags.low_profile) {
649             var Users = new instance.web.DataSet(self, 'res.users'),
650                 $tips = this.$element.find('.oe_view_manager_menu_tips');
651             $tips.delegate('blockquote button', 'click', function() {
652                 var $this = $(this);
653                 //noinspection FallthroughInSwitchStatementJS
654                 switch ($this.attr('name')) {
655                 case 'disable':
656                     Users.write(self.session.uid, {menu_tips:false});
657                 case 'hide':
658                     $this.closest('blockquote').hide();
659                     self.session.hidden_menutips[self.action.id] = true;
660                 }
661             });
662             if (!(self.action.id in self.session.hidden_menutips)) {
663                 Users.read_ids([this.session.uid], ['menu_tips']).then(function(users) {
664                     var user = users[0];
665                     if (!(user && user.id === self.session.uid)) {
666                         return;
667                     }
668                     $tips.find('blockquote').toggle(user.menu_tips);
669                 });
670             }
671         }
672
673         return manager_ready;
674     },
675     on_debug_changed: function (evt) {
676         var self = this,
677             $sel = $(evt.currentTarget),
678             $option = $sel.find('option:selected'),
679             val = $sel.val(),
680             current_view = this.views[this.active_view].controller;
681         switch (val) {
682             case 'fvg':
683                 var dialog = new instance.web.Dialog(this, { title: _t("Fields View Get"), width: '95%' }).open();
684                 $('<pre>').text(instance.web.json_node_to_xml(current_view.fields_view.arch, true)).appendTo(dialog.$element);
685                 break;
686             case 'perm_read':
687                 var ids = current_view.get_selected_ids();
688                 if (ids.length === 1) {
689                     this.dataset.call('perm_read', [ids]).then(function(result) {
690                         var dialog = new instance.web.Dialog(this, {
691                             title: _.str.sprintf(_t("View Log (%s)"), self.dataset.model),
692                             width: 400
693                         }, QWeb.render('ViewManagerDebugViewLog', {
694                             perm : result[0],
695                             format : instance.web.format_value
696                         })).open();
697                     });
698                 }
699                 break;
700             case 'toggle_layout_outline':
701                 current_view.rendering_engine.toggle_layout_debugging();
702                 break;
703             case 'fields':
704                 this.dataset.call_and_eval(
705                         'fields_get', [false, {}], null, 1).then(function (fields) {
706                     var $root = $('<dl>');
707                     _(fields).each(function (attributes, name) {
708                         $root.append($('<dt>').append($('<h4>').text(name)));
709                         var $attrs = $('<dl>').appendTo(
710                                 $('<dd>').appendTo($root));
711                         _(attributes).each(function (def, name) {
712                             if (def instanceof Object) {
713                                 def = JSON.stringify(def);
714                             }
715                             $attrs
716                                 .append($('<dt>').text(name))
717                                 .append($('<dd style="white-space: pre-wrap;">').text(def));
718                         });
719                     });
720                     new instance.web.Dialog(self, {
721                         title: _.str.sprintf(_t("Model %s fields"),
722                                              self.dataset.model),
723                         width: '95%'}, $root).open();
724                 });
725                 break;
726             case 'manage_views':
727                 if (current_view.fields_view && current_view.fields_view.arch) {
728                     var view_editor = new instance.web.ViewEditor(current_view, current_view.$element, this.dataset, current_view.fields_view.arch);
729                     view_editor.start();
730                 } else {
731                     this.do_warn(_t("Manage Views"),
732                             _t("Could not find current view declaration"));
733                 }
734                 break;
735             case 'edit_workflow':
736                 return this.do_action({
737                     res_model : 'workflow',
738                     domain : [['osv', '=', this.dataset.model]],
739                     views: [[false, 'list'], [false, 'form'], [false, 'diagram']],
740                     type : 'ir.actions.act_window',
741                     view_type : 'list',
742                     view_mode : 'list'
743                 });
744                 break;
745             case 'edit':
746                 this.do_edit_resource($option.data('model'), $option.data('id'), { name : $option.text() });
747                 break;
748             case 'manage_filters':
749                 this.do_action({
750                     res_model: 'ir.filters',
751                     views: [[false, 'list'], [false, 'form']],
752                     type: 'ir.actions.act_window',
753                     context: {
754                         search_default_my_filters: true,
755                         search_default_model_id: this.dataset.model
756                     }
757                 });
758                 break;
759             default:
760                 if (val) {
761                     console.log("No debug handler for ", val);
762                 }
763         }
764         evt.currentTarget.selectedIndex = 0;
765     },
766     do_edit_resource: function(model, id, action) {
767         var action = _.extend({
768             res_model : model,
769             res_id : id,
770             type : 'ir.actions.act_window',
771             view_type : 'form',
772             view_mode : 'form',
773             views : [[false, 'form']],
774             target : 'new',
775             flags : {
776                 action_buttons : true,
777                 form : {
778                     resize_textareas : true
779                 }
780             }
781         }, action || {});
782         this.do_action(action);
783     },
784     on_mode_switch: function (view_type, no_store, options) {
785         var self = this;
786
787         return $.when(this._super.apply(this, arguments)).then(function () {
788             var controller = self.views[self.active_view].controller,
789                 fvg = controller.fields_view,
790                 view_id = (fvg && fvg.view_id) || '--';
791             self.$element.find('.oe_debug_view').html(QWeb.render('ViewManagerDebug', {
792                 view: controller,
793                 view_manager: self
794             }));
795             if (!self.action.name && fvg) {
796                 self.$element.find('.oe_view_title_text').text(fvg.arch.attrs.string || fvg.name);
797             }
798
799         });
800     },
801     do_push_state: function(state) {
802         if (this.getParent() && this.getParent().do_push_state) {
803             state["view_type"] = this.active_view;
804             this.getParent().do_push_state(state);
805         }
806     },
807     do_load_state: function(state, warm) {
808         var self = this,
809             defs = [];
810         if (state.view_type && state.view_type !== this.active_view) {
811             defs.push(
812                 this.views[this.active_view].deferred.pipe(function() {
813                     return self.on_mode_switch(state.view_type, true);
814                 })
815             );
816         } 
817
818         $.when(defs).then(function() {
819             self.views[self.active_view].controller.do_load_state(state, warm);
820         });
821     },
822     set_title: function (title) {
823         this.getParent().breadcrumb.update();
824     }
825 });
826
827 instance.web.Sidebar = instance.web.Widget.extend({
828     init: function(parent) {
829         var self = this;
830         this._super(parent);
831         var view = this.getParent();
832         this.sections = [
833             { 'name' : 'print', 'label' : _t('Print'), },
834             { 'name' : 'files', 'label' : _t('Attachment'), },
835             { 'name' : 'other', 'label' : _t('More'), }
836         ];
837         this.items = {
838             'print' : [],
839             'files' : [],
840             'other' : []
841         };
842         if (this.session.uid === 1) {
843             var item = { label: _t("Translate"), callback: view.on_sidebar_translate, title: _t("Technical translation") };
844             this.items.other.push(item);
845         }
846         this.fileupload_id = _.uniqueId('oe_fileupload');
847         $(window).on(this.fileupload_id, function() {
848             var args = [].slice.call(arguments).slice(1);
849             if (args[0] && args[0].error) {
850                 alert(args[0].error);
851             } else {
852                 self.do_attachement_update(self.dataset, self.model_id);
853             }
854             $.unblockUI();
855         });
856     },
857     start: function() {
858         var self = this;
859         this._super(this);
860         this.redraw();
861         this.$element.on('click','.oe_dropdown_menu li a', function(event) {
862             var section = $(this).data('section');
863             var index = $(this).data('index');
864             var item = self.items[section][index];
865             if (item.callback) {
866                 item.callback.apply(self, [item]);
867             } else if (item.action) {
868                 self.on_item_action_clicked(item);
869             } else if (item.url) {
870                 return true;
871             }
872             event.preventDefault();
873         });
874     },
875     redraw: function() {
876         var self = this;
877         self.$element.html(QWeb.render('Sidebar', {widget: self}));
878
879         // Hides Sidebar sections when item list is empty
880         this.$('.oe_form_dropdown_section').each(function() {
881             $(this).toggle(!!$(this).find('li').length);
882         });
883     },
884     /**
885      * For each item added to the section:
886      *
887      * ``label``
888      *     will be used as the item's name in the sidebar, can be html
889      *
890      * ``action``
891      *     descriptor for the action which will be executed, ``action`` and
892      *     ``callback`` should be exclusive
893      *
894      * ``callback``
895      *     function to call when the item is clicked in the sidebar, called
896      *     with the item descriptor as its first argument (so information
897      *     can be stored as additional keys on the object passed to
898      *     ``add_items``)
899      *
900      * ``classname`` (optional)
901      *     ``@class`` set on the sidebar serialization of the item
902      *
903      * ``title`` (optional)
904      *     will be set as the item's ``@title`` (tooltip)
905      *
906      * @param {String} section_code
907      * @param {Array<{label, action | callback[, classname][, title]}>} items
908      */
909     add_items: function(section_code, items) {
910         var self = this;
911         if (items) {
912             this.items[section_code].push.apply(this.items[section_code],items);
913             this.redraw();
914         }
915     },
916     add_toolbar: function(toolbar) {
917         var self = this;
918         _.each(['print','action','relate'], function(type) {
919             var items = toolbar[type];
920             if (items) {
921                 for (var i = 0; i < items.length; i++) {
922                     items[i] = {
923                         label: items[i]['name'],
924                         action: items[i],
925                         classname: 'oe_sidebar_' + type
926                     }
927                 }
928                 self.add_items(type=='print' ? 'print' : 'other', items);
929             }
930         });
931     },
932     on_item_action_clicked: function(item) {
933         var self = this;
934         self.getParent().sidebar_context().then(function (context) {
935             var ids = self.getParent().get_selected_ids();
936             if (ids.length == 0) {
937                 instance.web.dialog($("<div />").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true });
938                 return false;
939             }
940             var additional_context = _.extend({
941                 active_id: ids[0],
942                 active_ids: ids,
943                 active_model: self.getParent().dataset.model
944             }, context);
945             self.rpc("/web/action/load", {
946                 action_id: item.action.id,
947                 context: additional_context
948             }, function(result) {
949                 result.result.context = _.extend(result.result.context || {},
950                     additional_context);
951                 result.result.flags = result.result.flags || {};
952                 result.result.flags.new_window = true;
953                 self.do_action(result.result, function () {
954                     // reload view
955                     self.getParent().reload();
956                 });
957             });
958         });
959     },
960     do_attachement_update: function(dataset, model_id) {
961         this.dataset = dataset;
962         this.model_id = model_id;
963         if (!model_id) {
964             this.on_attachments_loaded([]);
965         } else {
966             var dom = [ ['res_model', '=', dataset.model], ['res_id', '=', model_id], ['type', 'in', ['binary', 'url']] ];
967             var ds = new instance.web.DataSetSearch(this, 'ir.attachment', dataset.get_context(), dom);
968             ds.read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
969         }
970     },
971     on_attachments_loaded: function(attachments) {
972         var self = this;
973         var items = [];
974         var prefix = this.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=name&id=';
975         _.each(attachments,function(a) {
976             a.label = a.name;
977             if(a.type === "binary") {
978                 a.url = prefix  + a.id + '&t=' + (new Date().getTime());
979             }
980         });
981         self.items['files'] = attachments;
982         self.redraw();
983         this.$('.oe_sidebar_add_attachment .oe_form_binary_file').change(this.on_attachment_changed);
984         this.$element.find('.oe_sidebar_delete_item').click(this.on_attachment_delete);
985     },
986     on_attachment_changed: function(e) {
987         var $e = $(e.target);
988         if ($e.val() !== '') {
989             this.$element.find('form.oe_form_binary_form').submit();
990             $e.parent().find('input[type=file]').prop('disabled', true);
991             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
992             this.$('.oe_sidebar_add_attachment span').text(_t('Uploading...'));
993             $.blockUI();
994         }
995     },
996     on_attachment_delete: function(e) {
997         var self = this;
998         e.preventDefault();
999         e.stopPropagation();
1000         var self = this;
1001         var $e = $(e.currentTarget);
1002         if (confirm(_t("Do you really want to delete this attachment ?"))) {
1003             (new instance.web.DataSet(this, 'ir.attachment')).unlink([parseInt($e.attr('data-id'), 10)]).then(function() {
1004                 self.do_attachement_update(self.dataset, self.model_id);
1005             });
1006         }
1007     }
1008 });
1009
1010 instance.web.TranslateDialog = instance.web.Dialog.extend({
1011     dialog_title: {toString: function () { return _t("Translations"); }},
1012     init: function(view) {
1013         // TODO fme: should add the language to fields_view_get because between the fields view get
1014         // and the moment the user opens the translation dialog, the user language could have been changed
1015         this.view_language = view.session.user_context.lang;
1016         this['on_button_' + _t("Save")] = this.on_btn_save;
1017         this['on_button_' + _t("Close")] = this.on_btn_close;
1018         this._super(view, {
1019             width: '80%',
1020             height: '80%'
1021         });
1022         this.view = view;
1023         this.view_type = view.fields_view.type || '';
1024         this.$fields_form = null;
1025         this.$view_form = null;
1026         this.$sidebar_form = null;
1027         this.translatable_fields_keys = _.map(this.view.translatable_fields || [], function(i) { return i.name });
1028         this.languages = null;
1029         this.languages_loaded = $.Deferred();
1030         (new instance.web.DataSetSearch(this, 'res.lang', this.view.dataset.get_context(),
1031             [['translatable', '=', '1']])).read_slice(['code', 'name'], { sort: 'id' }).then(this.on_languages_loaded);
1032     },
1033     start: function() {
1034         var self = this;
1035         this._super();
1036         $.when(this.languages_loaded).then(function() {
1037             self.$element.html(instance.web.qweb.render('TranslateDialog', { widget: self }));
1038             self.$fields_form = self.$element.find('.oe_translation_form');
1039             self.$fields_form.find('.oe_trad_field').change(function() {
1040                 $(this).toggleClass('touched', ($(this).val() != $(this).attr('data-value')));
1041             });
1042         });
1043         return this;
1044     },
1045     on_languages_loaded: function(langs) {
1046         this.languages = langs;
1047         this.languages_loaded.resolve();
1048     },
1049     do_load_fields_values: function(callback) {
1050         var self = this,
1051             deffered = [];
1052         this.$fields_form.find('.oe_trad_field').val('').removeClass('touched');
1053         _.each(self.languages, function(lg) {
1054             var deff = $.Deferred();
1055             deffered.push(deff);
1056             var callback = function(values) {
1057                 _.each(self.translatable_fields_keys, function(f) {
1058                     self.$fields_form.find('.oe_trad_field[name="' + lg.code + '-' + f + '"]').val(values[0][f] || '').attr('data-value', values[0][f] || '');
1059                 });
1060                 deff.resolve();
1061             };
1062             if (lg.code === self.view_language) {
1063                 var values = {};
1064                 _.each(self.translatable_fields_keys, function(field) {
1065                     values[field] = self.view.fields[field].get_value();
1066                 });
1067                 callback([values]);
1068             } else {
1069                 self.rpc('/web/dataset/get', {
1070                     model: self.view.dataset.model,
1071                     ids: [self.view.datarecord.id],
1072                     fields: self.translatable_fields_keys,
1073                     context: self.view.dataset.get_context({
1074                         'lang': lg.code
1075                     })}, callback);
1076             }
1077         });
1078         $.when.apply(null, deffered).then(callback);
1079     },
1080     open: function(field) {
1081         var self = this,
1082             sup = this._super;
1083         $.when(this.languages_loaded).then(function() {
1084             if (self.view.translatable_fields && self.view.translatable_fields.length) {
1085                 self.do_load_fields_values(function() {
1086                     sup.call(self);
1087                     if (field) {
1088                         var $field_input = self.$element.find('tr[data-field="' + field.name + '"] td:nth-child(2) *:first-child');
1089                         self.$element.scrollTo($field_input);
1090                         $field_input.focus();
1091                     }
1092                 });
1093             } else {
1094                 sup.call(self);
1095             }
1096         });
1097     },
1098     on_btn_save: function() {
1099         var trads = {},
1100             self = this,
1101             trads_mutex = new $.Mutex();
1102         self.$fields_form.find('.oe_trad_field.touched').each(function() {
1103             var field = $(this).attr('name').split('-');
1104             if (!trads[field[0]]) {
1105                 trads[field[0]] = {};
1106             }
1107             trads[field[0]][field[1]] = $(this).val();
1108         });
1109         _.each(trads, function(data, code) {
1110             if (code === self.view_language) {
1111                 _.each(data, function(value, field) {
1112                     self.view.fields[field].set_value(value);
1113                 });
1114             }
1115             trads_mutex.exec(function() {
1116                 return self.view.dataset.write(self.view.datarecord.id, data, { context : { 'lang': code } });
1117             });
1118         });
1119         this.close();
1120     },
1121     on_btn_close: function() {
1122         this.close();
1123     }
1124 });
1125
1126 instance.web.View = instance.web.Widget.extend({
1127     template: "EmptyComponent",
1128     // name displayed in view switchers
1129     display_name: '',
1130     /**
1131      * Define a view type for each view to allow automatic call to fields_view_get.
1132      */
1133     view_type: undefined,
1134     init: function(parent, dataset, view_id, options) {
1135         this._super(parent);
1136         this.dataset = dataset;
1137         this.view_id = view_id;
1138         this.set_default_options(options);
1139     },
1140     start: function() {
1141         return this.load_view();
1142     },
1143     load_view: function() {
1144         if (this.embedded_view) {
1145             var def = $.Deferred();
1146             var self = this;
1147             $.async_when().then(function() {def.resolve(self.embedded_view);});
1148             return def.pipe(this.on_loaded);
1149         } else {
1150             var context = new instance.web.CompoundContext(this.dataset.get_context());
1151             if (! this.view_type)
1152                 console.warn("view_type is not defined", this);
1153             return this.rpc("/web/view/load", {
1154                 "model": this.dataset.model,
1155                 "view_id": this.view_id,
1156                 "view_type": this.view_type,
1157                 toolbar: !!this.options.$sidebar,
1158                 context: context
1159                 }).pipe(this.on_loaded);
1160         }
1161     },
1162     /**
1163      * Called after a successful call to fields_view_get.
1164      * Must return a promise.
1165      */
1166     on_loaded: function(fields_view_get) {
1167     },
1168     set_default_options: function(options) {
1169         this.options = options || {};
1170         _.defaults(this.options, {
1171             // All possible views options should be defaulted here
1172             $sidebar: null,
1173             sidebar_id: null,
1174             action: null,
1175             action_views_ids: {}
1176         });
1177     },
1178     open_translate_dialog: function(field) {
1179         if (!this.translate_dialog) {
1180             this.translate_dialog = new instance.web.TranslateDialog(this).start();
1181         }
1182         this.translate_dialog.open(field);
1183     },
1184     /**
1185      * Fetches and executes the action identified by ``action_data``.
1186      *
1187      * @param {Object} action_data the action descriptor data
1188      * @param {String} action_data.name the action name, used to uniquely identify the action to find and execute it
1189      * @param {String} [action_data.special=null] special action handlers (currently: only ``'cancel'``)
1190      * @param {String} [action_data.type='workflow'] the action type, if present, one of ``'object'``, ``'action'`` or ``'workflow'``
1191      * @param {Object} [action_data.context=null] additional action context, to add to the current context
1192      * @param {instance.web.DataSet} dataset a dataset object used to communicate with the server
1193      * @param {Object} [record_id] the identifier of the object on which the action is to be applied
1194      * @param {Function} on_closed callback to execute when dialog is closed or when the action does not generate any result (no new action)
1195      */
1196     do_execute_action: function (action_data, dataset, record_id, on_closed) {
1197         var self = this;
1198         var result_handler = function () {
1199             if (on_closed) { on_closed.apply(null, arguments); }
1200             if (self.getParent() && self.getParent().on_action_executed) {
1201                 return self.getParent().on_action_executed.apply(null, arguments);
1202             }
1203         };
1204         var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {});
1205
1206         var handler = function (r) {
1207             var action = r.result;
1208             if (action && action.constructor == Object) {
1209                 var ncontext = new instance.web.CompoundContext(context);
1210                 if (record_id) {
1211                     ncontext.add({
1212                         active_id: record_id,
1213                         active_ids: [record_id],
1214                         active_model: dataset.model
1215                     });
1216                 }
1217                 ncontext.add(action.context || {});
1218                 return self.rpc('/web/session/eval_domain_and_context', {
1219                     contexts: [ncontext],
1220                     domains: []
1221                 }).pipe(function (results) {
1222                     action.context = results.context;
1223                     /* niv: previously we were overriding once more with action_data.context,
1224                      * I assumed this was not a correct behavior and removed it
1225                      */
1226                     return self.do_action(action, result_handler);
1227                 }, null);
1228             } else {
1229                 return result_handler();
1230             }
1231         };
1232
1233         if (action_data.special) {
1234             return handler({result: {"type":"ir.actions.act_window_close"}});
1235         } else if (action_data.type=="object") {
1236             var args = [[record_id]], additional_args = [];
1237             if (action_data.args) {
1238                 try {
1239                     // Warning: quotes and double quotes problem due to json and xml clash
1240                     // Maybe we should force escaping in xml or do a better parse of the args array
1241                     additional_args = JSON.parse(action_data.args.replace(/'/g, '"'));
1242                     args = args.concat(additional_args);
1243                 } catch(e) {
1244                     console.error("Could not JSON.parse arguments", action_data.args);
1245                 }
1246             }
1247             args.push(context);
1248             return dataset.call_button(action_data.name, args, handler);
1249         } else if (action_data.type=="action") {
1250             return this.rpc('/web/action/load', { action_id: parseInt(action_data.name, 10), context: context, do_not_eval: true}, handler);
1251         } else  {
1252             return dataset.exec_workflow(record_id, action_data.name, handler);
1253         }
1254     },
1255     /**
1256      * Directly set a view to use instead of calling fields_view_get. This method must
1257      * be called before start(). When an embedded view is set, underlying implementations
1258      * of instance.web.View must use the provided view instead of any other one.
1259      *
1260      * @param embedded_view A view.
1261      */
1262     set_embedded_view: function(embedded_view) {
1263         this.embedded_view = embedded_view;
1264     },
1265     do_show: function () {
1266         this.$element.show();
1267     },
1268     do_hide: function () {
1269         this.$element.hide();
1270     },
1271     do_push_state: function(state) {
1272         if (this.getParent() && this.getParent().do_push_state) {
1273             this.getParent().do_push_state(state);
1274         }
1275     },
1276     do_load_state: function(state, warm) {
1277     },
1278     /**
1279      * Switches to a specific view type
1280      *
1281      * @param {String} view view type to switch to
1282      */
1283     do_switch_view: function(view) { 
1284     },
1285     /**
1286      * Cancels the switch to the current view, switches to the previous one
1287      *
1288      * @param {Object} [options]
1289      * @param {Boolean} [options.created=false] resource was created
1290      * @param {String} [options.default=null] view to switch to if no previous view
1291      */
1292     do_prev_view: function (options) {
1293     },
1294     do_search: function(view) {
1295     },
1296     on_sidebar_import: function() {
1297         var import_view = new instance.web.DataImport(this, this.dataset);
1298         import_view.start();
1299     },
1300     on_sidebar_export: function() {
1301         var export_view = new instance.web.DataExport(this, this.dataset);
1302         export_view.start();
1303     },
1304     on_sidebar_translate: function() {
1305         return this.do_action({
1306             res_model : 'ir.translation',
1307             domain : [['type', '!=', 'object'], '|', ['name', '=', this.dataset.model], ['name', 'ilike', this.dataset.model + ',']],
1308             views: [[false, 'list'], [false, 'form']],
1309             type : 'ir.actions.act_window',
1310             view_type : "list",
1311             view_mode : "list"
1312         });
1313     },
1314     sidebar_context: function () {
1315         return $.when();
1316     },
1317     /**
1318      * Asks the view to reload itself, if the reloading is asynchronous should
1319      * return a {$.Deferred} indicating when the reloading is done.
1320      */
1321     reload: function () {
1322         return $.when();
1323     }
1324 });
1325
1326 instance.web.xml_to_json = function(node) {
1327     switch (node.nodeType) {
1328         case 3:
1329         case 4:
1330             return node.data;
1331         break;
1332         case 1:
1333             var attrs = $(node).getAttributes();
1334             _.each(['domain', 'filter_domain', 'context', 'default_get'], function(key) {
1335                 if (attrs[key]) {
1336                     try {
1337                         attrs[key] = JSON.parse(attrs[key]);
1338                     } catch(e) { }
1339                 }
1340             });
1341             return {
1342                 tag: node.tagName.toLowerCase(),
1343                 attrs: attrs,
1344                 children: _.map(node.childNodes, instance.web.xml_to_json)
1345             }
1346     }
1347 }
1348 instance.web.json_node_to_xml = function(node, human_readable, indent) {
1349     // For debugging purpose, this function will convert a json node back to xml
1350     // Maybe useful for xml view editor
1351     indent = indent || 0;
1352     var sindent = (human_readable ? (new Array(indent + 1).join('\t')) : ''),
1353         r = sindent + '<' + node.tag,
1354         cr = human_readable ? '\n' : '';
1355
1356     if (typeof(node) === 'string') {
1357         return sindent + node;
1358     } else if (typeof(node.tag) !== 'string' || !node.children instanceof Array || !node.attrs instanceof Object) {
1359         throw("Node a json node");
1360     }
1361     for (var attr in node.attrs) {
1362         var vattr = node.attrs[attr];
1363         if (typeof(vattr) !== 'string') {
1364             // domains, ...
1365             vattr = JSON.stringify(vattr);
1366         }
1367         vattr = vattr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1368         if (human_readable) {
1369             vattr = vattr.replace(/&quot;/g, "'");
1370         }
1371         r += ' ' + attr + '="' + vattr + '"';
1372     }
1373     if (node.children && node.children.length) {
1374         r += '>' + cr;
1375         var childs = [];
1376         for (var i = 0, ii = node.children.length; i < ii; i++) {
1377             childs.push(instance.web.json_node_to_xml(node.children[i], human_readable, indent + 1));
1378         }
1379         r += childs.join(cr);
1380         r += cr + sindent + '</' + node.tag + '>';
1381         return r;
1382     } else {
1383         return r + '/>';
1384     }
1385 }
1386 instance.web.xml_to_str = function(node) {
1387     if (window.ActiveXObject) {
1388         return node.xml;
1389     } else {
1390         return (new XMLSerializer()).serializeToString(node);
1391     }
1392 }
1393 instance.web.str_to_xml = function(s) {
1394     if (window.DOMParser) {
1395         var dp = new DOMParser();
1396         var r = dp.parseFromString(s, "text/xml");
1397         if (r.body && r.body.firstChild && r.body.firstChild.nodeName == 'parsererror') {
1398             throw new Error("Could not parse string to xml");
1399         }
1400         return r;
1401     }
1402     var xDoc;
1403     try {
1404         xDoc = new ActiveXObject("MSXML2.DOMDocument");
1405     } catch (e) {
1406         throw new Error("Could not find a DOM Parser: " + e.message);
1407     }
1408     xDoc.async = false;
1409     xDoc.preserveWhiteSpace = true;
1410     xDoc.loadXML(s);
1411     return xDoc;
1412 }
1413
1414 /**
1415  * Registry for all the main views
1416  */
1417 instance.web.views = new instance.web.Registry();
1418
1419 };
1420
1421 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: