[MERGE] forward port of branch 7.0 up to 2080ea0
[odoo/odoo.git] / addons / web / static / src / js / view_list.js
1 (function() {
2
3 var instance = openerp;
4 openerp.web.list = {};
5 var _t = instance.web._t,
6     _lt = instance.web._lt;
7 var QWeb = instance.web.qweb;
8 instance.web.views.add('list', 'instance.web.ListView');
9 instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
10     _template: 'ListView',
11     display_name: _lt('List'),
12     defaults: {
13         // records can be selected one by one
14         'selectable': true,
15         // list rows can be deleted
16         'deletable': false,
17         // whether the column headers should be displayed
18         'header': true,
19         // display addition button, with that label
20         'addable': _lt("Create"),
21         // whether the list view can be sorted, note that once a view has been
22         // sorted it can not be reordered anymore
23         'sortable': true,
24         // whether the view rows can be reordered (via vertical drag & drop)
25         'reorderable': true,
26         'action_buttons': true,
27         //whether the editable property of the view has to be disabled
28         'disable_editable_mode': false,
29     },
30     view_type: 'tree',
31     events: {
32         'click thead th.oe_sortable[data-id]': 'sort_by_column'
33     },
34     /**
35      * Core class for list-type displays.
36      *
37      * As a view, needs a number of view-related parameters to be correctly
38      * instantiated, provides options and overridable methods for behavioral
39      * customization.
40      *
41      * See constructor parameters and method documentations for information on
42      * the default behaviors and possible options for the list view.
43      *
44      * @constructs instance.web.ListView
45      * @extends instance.web.View
46      *
47      * @param parent parent object
48      * @param {instance.web.DataSet} dataset the dataset the view should work with
49      * @param {String} view_id the listview's identifier, if any
50      * @param {Object} options A set of options used to configure the view
51      * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
52      * @param {Boolean} [options.header=true] should the list's header be displayed
53      * @param {Boolean} [options.deletable=true] are the list rows deletable
54      * @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
55      * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
56      * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
57      */
58     init: function(parent, dataset, view_id, options) {
59         var self = this;
60         this._super(parent);
61         this.set_default_options(_.extend({}, this.defaults, options || {}));
62         this.dataset = dataset;
63         this.model = dataset.model;
64         this.view_id = view_id;
65         this.previous_colspan = null;
66         this.colors = null;
67         this.fonts = null;
68
69         this.columns = [];
70
71         this.records = new Collection();
72
73         this.set_groups(new (this.options.GroupsType)(this));
74
75         if (this.dataset instanceof instance.web.DataSetStatic) {
76             this.groups.datagroup = new StaticDataGroup(this.dataset);
77         } else {
78             this.groups.datagroup = new DataGroup(
79                 this, this.model,
80                 dataset.get_domain(),
81                 dataset.get_context());
82             this.groups.datagroup.sort = this.dataset._sort;
83         }
84
85         this.page = 0;
86         this.records.bind('change', function (event, record, key) {
87             if (!_(self.aggregate_columns).chain()
88                     .pluck('name').contains(key).value()) {
89                 return;
90             }
91             self.compute_aggregates();
92         });
93
94         this.no_leaf = false;
95         this.grouped = false;
96     },
97     view_loading: function(r) {
98         return this.load_list(r);
99     },
100     set_default_options: function (options) {
101         this._super(options);
102         _.defaults(this.options, {
103             GroupsType: instance.web.ListView.Groups,
104             ListType: instance.web.ListView.List
105         });
106     },
107
108     /**
109      * Retrieves the view's number of records per page (|| section)
110      *
111      * options > defaults > parent.action.limit > indefinite
112      *
113      * @returns {Number|null}
114      */
115     limit: function () {
116         if (this._limit === undefined) {
117             this._limit = (this.options.limit
118                         || this.defaults.limit
119                         || (this.getParent().action || {}).limit
120                         || 80);
121         }
122         return this._limit;
123     },
124     /**
125      * Set a custom Group construct as the root of the List View.
126      *
127      * @param {instance.web.ListView.Groups} groups
128      */
129     set_groups: function (groups) {
130         var self = this;
131         if (this.groups) {
132             $(this.groups).unbind("selected deleted action row_link");
133             delete this.groups;
134         }
135
136         this.groups = groups;
137         $(this.groups).bind({
138             'selected': function (e, ids, records, deselected) {
139                 self.do_select(ids, records, deselected);
140             },
141             'deleted': function (e, ids) {
142                 self.do_delete(ids);
143             },
144             'action': function (e, action_name, id, callback) {
145                 self.do_button_action(action_name, id, callback);
146             },
147             'row_link': function (e, id, dataset, view) {
148                 self.do_activate_record(dataset.index, id, dataset, view);
149             }
150         });
151     },
152     /**
153      * View startup method, the default behavior is to set the ``oe_list``
154      * class on its root element and to perform an RPC load call.
155      *
156      * @returns {$.Deferred} loading promise
157      */
158     start: function() {
159         this.$el.addClass('oe_list');
160         return this._super();
161     },
162     /**
163      * Returns the style for the provided record in the current view (from the
164      * ``@colors`` and ``@fonts`` attributes)
165      *
166      * @param {Record} record record for the current row
167      * @returns {String} CSS style declaration
168      */
169     style_for: function (record) {
170         var style= '';
171
172         var context = _.extend({}, record.attributes, {
173             uid: this.session.uid,
174             current_date: new Date().toString('yyyy-MM-dd')
175             // TODO: time, datetime, relativedelta
176         });
177         var i;
178         var pair;
179         var expression;
180         if (this.fonts) {
181             for(i=0, len=this.fonts.length; i<len; ++i) {
182                 pair = this.fonts[i];
183                 var font = pair[0];
184                 expression = pair[1];
185                 if (py.evaluate(expression, context).toJSON()) {
186                     switch(font) {
187                     case 'bold':
188                         style += 'font-weight: bold;';
189                         break;
190                     case 'italic':
191                         style += 'font-style: italic;';
192                         break;
193                     case 'underline':
194                         style += 'text-decoration: underline;';
195                         break;
196                     }
197                 }
198             }
199         }
200
201         if (!this.colors) { return style; }
202         for(i=0, len=this.colors.length; i<len; ++i) {
203             pair = this.colors[i];
204             var color = pair[0];
205             expression = pair[1];
206             if (py.evaluate(expression, context).toJSON()) {
207                 return style += 'color: ' + color + ';';
208             }
209             // TODO: handle evaluation errors
210         }
211         return style;
212     },
213     /**
214      * Called after loading the list view's description, sets up such things
215      * as the view table's columns, renders the table itself and hooks up the
216      * various table-level and row-level DOM events (action buttons, deletion
217      * buttons, selection of records, [New] button, selection of a given
218      * record, ...)
219      *
220      * Sets up the following:
221      *
222      * * Processes arch and fields to generate a complete field descriptor for each field
223      * * Create the table itself and allocate visible columns
224      * * Hook in the top-level (header) [New|Add] and [Delete] button
225      * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
226      * * Sets up event handlers for action buttons and per-row deletion button
227      * * Hooks global callback for clicking on a row
228      * * Sets up its sidebar, if any
229      *
230      * @param {Object} data wrapped fields_view_get result
231      * @param {Object} data.fields_view fields_view_get result (processed)
232      * @param {Object} data.fields_view.fields mapping of fields for the current model
233      * @param {Object} data.fields_view.arch current list view descriptor
234      * @param {Boolean} grouped Is the list view grouped
235      */
236     load_list: function(data) {
237         var self = this;
238         this.fields_view = data;
239         this.name = "" + this.fields_view.arch.attrs.string;
240
241         if (this.fields_view.arch.attrs.colors) {
242             this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
243                 .compact()
244                 .map(function(color_pair) {
245                     var pair = color_pair.split(':'),
246                         color = pair[0],
247                         expr = pair[1];
248                     return [color, py.parse(py.tokenize(expr)), expr];
249                 }).value();
250         }
251
252         if (this.fields_view.arch.attrs.fonts) {
253             this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
254                 .map(function(font_pair) {
255                     var pair = font_pair.split(':'),
256                         font = pair[0],
257                         expr = pair[1];
258                     return [font, py.parse(py.tokenize(expr)), expr];
259                 }).value();
260         }
261
262         this.setup_columns(this.fields_view.fields, this.grouped);
263
264         this.$el.html(QWeb.render(this._template, this));
265         this.$el.addClass(this.fields_view.arch.attrs['class']);
266
267         // Head hook
268         // Selecting records
269         this.$el.find('.oe_list_record_selector').click(function(){
270             self.$el.find('.oe_list_record_selector input').prop('checked',
271                 self.$el.find('.oe_list_record_selector').prop('checked')  || false);
272             var selection = self.groups.get_selection();
273             $(self.groups).trigger(
274                 'selected', [selection.ids, selection.records]);
275         });
276
277         // Add button
278         if (!this.$buttons) {
279             this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
280             if (this.options.$buttons) {
281                 this.$buttons.appendTo(this.options.$buttons);
282             } else {
283                 this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
284             }
285             this.$buttons.find('.oe_list_add')
286                     .click(this.proxy('do_add_record'))
287                     .prop('disabled', this.grouped);
288         }
289
290         // Pager
291         if (!this.$pager) {
292             this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
293             if (this.options.$buttons) {
294                 this.$pager.appendTo(this.options.$pager);
295             } else {
296                 this.$el.find('.oe_list_pager').replaceWith(this.$pager);
297             }
298
299             this.$pager
300                 .on('click', 'a[data-pager-action]', function () {
301                     var $this = $(this);
302                     var max_page = Math.floor(self.dataset.size() / self.limit());
303                     switch ($this.data('pager-action')) {
304                         case 'first':
305                             self.page = 0; break;
306                         case 'last':
307                             self.page = max_page - 1;
308                             break;
309                         case 'next':
310                             self.page += 1; break;
311                         case 'previous':
312                             self.page -= 1; break;
313                     }
314                     if (self.page < 0) {
315                         self.page = max_page;
316                     } else if (self.page > max_page) {
317                         self.page = 0;
318                     }
319                     self.reload_content();
320                 }).find('.oe_list_pager_state')
321                     .click(function (e) {
322                         e.stopPropagation();
323                         var $this = $(this);
324
325                         var $select = $('<select>')
326                             .appendTo($this.empty())
327                             .click(function (e) {e.stopPropagation();})
328                             .append('<option value="80">80</option>' +
329                                     '<option value="200">200</option>' +
330                                     '<option value="500">500</option>' +
331                                     '<option value="2000">2000</option>' +
332                                     '<option value="NaN">' + _t("Unlimited") + '</option>')
333                             .change(function () {
334                                 var val = parseInt($select.val(), 10);
335                                 self._limit = (isNaN(val) ? null : val);
336                                 self.page = 0;
337                                 self.reload_content();
338                             }).blur(function() {
339                                 $(this).trigger('change');
340                             })
341                             .val(self._limit || 'NaN');
342                     });
343         }
344
345         // Sidebar
346         if (!this.sidebar && this.options.$sidebar) {
347             this.sidebar = new instance.web.Sidebar(this);
348             this.sidebar.appendTo(this.options.$sidebar);
349             this.sidebar.add_items('other', _.compact([
350                 { label: _t("Export"), callback: this.on_sidebar_export },
351                 self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
352             ]));
353             this.sidebar.add_toolbar(this.fields_view.toolbar);
354             this.sidebar.$el.hide();
355         }
356         //Sort
357         if(this.dataset._sort.length){
358             if(this.dataset._sort[0].indexOf('-') == -1){
359                 this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
360             }else {
361                 this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
362             }
363         }
364         this.trigger('list_view_loaded', data, this.grouped);
365     },
366     sort_by_column: function (e) {
367         e.stopPropagation();
368         var $column = $(e.currentTarget);
369         var col_name = $column.data('id');
370         var field = this.fields_view.fields[col_name];
371         // test if the field is a function field with store=false, since it's impossible
372         // for the server to sort those fields we desactivate the feature
373         if (field && field.store === false) {
374             return false;
375         }
376         this.dataset.sort(col_name);
377         if($column.hasClass("sortdown") || $column.hasClass("sortup"))  {
378             $column.toggleClass("sortup sortdown");
379         } else {
380             $column.addClass("sortdown");
381         }
382         $column.siblings('.oe_sortable').removeClass("sortup sortdown");
383
384         this.reload_content();
385     },
386     /**
387      * Configures the ListView pager based on the provided dataset's information
388      *
389      * Horrifying side-effect: sets the dataset's data on this.dataset?
390      *
391      * @param {instance.web.DataSet} dataset
392      */
393     configure_pager: function (dataset) {
394         this.dataset.ids = dataset.ids;
395         // Not exactly clean
396         if (dataset._length) {
397             this.dataset._length = dataset._length;
398         }
399
400         var total = dataset.size();
401         var limit = this.limit() || total;
402         if (total === 0)
403             this.$pager.hide();
404         else
405             this.$pager.css("display", "");
406         this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
407         var spager = '-';
408         if (total) {
409             var range_start = this.page * limit + 1;
410             var range_stop = range_start - 1 + limit;
411             if (this.records.length) {
412                 range_stop = range_start - 1 + this.records.length;
413             }
414             if (range_stop > total) {
415                 range_stop = total;
416             }
417             spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
418         }
419
420         this.$pager.find('.oe_list_pager_state').text(spager);
421     },
422     /**
423      * Sets up the listview's columns: merges view and fields data, move
424      * grouped-by columns to the front of the columns list and make them all
425      * visible.
426      *
427      * @param {Object} fields fields_view_get's fields section
428      * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
429      */
430     setup_columns: function (fields, grouped) {
431         var registry = instance.web.list.columns;
432         this.columns.splice(0, this.columns.length);
433         this.columns.push.apply(this.columns,
434             _(this.fields_view.arch.children).map(function (field) {
435                 var id = field.attrs.name;
436                 return registry.for_(id, fields[id], field);
437         }));
438         if (grouped) {
439             this.columns.unshift(
440                 new instance.web.list.MetaColumn('_group', _t("Group")));
441         }
442
443         this.visible_columns = _.filter(this.columns, function (column) {
444             return column.invisible !== '1';
445         });
446
447         this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
448     },
449     /**
450      * Used to handle a click on a table row, if no other handler caught the
451      * event.
452      *
453      * The default implementation asks the list view's view manager to switch
454      * to a different view (by calling
455      * :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
456      * provided record index (within the current list view's dataset).
457      *
458      * If the index is null, ``switch_to_record`` asks for the creation of a
459      * new record.
460      *
461      * @param {Number|void} index the record index (in the current dataset) to switch to
462      * @param {String} [view="page"] the view type to switch to
463      */
464     select_record:function (index, view) {
465         view = view || index === null || index === undefined ? 'form' : 'form';
466         this.dataset.index = index;
467         _.delay(_.bind(function () {
468             this.do_switch_view(view);
469         }, this));
470     },
471     do_show: function () {
472         this._super();
473         if (this.$buttons) {
474             this.$buttons.show();
475         }
476         if (this.$pager) {
477             this.$pager.show();
478         }
479     },
480     do_hide: function () {
481         if (this.sidebar) {
482             this.sidebar.$el.hide();
483         }
484         if (this.$buttons) {
485             this.$buttons.hide();
486         }
487         if (this.$pager) {
488             this.$pager.hide();
489         }
490         this._super();
491     },
492     /**
493      * Reloads the list view based on the current settings (dataset & al)
494      *
495      * @deprecated
496      * @param {Boolean} [grouped] Should the list be displayed grouped
497      * @param {Object} [context] context to send the server while loading the view
498      */
499     reload_view: function (grouped, context, initial) {
500         return this.load_view(context);
501     },
502     /**
503      * re-renders the content of the list view
504      *
505      * @returns {$.Deferred} promise to content reloading
506      */
507     reload_content: synchronized(function () {
508         var self = this;
509         self.$el.find('.oe_list_record_selector').prop('checked', false);
510         this.records.reset();
511         var reloaded = $.Deferred();
512         this.$el.find('.oe_list_content').append(
513             this.groups.render(function () {
514                 if (self.dataset.index == null) {
515                     if (self.records.length) {
516                         self.dataset.index = 0;
517                     }
518                 } else if (self.dataset.index >= self.records.length) {
519                     self.dataset.index = self.records.length ? 0 : null;
520                 }
521
522                 self.compute_aggregates();
523                 reloaded.resolve();
524             }));
525         this.do_push_state({
526             page: this.page,
527             limit: this._limit
528         });
529         return reloaded.promise();
530     }),
531     reload: function () {
532         return this.reload_content();
533     },
534     reload_record: function (record) {
535         var self = this;
536         return this.dataset.read_ids(
537             [record.get('id')],
538             _.pluck(_(this.columns).filter(function (r) {
539                     return r.tag === 'field';
540                 }), 'name'),
541             {check_access_rule: true}
542         ).done(function (records) {
543             var values = records[0];
544             if (!values) {
545                 self.records.remove(record);
546                 return;
547             }
548             _.each(values, function (value, key) {
549                 record.set(key + '__display', false, {silent: true});
550                 record.set(key, value, {silent: true});            
551             });
552             record.trigger('change', record);
553         });
554     },
555
556     do_load_state: function(state, warm) {
557         var reload = false;
558         if (state.page && this.page !== state.page) {
559             this.page = state.page;
560             reload = true;
561         }
562         if (state.limit) {
563             if (_.isString(state.limit)) {
564                 state.limit = null;
565             }
566             if (state.limit !== this._limit) {
567                 this._limit = state.limit;
568                 reload = true;
569             }
570         }
571         if (reload) {
572             this.reload_content();
573         }
574     },
575     /**
576      * Handler for the result of eval_domain_and_context, actually perform the
577      * searching
578      *
579      * @param {Object} results results of evaluating domain and process for a search
580      */
581     do_search: function (domain, context, group_by) {
582         this.page = 0;
583         this.groups.datagroup = new DataGroup(
584             this, this.model, domain, context, group_by);
585         this.groups.datagroup.sort = this.dataset._sort;
586
587         if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
588             group_by = null;
589         }
590         this.no_leaf = !!context['group_by_no_leaf'];
591         this.grouped = !!group_by;
592
593         return this.alive(this.load_view(context)).then(
594             this.proxy('reload_content'));
595     },
596     /**
597      * Handles the signal to delete lines from the records list
598      *
599      * @param {Array} ids the ids of the records to delete
600      */
601     do_delete: function (ids) {
602         if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
603             return;
604         }
605         var self = this;
606         return $.when(this.dataset.unlink(ids)).done(function () {
607             _(ids).each(function (id) {
608                 self.records.remove(self.records.get(id));
609             });
610             if (self.records.length === 0 && self.dataset.size() > 0) {
611                 //Trigger previous manually to navigate to previous page, 
612                 //If all records are deleted on current page.
613                 self.$pager.find('ul li:first a').trigger('click');
614             } else if (self.dataset.size() == self.limit()) {
615                 //Reload listview to update current page with next page records 
616                 //because pager going to be hidden if dataset.size == limit
617                 self.reload();
618             } else {
619                 self.configure_pager(self.dataset);
620             }
621             self.compute_aggregates();
622         });
623     },
624     /**
625      * Handles the signal indicating that a new record has been selected
626      *
627      * @param {Array} ids selected record ids
628      * @param {Array} records selected record values
629      */
630     do_select: function (ids, records, deselected) {
631         // uncheck header hook if at least one row has been deselected
632         if (deselected) {
633             this.$('.oe_list_record_selector').prop('checked', false);
634         }
635
636         if (!ids.length) {
637             this.dataset.index = 0;
638             if (this.sidebar) {
639                 this.sidebar.$el.hide();
640             }
641             this.compute_aggregates();
642             return;
643         }
644
645         this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
646         if (this.sidebar) {
647             this.options.$sidebar.show();
648             this.sidebar.$el.show();
649         }
650
651         this.compute_aggregates(_(records).map(function (record) {
652             return {count: 1, values: record};
653         }));
654     },
655     /**
656      * Handles action button signals on a record
657      *
658      * @param {String} name action name
659      * @param {Object} id id of the record the action should be called on
660      * @param {Function} callback should be called after the action is executed, if non-null
661      */
662     do_button_action: function (name, id, callback) {
663         this.handle_button(name, id, callback);
664     },
665     /**
666      * Base handling of buttons, can be called when overriding do_button_action
667      * in order to bypass parent overrides.
668      *
669      * The callback will be provided with the ``id`` as its parameter, in case
670      * handle_button's caller had to alter the ``id`` (or even create one)
671      * while not being ``callback``'s creator.
672      *
673      * This method should not be overridden.
674      *
675      * @param {String} name action name
676      * @param {Object} id id of the record the action should be called on
677      * @param {Function} callback should be called after the action is executed, if non-null
678      */
679     handle_button: function (name, id, callback) {
680         var action = _.detect(this.columns, function (field) {
681             return field.name === name;
682         });
683         if (!action) { return; }
684         if ('confirm' in action && !window.confirm(action.confirm)) {
685             return;
686         }
687
688         var c = new instance.web.CompoundContext();
689         c.set_eval_context(_.extend({
690             active_id: id,
691             active_ids: [id],
692             active_model: this.dataset.model
693         }, this.records.get(id).toContext()));
694         if (action.context) {
695             c.add(action.context);
696         }
697         action.context = c;
698         this.do_execute_action(
699             action, this.dataset, id, _.bind(callback, null, id));
700     },
701     /**
702      * Handles the activation of a record (clicking on it)
703      *
704      * @param {Number} index index of the record in the dataset
705      * @param {Object} id identifier of the activated record
706      * @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
707      */
708     do_activate_record: function (index, id, dataset, view) {
709         this.dataset.ids = dataset.ids;
710         this.select_record(index, view);
711     },
712     /**
713      * Handles signal for the addition of a new record (can be a creation,
714      * can be the addition from a remote source, ...)
715      *
716      * The default implementation is to switch to a new record on the form view
717      */
718     do_add_record: function () {
719         this.select_record(null);
720     },
721     /**
722      * Handles deletion of all selected lines
723      */
724     do_delete_selected: function () {
725         var ids = this.groups.get_selection().ids;
726         if (ids.length) {
727             this.do_delete(this.groups.get_selection().ids);
728         } else {
729             this.do_warn(_t("Warning"), _t("You must select at least one record."));
730         }
731     },
732     /**
733      * Computes the aggregates for the current list view, either on the
734      * records provided or on the records of the internal
735      * :js:class:`~instance.web.ListView.Group`, by calling
736      * :js:func:`~instance.web.ListView.group.get_records`.
737      *
738      * Then displays the aggregates in the table through
739      * :js:method:`~instance.web.ListView.display_aggregates`.
740      *
741      * @param {Array} [records]
742      */
743     compute_aggregates: function (records) {
744         var columns = _(this.aggregate_columns).filter(function (column) {
745             return column['function']; });
746         if (_.isEmpty(columns)) { return; }
747
748         if (_.isEmpty(records)) {
749             records = this.groups.get_records();
750         }
751         records = _(records).compact();
752
753         var count = 0, sums = {};
754         _(columns).each(function (column) {
755             switch (column['function']) {
756                 case 'max':
757                     sums[column.id] = -Infinity;
758                     break;
759                 case 'min':
760                     sums[column.id] = Infinity;
761                     break;
762                 default:
763                     sums[column.id] = 0;
764             }
765         });
766         _(records).each(function (record) {
767             count += record.count || 1;
768             _(columns).each(function (column) {
769                 var field = column.id,
770                     value = record.values[field];
771                 switch (column['function']) {
772                     case 'sum':
773                         sums[field] += value;
774                         break;
775                     case 'avg':
776                         sums[field] += record.count * value;
777                         break;
778                     case 'min':
779                         if (sums[field] > value) {
780                             sums[field] = value;
781                         }
782                         break;
783                     case 'max':
784                         if (sums[field] < value) {
785                             sums[field] = value;
786                         }
787                         break;
788                 }
789             });
790         });
791
792         var aggregates = {};
793         _(columns).each(function (column) {
794             var field = column.id;
795             switch (column['function']) {
796                 case 'avg':
797                     aggregates[field] = {value: sums[field] / count};
798                     break;
799                 default:
800                     aggregates[field] = {value: sums[field]};
801             }
802         });
803
804         this.display_aggregates(aggregates);
805     },
806     display_aggregates: function (aggregation) {
807         var self = this;
808         var $footer_cells = this.$el.find('.oe_list_footer');
809         _(this.aggregate_columns).each(function (column) {
810             if (!column['function']) {
811                 return;
812             }
813
814             $footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
815                 .html(column.format(aggregation, { process_modifiers: false }));
816         });
817     },
818     get_selected_ids: function() {
819         var ids = this.groups.get_selection().ids;
820         return ids;
821     },
822     /**
823      * Calculate the active domain of the list view. This should be done only
824      * if the header checkbox has been checked. This is done by evaluating the
825      * search results, and then adding the dataset domain (i.e. action domain).
826      */
827     get_active_domain: function () {
828         var self = this;
829         if (this.$('.oe_list_record_selector').prop('checked')) {
830             var search_view = this.getParent().searchview;
831             var search_data = search_view.build_search_data();
832             return instance.web.pyeval.eval_domains_and_contexts({
833                 domains: search_data.domains,
834                 contexts: search_data.contexts,
835                 group_by_seq: search_data.groupbys || []
836             }).then(function (results) {
837                 var domain = self.dataset.domain.concat(results.domain || []);
838                 return domain
839             });
840         }
841         else {
842             return $.Deferred().resolve();
843         }
844     },
845     /**
846      * Adds padding columns at the start or end of all table rows (including
847      * field names row)
848      *
849      * @param {Number} count number of columns to add
850      * @param {Object} options
851      * @param {"before"|"after"} [options.position="after"] insertion position for the new columns
852      * @param {Object} [options.except] content row to not pad
853      */
854     pad_columns: function (count, options) {
855         options = options || {};
856         // padding for action/pager header
857         var $first_header = this.$el.find('thead tr:first th');
858         var colspan = $first_header.attr('colspan');
859         if (colspan) {
860             if (!this.previous_colspan) {
861                 this.previous_colspan = colspan;
862             }
863             $first_header.attr('colspan', parseInt(colspan, 10) + count);
864         }
865         // Padding for column titles, footer and data rows
866         var $rows = this.$el
867                 .find('.oe_list_header_columns, tr:not(thead tr)')
868                 .not(options['except']);
869         var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
870         if (options.position === 'before') {
871             $rows.prepend(newcols);
872         } else {
873             $rows.append(newcols);
874         }
875     },
876     /**
877      * Removes all padding columns of the table
878      */
879     unpad_columns: function () {
880         this.$el.find('.oe_list_padding').remove();
881         if (this.previous_colspan) {
882             this.$el
883                     .find('thead tr:first th')
884                     .attr('colspan', this.previous_colspan);
885             this.previous_colspan = null;
886         }
887     },
888     no_result: function () {
889         this.$el.find('.oe_view_nocontent').remove();
890         if (this.groups.group_by
891             || !this.options.action
892             || !this.options.action.help) {
893             return;
894         }
895         this.$el.find('table:first').hide();
896         this.$el.prepend(
897             $('<div class="oe_view_nocontent">').html(this.options.action.help)
898         );
899         var create_nocontent = this.$buttons;
900         this.$el.find('.oe_view_nocontent').click(function() {
901             create_nocontent.openerpBounce();
902         });
903     }
904 });
905 instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
906     /**
907      * List display for the ListView, handles basic DOM events and transforms
908      * them in the relevant higher-level events, to which the list view (or
909      * other consumers) can subscribe.
910      *
911      * Events on this object are registered via jQuery.
912      *
913      * Available events:
914      *
915      * `selected`
916      *   Triggered when a row is selected (using check boxes), provides an
917      *   array of ids of all the selected records.
918      * `deleted`
919      *   Triggered when deletion buttons are hit, provide an array of ids of
920      *   all the records being marked for suppression.
921      * `action`
922      *   Triggered when an action button is clicked, provides two parameters:
923      *
924      *   * The name of the action to execute (as a string)
925      *   * The id of the record to execute the action on
926      * `row_link`
927      *   Triggered when a row of the table is clicked, provides the index (in
928      *   the rows array) and id of the selected record to the handle function.
929      *
930      * @constructs instance.web.ListView.List
931      * @extends instance.web.Class
932      * 
933      * @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
934      */
935     init: function (group, opts) {
936         var self = this;
937         this.group = group;
938         this.view = group.view;
939         this.session = this.view.session;
940
941         this.options = opts.options;
942         this.columns = opts.columns;
943         this.dataset = opts.dataset;
944         this.records = opts.records;
945
946         this.record_callbacks = {
947             'remove': function (event, record) {
948                 var id = record.get('id');
949                 self.dataset.remove_ids([id]);
950                 var $row = self.$current.children('[data-id=' + id + ']');
951                 var index = $row.data('index');
952                 $row.remove();
953             },
954             'reset': function () { return self.on_records_reset(); },
955             'change': function (event, record, attribute, value, old_value) {
956                 var $row;
957                 if (attribute === 'id') {
958                     if (old_value) {
959                         throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
960                             JSON.stringify(record.attributes) ));
961                     }
962                     self.dataset.add_ids([value], self.records.indexOf(record));
963                     // Set id on new record
964                     $row = self.$current.children('[data-id=false]');
965                 } else {
966                     $row = self.$current.children(
967                         '[data-id=' + record.get('id') + ']');
968                 }
969                 $row.replaceWith(self.render_record(record));
970             },
971             'add': function (ev, records, record, index) {
972                 var $new_row = $(self.render_record(record));
973                 var id = record.get('id');
974                 if (id) { self.dataset.add_ids([id], index); }
975
976                 if (index === 0) {
977                     $new_row.prependTo(self.$current);
978                 } else {
979                     var previous_record = records.at(index-1),
980                         $previous_sibling = self.$current.children(
981                                 '[data-id=' + previous_record.get('id') + ']');
982                     $new_row.insertAfter($previous_sibling);
983                 }
984             }
985         };
986         _(this.record_callbacks).each(function (callback, event) {
987             this.records.bind(event, callback);
988         }, this);
989
990         this.$current = $('<tbody>')
991             .delegate('input[readonly=readonly]', 'click', function (e) {
992                 /*
993                     Against all logic and sense, as of right now @readonly
994                     apparently does nothing on checkbox and radio inputs, so
995                     the trick of using @readonly to have, well, readonly
996                     checkboxes (which still let clicks go through) does not
997                     work out of the box. We *still* need to preventDefault()
998                     on the event, otherwise the checkbox's state *will* toggle
999                     on click
1000                  */
1001                 e.preventDefault();
1002             })
1003             .delegate('th.oe_list_record_selector', 'click', function (e) {
1004                 e.stopPropagation();
1005                 var selection = self.get_selection();
1006                 var checked = $(e.currentTarget).find('input').prop('checked');
1007                 $(self).trigger(
1008                         'selected', [selection.ids, selection.records, ! checked]);
1009             })
1010             .delegate('td.oe_list_record_delete button', 'click', function (e) {
1011                 e.stopPropagation();
1012                 var $row = $(e.target).closest('tr');
1013                 $(self).trigger('deleted', [[self.row_id($row)]]);
1014             })
1015             .delegate('td.oe_list_field_cell button', 'click', function (e) {
1016                 e.stopPropagation();
1017                 var $target = $(e.currentTarget),
1018                       field = $target.closest('td').data('field'),
1019                        $row = $target.closest('tr'),
1020                   record_id = self.row_id($row);
1021                 
1022                 if ($target.attr('disabled')) {
1023                     return;
1024                 }
1025                 $target.attr('disabled', 'disabled');
1026
1027                 // note: $.data converts data to number if it's composed only
1028                 // of digits, nice when storing actual numbers, not nice when
1029                 // storing strings composed only of digits. Force the action
1030                 // name to be a string
1031                 $(self).trigger('action', [field.toString(), record_id, function (id) {
1032                     $target.removeAttr('disabled');
1033                     return self.reload_record(self.records.get(id));
1034                 }]);
1035             })
1036             .delegate('a', 'click', function (e) {
1037                 e.stopPropagation();
1038             })
1039             .delegate('tr', 'click', function (e) {
1040                 var row_id = self.row_id(e.currentTarget);
1041                 if (row_id) {
1042                     e.stopPropagation();
1043                     if (!self.dataset.select_id(row_id)) {
1044                         throw new Error(_t("Could not find id in dataset"));
1045                     }
1046                     self.row_clicked(e);
1047                 }
1048             });
1049     },
1050     row_clicked: function (e, view) {
1051         $(this).trigger(
1052             'row_link',
1053             [this.dataset.ids[this.dataset.index],
1054              this.dataset, view]);
1055     },
1056     render_cell: function (record, column) {
1057         var value;
1058         if(column.type === 'reference') {
1059             value = record.get(column.id);
1060             var ref_match;
1061             // Ensure that value is in a reference "shape", otherwise we're
1062             // going to loop on performing name_get after we've resolved (and
1063             // set) a human-readable version. m2o does not have this issue
1064             // because the non-human-readable is just a number, where the
1065             // human-readable version is a pair
1066             if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
1067                 // reference values are in the shape "$model,$id" (as a
1068                 // string), we need to split and name_get this pair in order
1069                 // to get a correctly displayable value in the field
1070                 var model = ref_match[1],
1071                     id = parseInt(ref_match[2], 10);
1072                 new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
1073                     if (!names.length) { return; }
1074                     record.set(column.id + '__display', names[0][1]);
1075                 });
1076             }
1077         } else if (column.type === 'many2one') {
1078             value = record.get(column.id);
1079             // m2o values are usually name_get formatted, [Number, String]
1080             // pairs, but in some cases only the id is provided. In these
1081             // cases, we need to perform a name_get call to fetch the actual
1082             // displayable value
1083             if (typeof value === 'number' || value instanceof Number) {
1084                 // fetch the name, set it on the record (in the right field)
1085                 // and let the various registered events handle refreshing the
1086                 // row
1087                 new instance.web.DataSet(this.view, column.relation)
1088                         .name_get([value]).done(function (names) {
1089                     if (!names.length) { return; }
1090                     record.set(column.id, names[0]);
1091                 });
1092             }
1093         } else if (column.type === 'many2many') {
1094             value = record.get(column.id);
1095             // non-resolved (string) m2m values are arrays
1096             if (value instanceof Array && !_.isEmpty(value)
1097                     && !record.get(column.id + '__display')) {
1098                 var ids;
1099                 // they come in two shapes:
1100                 if (value[0] instanceof Array) {
1101                     var command = value[0];
1102                     // 1. an array of m2m commands (usually (6, false, ids))
1103                     if (command[0] !== 6) {
1104                         throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
1105                     }
1106                     ids = command[2];
1107                 } else {
1108                     // 2. an array of ids
1109                     ids = value;
1110                 }
1111                 new instance.web.Model(column.relation)
1112                     .call('name_get', [ids, this.dataset.context]).done(function (names) {
1113                         // FIXME: nth horrible hack in this poor listview
1114                         record.set(column.id + '__display',
1115                                    _(names).pluck(1).join(', '));
1116                         record.set(column.id, ids);
1117                     });
1118                 // temp empty value
1119                 record.set(column.id, false);
1120             }
1121         }
1122         return column.format(record.toForm().data, {
1123             model: this.dataset.model,
1124             id: record.get('id')
1125         });
1126     },
1127     render: function () {
1128         this.$current.empty().append(
1129             QWeb.render('ListView.rows', _.extend({
1130                     render_cell: function () {
1131                         return self.render_cell.apply(self, arguments); }
1132                 }, this)));
1133         this.pad_table_to(4);
1134     },
1135     pad_table_to: function (count) {
1136         if (this.records.length >= count ||
1137                 _(this.columns).any(function(column) { return column.meta; })) {
1138             return;
1139         }
1140         var cells = [];
1141         if (this.options.selectable) {
1142             cells.push('<th class="oe_list_record_selector"></td>');
1143         }
1144         _(this.columns).each(function(column) {
1145             if (column.invisible === '1') {
1146                 return;
1147             }
1148             cells.push('<td title="' + column.string + '">&nbsp;</td>');
1149         });
1150         if (this.options.deletable) {
1151             cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
1152         }
1153         cells.unshift('<tr>');
1154         cells.push('</tr>');
1155
1156         var row = cells.join('');
1157         this.$current
1158             .children('tr:not([data-id])').remove().end()
1159             .append(new Array(count - this.records.length + 1).join(row));
1160     },
1161     /**
1162      * Gets the ids of all currently selected records, if any
1163      * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
1164      */
1165     get_selection: function () {
1166         var result = {ids: [], records: []};
1167         if (!this.options.selectable) {
1168             return result;
1169         }
1170         var records = this.records;
1171         this.$current.find('th.oe_list_record_selector input:checked')
1172                 .closest('tr').each(function () {
1173             var record = records.get($(this).data('id'));
1174             result.ids.push(record.get('id'));
1175             result.records.push(record.attributes);
1176         });
1177         return result;
1178     },
1179     /**
1180      * Returns the identifier of the object displayed in the provided table
1181      * row
1182      *
1183      * @param {Object} row the selected table row
1184      * @returns {Number|String} the identifier of the row's object
1185      */
1186     row_id: function (row) {
1187         return $(row).data('id');
1188     },
1189     /**
1190      * Death signal, cleans up list display
1191      */
1192     on_records_reset: function () {
1193         _(this.record_callbacks).each(function (callback, event) {
1194             this.records.unbind(event, callback);
1195         }, this);
1196         if (!this.$current) { return; }
1197         this.$current.remove();
1198     },
1199     get_records: function () {
1200         return this.records.map(function (record) {
1201             return {count: 1, values: record.attributes};
1202         });
1203     },
1204     /**
1205      * Reloads the provided record by re-reading its content from the server.
1206      *
1207      * @param {Record} record
1208      * @returns {$.Deferred} promise to the finalization of the reloading
1209      */
1210     reload_record: function (record) {
1211         return this.view.reload_record(record);
1212     },
1213     /**
1214      * Renders a list record to HTML
1215      *
1216      * @param {Record} record index of the record to render in ``this.rows``
1217      * @returns {String} QWeb rendering of the selected record
1218      */
1219     render_record: function (record) {
1220         var self = this;
1221         var index = this.records.indexOf(record);
1222         return QWeb.render('ListView.row', {
1223             columns: this.columns,
1224             options: this.options,
1225             record: record,
1226             row_parity: (index % 2 === 0) ? 'even' : 'odd',
1227             view: this.view,
1228             render_cell: function () {
1229                 return self.render_cell.apply(self, arguments); }
1230         });
1231     }
1232 });
1233 instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
1234     passthrough_events: 'action deleted row_link',
1235     /**
1236      * Grouped display for the ListView. Handles basic DOM events and interacts
1237      * with the :js:class:`~DataGroup` bound to it.
1238      *
1239      * Provides events similar to those of
1240      * :js:class:`~instance.web.ListView.List`
1241      *
1242      * @constructs instance.web.ListView.Groups
1243      * @extends instance.web.Class
1244      *
1245      * @param {instance.web.ListView} view
1246      * @param {Object} [options]
1247      * @param {Collection} [options.records]
1248      * @param {Object} [options.options]
1249      * @param {Array} [options.columns]
1250      */
1251     init: function (view, options) {
1252         options = options || {};
1253         this.view = view;
1254         this.records = options.records || view.records;
1255         this.options = options.options || view.options;
1256         this.columns = options.columns || view.columns;
1257         this.datagroup = null;
1258
1259         this.$row = null;
1260         this.children = {};
1261
1262         this.page = 0;
1263
1264         var self = this;
1265         this.records.bind('reset', function () {
1266             return self.on_records_reset(); });
1267     },
1268     make_fragment: function () {
1269         return document.createDocumentFragment();
1270     },
1271     /**
1272      * Returns a DOM node after which a new tbody can be inserted, so that it
1273      * follows the provided row.
1274      *
1275      * Necessary to insert the result of a new group or list view within an
1276      * existing groups render, without losing track of the groups's own
1277      * elements
1278      *
1279      * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1280      * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1281      */
1282     point_insertion: function (row) {
1283         var $row = $(row);
1284         var red_letter_tboday = $row.closest('tbody')[0];
1285
1286         var $next_siblings = $row.nextAll();
1287         if ($next_siblings.length) {
1288             var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1289
1290             $root_kanal.append($next_siblings);
1291             this.elements.splice(
1292                 _.indexOf(this.elements, red_letter_tboday),
1293                 0,
1294                 $root_kanal[0]);
1295         }
1296         return red_letter_tboday;
1297     },
1298     make_paginator: function () {
1299         var self = this;
1300         var $prev = $('<button type="button" data-pager-action="previous">&lt;</button>')
1301             .click(function (e) {
1302                 e.stopPropagation();
1303                 self.page -= 1;
1304
1305                 self.$row.closest('tbody').next()
1306                     .replaceWith(self.render());
1307             });
1308         var $next = $('<button type="button" data-pager-action="next">&gt;</button>')
1309             .click(function (e) {
1310                 e.stopPropagation();
1311                 self.page += 1;
1312
1313                 self.$row.closest('tbody').next()
1314                     .replaceWith(self.render());
1315             });
1316         this.$row.children().last()
1317             .addClass('oe_list_group_pagination')
1318             .append($prev)
1319             .append('<span class="oe_list_pager_state"></span>')
1320             .append($next);
1321     },
1322     open: function (point_insertion) {
1323         this.render().insertAfter(point_insertion);
1324
1325         var no_subgroups = _(this.datagroup.group_by).isEmpty(),
1326             records_terminated = !this.datagroup.context['group_by_no_leaf'];
1327         if (no_subgroups && records_terminated) {
1328             this.make_paginator();
1329         }
1330     },
1331     close: function () {
1332         this.$row.children().last().find('button').remove();
1333         this.$row.children().last().find('span').remove();
1334         this.records.reset();
1335     },
1336     /**
1337      * Prefixes ``$node`` with floated spaces in order to indent it relative
1338      * to its own left margin/baseline
1339      *
1340      * @param {jQuery} $node jQuery object to indent
1341      * @param {Number} level current nesting level, >= 1
1342      * @returns {jQuery} the indentation node created
1343      */
1344     indent: function ($node, level) {
1345         return $('<span>')
1346                 .css({'float': 'left', 'white-space': 'pre'})
1347                 .text(new Array(level).join('   '))
1348                 .prependTo($node);
1349     },
1350     render_groups: function (datagroups) {
1351         var self = this;
1352         var placeholder = this.make_fragment();
1353         _(datagroups).each(function (group) {
1354             if (self.children[group.value]) {
1355                 self.records.proxy(group.value).reset();
1356                 delete self.children[group.value];
1357             }
1358             var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
1359                 records: self.records.proxy(group.value),
1360                 options: self.options,
1361                 columns: self.columns
1362             });
1363             self.bind_child_events(child);
1364             child.datagroup = group;
1365
1366             var $row = child.$row = $('<tr class="oe_group_header">');
1367             if (group.openable && group.length) {
1368                 $row.click(function (e) {
1369                     if (!$row.data('open')) {
1370                         $row.data('open', true)
1371                             .find('span.ui-icon')
1372                                 .removeClass('ui-icon-triangle-1-e')
1373                                 .addClass('ui-icon-triangle-1-s');
1374                         child.open(self.point_insertion(e.currentTarget));
1375                     } else {
1376                         $row.removeData('open')
1377                             .find('span.ui-icon')
1378                                 .removeClass('ui-icon-triangle-1-s')
1379                                 .addClass('ui-icon-triangle-1-e');
1380                         child.close();
1381                         // force recompute the selection as closing group reset properties
1382                         var selection = self.get_selection();
1383                         $(self).trigger('selected', [selection.ids, this.records]);
1384                     }
1385                 });
1386             }
1387             placeholder.appendChild($row[0]);
1388
1389             var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
1390             // Don't fill this if group_by_no_leaf but no group_by
1391             if (group.grouped_on) {
1392                 var row_data = {};
1393                 row_data[group.grouped_on] = group;
1394                 var group_label = _t("Undefined");
1395                 var group_column = _(self.columns).detect(function (column) {
1396                     return column.id === group.grouped_on; });
1397                 if (group_column) {
1398                     try {
1399                         group_label = group_column.format(row_data, {
1400                             value_if_empty: _t("Undefined"),
1401                             process_modifiers: false
1402                         });
1403                     } catch (e) {
1404                         group_label = _.str.escapeHTML(row_data[group_column.id].value);
1405                     }
1406                 } else {
1407                     group_label = group.value;
1408                     if (group_label instanceof Array) {
1409                         group_label = group_label[1];
1410                     }
1411                     if (group_label === false) {
1412                         group_label = _t('Undefined');
1413                     }
1414                     group_label = _.str.escapeHTML(group_label);
1415                 }
1416                     
1417                 // group_label is html-clean (through format or explicit
1418                 // escaping if format failed), can inject straight into HTML
1419                 $group_column.html(_.str.sprintf(_t("%s (%d)"),
1420                     group_label, group.length));
1421
1422                 if (group.length && group.openable) {
1423                     // Make openable if not terminal group & group_by_no_leaf
1424                     $group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1425                 } else {
1426                     // Kinda-ugly hack: jquery-ui has no "empty" icon, so set
1427                     // wonky background position to ensure nothing is displayed
1428                     // there but the rest of the behavior is ui-icon's
1429                     $group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
1430                 }
1431             }
1432             self.indent($group_column, group.level);
1433
1434             if (self.options.selectable) {
1435                 $row.append('<td>');
1436             }
1437             _(self.columns).chain()
1438                 .filter(function (column) { return column.invisible !== '1'; })
1439                 .each(function (column) {
1440                     if (column.meta) {
1441                         // do not do anything
1442                     } else if (column.id in group.aggregates) {
1443                         var r = {};
1444                         r[column.id] = {value: group.aggregates[column.id]};
1445                         $('<td class="oe_number">')
1446                             .html(column.format(r, {process_modifiers: false}))
1447                             .appendTo($row);
1448                     } else {
1449                         $row.append('<td>');
1450                     }
1451                 });
1452             if (self.options.deletable) {
1453                 $row.append('<td class="oe_list_group_pagination">');
1454             }
1455         });
1456         return placeholder;
1457     },
1458     bind_child_events: function (child) {
1459         var $this = $(this),
1460              self = this;
1461         $(child).bind('selected', function (e, _0, _1, deselected) {
1462             // can have selections spanning multiple links
1463             var selection = self.get_selection();
1464             $this.trigger(e, [selection.ids, selection.records, deselected]);
1465         }).bind(this.passthrough_events, function (e) {
1466             // additional positional parameters are provided to trigger as an
1467             // Array, following the event type or event object, but are
1468             // provided to the .bind event handler as *args.
1469             // Convert our *args back into an Array in order to trigger them
1470             // on the group itself, so it can ultimately be forwarded wherever
1471             // it's supposed to go.
1472             var args = Array.prototype.slice.call(arguments, 1);
1473             $this.trigger.call($this, e, args);
1474         });
1475     },
1476     render_dataset: function (dataset) {
1477         var self = this,
1478             list = new (this.view.options.ListType)(this, {
1479                 options: this.options,
1480                 columns: this.columns,
1481                 dataset: dataset,
1482                 records: this.records
1483             });
1484         this.bind_child_events(list);
1485
1486         var view = this.view,
1487            limit = view.limit(),
1488             page = this.datagroup.openable ? this.page : view.page;
1489
1490         var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field";}), 'name');
1491         var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
1492         //TODO xmo: investigate why we need to put the setTimeout
1493         return $.async_when().then(function() {
1494             return dataset.read_slice(fields, options).then(function (records) {
1495                 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1496                 if (self.records.length) {
1497                     self.records.reset(null, {silent: true});
1498                 }
1499                 if (!self.datagroup.openable) {
1500                     view.configure_pager(dataset);
1501                 } else {
1502                     if (dataset.size() == records.length) {
1503                         // only one page
1504                         self.$row.find('td.oe_list_group_pagination').find('button').remove();
1505                         self.$row.find('td.oe_list_group_pagination').find('span').remove();
1506                     } else {
1507                         var pages = Math.ceil(dataset.size() / limit);
1508                         self.$row
1509                             .find('.oe_list_pager_state')
1510                                 .text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
1511                                     page: page + 1,
1512                                     page_count: pages
1513                                 }))
1514                             .end()
1515                             .find('button[data-pager-action=previous]')
1516                                 .css('visibility',
1517                                      page === 0 ? 'hidden' : '')
1518                             .end()
1519                             .find('button[data-pager-action=next]')
1520                                 .css('visibility',
1521                                      page === pages - 1 ? 'hidden' : '');
1522                     }
1523                 }
1524
1525                 self.records.add(records, {silent: true});
1526                 list.render();
1527                 if (_.isEmpty(records)) {
1528                     view.no_result();
1529                 }
1530                 return list;
1531             });
1532         });
1533     },
1534     setup_resequence_rows: function (list, dataset) {
1535         // drag and drop enabled if list is not sorted and there is a
1536         // visible column with @widget=handle or "sequence" column in the view.
1537         if ((dataset.sort && dataset.sort())
1538             || !_(this.columns).any(function (column) {
1539                     return column.widget === 'handle'
1540                         || column.name === 'sequence'; })) {
1541             return;
1542         }
1543         var sequence_field = _(this.columns).find(function (c) {
1544             return c.widget === 'handle';
1545         });
1546         var seqname = sequence_field ? sequence_field.name : 'sequence';
1547
1548         // ondrop, move relevant record & fix sequences
1549         list.$current.sortable({
1550             axis: 'y',
1551             items: '> tr[data-id]',
1552             helper: 'clone'
1553         });
1554         if (sequence_field) {
1555             list.$current.sortable('option', 'handle', '.oe_list_field_handle');
1556         }
1557         list.$current.sortable('option', {
1558             start: function (e, ui) {
1559                 ui.placeholder.height(ui.item.height());
1560             },
1561             stop: function (event, ui) {
1562                 var to_move = list.records.get(ui.item.data('id')),
1563                     target_id = ui.item.prev().data('id'),
1564                     from_index = list.records.indexOf(to_move),
1565                     target = list.records.get(target_id);
1566                 if (list.records.at(from_index - 1) == target) {
1567                     return;
1568                 }
1569
1570                 list.records.remove(to_move);
1571                 var to = target_id ? list.records.indexOf(target) + 1 : 0;
1572                 list.records.add(to_move, { at: to });
1573
1574                 // resequencing time!
1575                 var record, index = to,
1576                     // if drag to 1st row (to = 0), start sequencing from 0
1577                     // (exclusive lower bound)
1578                     seq = to ? list.records.at(to - 1).get(seqname) : 0;
1579                 var fct = function (dataset, id, seq) {
1580                     $.async_when().done(function () {
1581                         var attrs = {};
1582                         attrs[seqname] = seq;
1583                         dataset.write(id, attrs);
1584                     });
1585                 };
1586                 while (++seq, (record = list.records.at(index++))) {
1587                     // write are independent from one another, so we can just
1588                     // launch them all at the same time and we don't really
1589                     // give a fig about when they're done
1590                     // FIXME: breaks on o2ms (e.g. Accounting > Financial
1591                     //        Accounting > Taxes > Taxes, child tax accounts)
1592                     //        when synchronous (without setTimeout)
1593                     fct(dataset, record.get('id'), seq);
1594                     record.set(seqname, seq);
1595                 }
1596             }
1597         });
1598     },
1599     render: function (post_render) {
1600         var self = this;
1601         var $el = $('<tbody>');
1602         this.elements = [$el[0]];
1603
1604         this.datagroup.list(
1605             _(this.view.visible_columns).chain()
1606                 .filter(function (column) { return column.tag === 'field';})
1607                 .pluck('name').value(),
1608             function (groups) {
1609                 self.view.$pager.hide();
1610                 $el[0].appendChild(
1611                     self.render_groups(groups));
1612                 if (post_render) { post_render(); }
1613             }, function (dataset) {
1614                 self.render_dataset(dataset).then(function (list) {
1615                     self.children[null] = list;
1616                     self.elements =
1617                         [list.$current.replaceAll($el)[0]];
1618                     self.setup_resequence_rows(list, dataset);
1619                 }).always(function() {
1620                     if (post_render) { post_render(); }
1621                 });
1622             });
1623         return $el;
1624     },
1625     /**
1626      * Returns the ids of all selected records for this group, and the records
1627      * themselves
1628      */
1629     get_selection: function () {
1630         var ids = [], records = [];
1631
1632         _(this.children)
1633             .each(function (child) {
1634                 var selection = child.get_selection();
1635                 ids.push.apply(ids, selection.ids);
1636                 records.push.apply(records, selection.records);
1637             });
1638
1639         return {ids: ids, records: records};
1640     },
1641     on_records_reset: function () {
1642         this.children = {};
1643         $(this.elements).remove();
1644     },
1645     get_records: function () {
1646         if (_(this.children).isEmpty()) {
1647             if (!this.datagroup.length) {
1648                 return;
1649             }
1650             return {
1651                 count: this.datagroup.length,
1652                 values: this.datagroup.aggregates
1653             };
1654         }
1655         return _(this.children).chain()
1656             .map(function (child) {
1657                 return child.get_records();
1658             }).flatten().value();
1659     }
1660 });
1661
1662 /**
1663  * Serializes concurrent calls to this asynchronous method. The method must
1664  * return a deferred or promise.
1665  *
1666  * Current-implementation is class-serialized (the mutex is common to all
1667  * instances of the list view). Can be switched to instance-serialized if
1668  * having concurrent list views becomes possible and common.
1669  */
1670 function synchronized(fn) {
1671     var fn_mutex = new $.Mutex();
1672     return function () {
1673         var obj = this;
1674         var args = _.toArray(arguments);
1675         return fn_mutex.exec(function () {
1676             if (obj.isDestroyed()) { return $.when(); }
1677             return fn.apply(obj, args)
1678         });
1679     };
1680 }
1681 var DataGroup =  instance.web.Class.extend({
1682    init: function(parent, model, domain, context, group_by, level) {
1683        this.model = new instance.web.Model(model, context, domain);
1684        this.group_by = group_by;
1685        this.context = context;
1686        this.domain = domain;
1687
1688        this.level = level || 0;
1689    },
1690    list: function (fields, ifGroups, ifRecords) {
1691        var self = this;
1692        if (!_.isEmpty(this.group_by)) {
1693            // ensure group_by fields are read.
1694            fields = _.unique((fields || []).concat(this.group_by));
1695        }
1696        var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
1697        $.when(query).done(function (querygroups) {
1698            // leaf node
1699            if (!querygroups) {
1700                var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
1701                ds._sort = self.sort;
1702                ifRecords(ds);
1703                return;
1704            }
1705            // internal node
1706            var child_datagroups = _(querygroups).map(function (group) {
1707                var child_context = _.extend(
1708                    {}, self.model.context(), group.model.context());
1709                var child_dg = new DataGroup(
1710                    self, self.model.name, group.model.domain(),
1711                    child_context, group.model._context.group_by,
1712                    self.level + 1);
1713                child_dg.sort = self.sort;
1714                // copy querygroup properties
1715                child_dg.__context = child_context;
1716                child_dg.__domain = group.model.domain();
1717                child_dg.folded = group.get('folded');
1718                child_dg.grouped_on = group.get('grouped_on');
1719                child_dg.length = group.get('length');
1720                child_dg.value = group.get('value');
1721                child_dg.openable = group.get('has_children');
1722                child_dg.aggregates = group.get('aggregates');
1723                return child_dg;
1724            });
1725            ifGroups(child_datagroups);
1726        });
1727    }
1728 });
1729 var StaticDataGroup = DataGroup.extend({
1730    init: function (dataset) {
1731        this.dataset = dataset;
1732    },
1733    list: function (fields, ifGroups, ifRecords) {
1734        ifRecords(this.dataset);
1735    }
1736 });
1737
1738 /**
1739  * @mixin Events
1740  */
1741 var Events = /** @lends Events# */{
1742     /**
1743      * @param {String} event event to listen to on the current object, null for all events
1744      * @param {Function} handler event handler to bind to the relevant event
1745      * @returns this
1746      */
1747     bind: function (event, handler) {
1748         var calls = this['_callbacks'] || (this._callbacks = {});
1749
1750         if (event in calls) {
1751             calls[event].push(handler);
1752         } else {
1753             calls[event] = [handler];
1754         }
1755         return this;
1756     },
1757     /**
1758      * @param {String} event event to unbind on the current object
1759      * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1760      * @returns this
1761      */
1762     unbind: function (event, handler) {
1763         var calls = this._callbacks || {};
1764         if (!(event in calls)) { return this; }
1765         if (!handler) {
1766             delete calls[event];
1767         } else {
1768             var handlers = calls[event];
1769             handlers.splice(
1770                 _(handlers).indexOf(handler),
1771                 1);
1772         }
1773         return this;
1774     },
1775     /**
1776      * @param {String} event
1777      * @returns this
1778      */
1779     trigger: function (event) {
1780         var calls;
1781         if (!(calls = this._callbacks)) { return this; }
1782         var callbacks = (calls[event] || []).concat(calls[null] || []);
1783         for(var i=0, length=callbacks.length; i<length; ++i) {
1784             callbacks[i].apply(this, arguments);
1785         }
1786         return this;
1787     }
1788 };
1789 var Record = instance.web.Class.extend(/** @lends Record# */{
1790     /**
1791      * @constructs Record
1792      * @extends instance.web.Class
1793      * 
1794      * @mixes Events
1795      * @param {Object} [data]
1796      */
1797     init: function (data) {
1798         this.attributes = data || {};
1799     },
1800     /**
1801      * @param {String} key
1802      * @returns {Object}
1803      */
1804     get: function (key) {
1805         return this.attributes[key];
1806     },
1807     /**
1808      * @param key
1809      * @param value
1810      * @param {Object} [options]
1811      * @param {Boolean} [options.silent=false]
1812      * @returns {Record}
1813      */
1814     set: function (key, value, options) {
1815         options = options || {};
1816         var old_value = this.attributes[key];
1817         if (old_value === value) {
1818             return this;
1819         }
1820         this.attributes[key] = value;
1821         if (!options.silent) {
1822             this.trigger('change:' + key, this, value, old_value);
1823             this.trigger('change', this, key, value, old_value);
1824         }
1825         return this;
1826     },
1827     /**
1828      * Converts the current record to the format expected by form views:
1829      *
1830      * .. code-block:: javascript
1831      *
1832      *    data: {
1833      *         $fieldname: {
1834      *             value: $value
1835      *         }
1836      *     }
1837      *
1838      *
1839      * @returns {Object} record displayable in a form view
1840      */
1841     toForm: function () {
1842         var form_data = {}, attrs = this.attributes;
1843         for(var k in attrs) {
1844             form_data[k] = {value: attrs[k]};
1845         }
1846
1847         return {data: form_data};
1848     },
1849     /**
1850      * Converts the current record to a format expected by context evaluations
1851      * (identical to record.attributes, except m2o fields are their integer
1852      * value rather than a pair)
1853      */
1854     toContext: function () {
1855         var output = {}, attrs = this.attributes;
1856         for(var k in attrs) {
1857             var val = attrs[k];
1858             if (typeof val !== 'object') {
1859                 output[k] = val;
1860             } else if (val instanceof Array) {
1861                 output[k] = val[0];
1862             } else {
1863                 throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
1864             }
1865         }
1866         return output;
1867     }
1868 });
1869 Record.include(Events);
1870 var Collection = instance.web.Class.extend(/** @lends Collection# */{
1871     /**
1872      * Smarter collections, with events, very strongly inspired by Backbone's.
1873      *
1874      * Using a "dumb" array of records makes synchronization between the
1875      * various serious 
1876      *
1877      * @constructs Collection
1878      * @extends instance.web.Class
1879      * 
1880      * @mixes Events
1881      * @param {Array} [records] records to initialize the collection with
1882      * @param {Object} [options]
1883      */
1884     init: function (records, options) {
1885         options = options || {};
1886         _.bindAll(this, '_onRecordEvent');
1887         this.length = 0;
1888         this.records = [];
1889         this._byId = {};
1890         this._proxies = {};
1891         this._key = options.key;
1892         this._parent = options.parent;
1893
1894         if (records) {
1895             this.add(records);
1896         }
1897     },
1898     /**
1899      * @param {Object|Array} record
1900      * @param {Object} [options]
1901      * @param {Number} [options.at]
1902      * @param {Boolean} [options.silent=false]
1903      * @returns this
1904      */
1905     add: function (record, options) {
1906         options = options || {};
1907         var records = record instanceof Array ? record : [record];
1908
1909         for(var i=0, length=records.length; i<length; ++i) {
1910             var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1911             instance_.bind(null, this._onRecordEvent);
1912             this._byId[instance_.get('id')] = instance_;
1913             if (options.at === undefined || options.at === null) {
1914                 this.records.push(instance_);
1915                 if (!options.silent) {
1916                     this.trigger('add', this, instance_, this.records.length-1);
1917                 }
1918             } else {
1919                 var insertion_index = options.at + i;
1920                 this.records.splice(insertion_index, 0, instance_);
1921                 if (!options.silent) {
1922                     this.trigger('add', this, instance_, insertion_index);
1923                 }
1924             }
1925             this.length++;
1926         }
1927         return this;
1928     },
1929
1930     /**
1931      * Get a record by its index in the collection, can also take a group if
1932      * the collection is not degenerate
1933      *
1934      * @param {Number} index
1935      * @param {String} [group]
1936      * @returns {Record|undefined}
1937      */
1938     at: function (index, group) {
1939         if (group) {
1940             var groups = group.split('.');
1941             return this._proxies[groups[0]].at(index, groups.join('.'));
1942         }
1943         return this.records[index];
1944     },
1945     /**
1946      * Get a record by its database id
1947      *
1948      * @param {Number} id
1949      * @returns {Record|undefined}
1950      */
1951     get: function (id) {
1952         if (!_(this._proxies).isEmpty()) {
1953             var record = null;
1954             _(this._proxies).detect(function (proxy) {
1955                 record = proxy.get(id);
1956                 return record;
1957             });
1958             return record;
1959         }
1960         return this._byId[id];
1961     },
1962     /**
1963      * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1964      * the subtree's group
1965      *
1966      * @param {String} section group path section
1967      * @returns {Collection}
1968      */
1969     proxy: function (section) {
1970         this._proxies[section] = new Collection(null, {
1971             parent: this,
1972             key: section
1973         }).bind(null, this._onRecordEvent);
1974         return this._proxies[section];
1975     },
1976     /**
1977      * @param {Array} [records]
1978      * @returns this
1979      */
1980     reset: function (records, options) {
1981         options = options || {};
1982         _(this._proxies).each(function (proxy) {
1983             proxy.reset();
1984         });
1985         this._proxies = {};
1986         _(this.records).invoke('unbind', null, this._onRecordEvent);
1987         this.length = 0;
1988         this.records = [];
1989         this._byId = {};
1990         if (records) {
1991             this.add(records);
1992         }
1993         if (!options.silent) {
1994             this.trigger('reset', this);
1995         }
1996         return this;
1997     },
1998     /**
1999      * Removes the provided record from the collection
2000      *
2001      * @param {Record} record
2002      * @returns this
2003      */
2004     remove: function (record) {
2005         var index = this.indexOf(record);
2006         if (index === -1) {
2007             _(this._proxies).each(function (proxy) {
2008                 proxy.remove(record);
2009             });
2010             return this;
2011         }
2012
2013         record.unbind(null, this._onRecordEvent);
2014         this.records.splice(index, 1);
2015         delete this._byId[record.get('id')];
2016         this.length--;
2017         this.trigger('remove', record, this);
2018         return this;
2019     },
2020
2021     _onRecordEvent: function (event) {
2022         switch(event) {
2023         // don't propagate reset events
2024         case 'reset': return;
2025         case 'change:id':
2026             var record = arguments[1];
2027             var new_value = arguments[2];
2028             var old_value = arguments[3];
2029             // [change:id, record, new_value, old_value]
2030             if (this._byId[old_value] === record) {
2031                 delete this._byId[old_value];
2032                 this._byId[new_value] = record;
2033             }
2034             break;
2035         }
2036         this.trigger.apply(this, arguments);
2037     },
2038
2039     // underscore-type methods
2040     find: function (callback) {
2041         var record;
2042         for(var section in this._proxies) {
2043             if (!this._proxies.hasOwnProperty(section)) {
2044                 continue;
2045             }
2046             if ((record = this._proxies[section].find(callback))) {
2047                 return record;
2048             }
2049         }
2050         for(var i=0; i<this.length; ++i) {
2051             record = this.records[i];
2052             if (callback(record)) {
2053                 return record;
2054             }
2055         }
2056     },
2057     each: function (callback) {
2058         for(var section in this._proxies) {
2059             if (this._proxies.hasOwnProperty(section)) {
2060                 this._proxies[section].each(callback);
2061             }
2062         }
2063         for(var i=0; i<this.length; ++i) {
2064             callback(this.records[i]);
2065         }
2066     },
2067     map: function (callback) {
2068         var results = [];
2069         this.each(function (record) {
2070             results.push(callback(record));
2071         });
2072         return results;
2073     },
2074     pluck: function (fieldname) {
2075         return this.map(function (record) {
2076             return record.get(fieldname);
2077         });
2078     },
2079     indexOf: function (record) {
2080         return _(this.records).indexOf(record);
2081     },
2082     succ: function (record, options) {
2083         options = options || {wraparound: false};
2084         var result;
2085         for(var section in this._proxies) {
2086             if (!this._proxies.hasOwnProperty(section)) {
2087                 continue;
2088             }
2089             if ((result = this._proxies[section].succ(record, options))) {
2090                 return result;
2091             }
2092         }
2093         var index = this.indexOf(record);
2094         if (index === -1) { return null; }
2095         var next_index = index + 1;
2096         if (options.wraparound && (next_index === this.length)) {
2097             return this.at(0);
2098         }
2099         return this.at(next_index);
2100     },
2101     pred: function (record, options) {
2102         options = options || {wraparound: false};
2103
2104         var result;
2105         for (var section in this._proxies) {
2106             if (!this._proxies.hasOwnProperty(section)) {
2107                 continue;
2108             }
2109             if ((result = this._proxies[section].pred(record, options))) {
2110                 return result;
2111             }
2112         }
2113
2114         var index = this.indexOf(record);
2115         if (index === -1) { return null; }
2116         var next_index = index - 1;
2117         if (options.wraparound && (next_index === -1)) {
2118             return this.at(this.length - 1);
2119         }
2120         return this.at(next_index);
2121     }
2122 });
2123 Collection.include(Events);
2124 instance.web.list = {
2125     Events: Events,
2126     Record: Record,
2127     Collection: Collection
2128 };
2129 /**
2130  * Registry for column objects used to format table cells (and some other tasks
2131  * e.g. aggregation computations).
2132  *
2133  * Maps a field or button to a Column type via its ``$tag.$widget``,
2134  * ``$tag.$type`` or its ``$tag`` (alone).
2135  *
2136  * This specific registry has a dedicated utility method ``for_`` taking a
2137  * field (from fields_get/fields_view_get.field) and a node (from a view) and
2138  * returning the right object *already instantiated from the data provided*.
2139  *
2140  * @type {instance.web.Registry}
2141  */
2142 instance.web.list.columns = new instance.web.Registry({
2143     'field': 'instance.web.list.Column',
2144     'field.boolean': 'instance.web.list.Boolean',
2145     'field.binary': 'instance.web.list.Binary',
2146     'field.char': 'instance.web.list.Char',
2147     'field.progressbar': 'instance.web.list.ProgressBar',
2148     'field.handle': 'instance.web.list.Handle',
2149     'button': 'instance.web.list.Button',
2150     'field.many2onebutton': 'instance.web.list.Many2OneButton',
2151     'field.reference': 'instance.web.list.Reference',
2152     'field.many2many': 'instance.web.list.Many2Many'
2153 });
2154 instance.web.list.columns.for_ = function (id, field, node) {
2155     var description = _.extend({tag: node.tag}, field, node.attrs);
2156     var tag = description.tag;
2157     var Type = this.get_any([
2158         tag + '.' + description.widget,
2159         tag + '.'+ description.type,
2160         tag
2161     ]);
2162     return new Type(id, node.tag, description);
2163 };
2164
2165 instance.web.list.Column = instance.web.Class.extend({
2166     init: function (id, tag, attrs) {
2167         _.extend(attrs, {
2168             id: id,
2169             tag: tag
2170         });
2171
2172         this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
2173         delete attrs.modifiers;
2174         _.extend(this, attrs);
2175
2176         if (this.modifiers['tree_invisible']) {
2177             this.invisible = '1';
2178         } else { delete this.invisible; }
2179     },
2180     modifiers_for: function (fields) {
2181         var out = {};
2182         var domain_computer = instance.web.form.compute_domain;
2183
2184         for (var attr in this.modifiers) {
2185             if (!this.modifiers.hasOwnProperty(attr)) { continue; }
2186             var modifier = this.modifiers[attr];
2187             out[attr] = _.isBoolean(modifier)
2188                 ? modifier
2189                 : domain_computer(modifier, fields);
2190         }
2191
2192         return out;
2193     },
2194     to_aggregate: function () {
2195         if (this.type !== 'integer' && this.type !== 'float') {
2196             return {};
2197         }
2198         var aggregation_func = this['group_operator'] || 'sum';
2199         if (!(aggregation_func in this)) {
2200             return {};
2201         }
2202         var C = function (fn, label) {
2203             this['function'] = fn;
2204             this.label = label;
2205         };
2206         C.prototype = this;
2207         return new C(aggregation_func, this[aggregation_func]);
2208     },
2209     /**
2210      *
2211      * @param row_data record whose values should be displayed in the cell
2212      * @param {Object} [options]
2213      * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
2214      * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
2215      * @param {String} [options.model] current record's model
2216      * @param {Number} [options.id] current record's id
2217      * @return {String}
2218      */
2219     format: function (row_data, options) {
2220         options = options || {};
2221         var attrs = {};
2222         if (options.process_modifiers !== false) {
2223             attrs = this.modifiers_for(row_data);
2224         }
2225         if (attrs.invisible) { return ''; }
2226
2227         if (!row_data[this.id]) {
2228             return options.value_if_empty === undefined
2229                     ? ''
2230                     : options.value_if_empty;
2231         }
2232         return this._format(row_data, options);
2233     },
2234     /**
2235      * Method to override in order to provide alternative HTML content for the
2236      * cell. Column._format will simply call ``instance.web.format_value`` and
2237      * escape the output.
2238      *
2239      * The output of ``_format`` will *not* be escaped by ``format``, any
2240      * escaping *must be done* by ``format``.
2241      *
2242      * @private
2243      */
2244     _format: function (row_data, options) {
2245         return _.escape(instance.web.format_value(
2246             row_data[this.id].value, this, options.value_if_empty));
2247     }
2248 });
2249 instance.web.list.MetaColumn = instance.web.list.Column.extend({
2250     meta: true,
2251     init: function (id, string) {
2252         this._super(id, '', {string: string});
2253     }
2254 });
2255 instance.web.list.Button = instance.web.list.Column.extend({
2256     /**
2257      * Return an actual ``<button>`` tag
2258      */
2259     format: function (row_data, options) {
2260         options = options || {};
2261         var attrs = {};
2262         if (options.process_modifiers !== false) {
2263             attrs = this.modifiers_for(row_data);
2264         }
2265         if (attrs.invisible) { return ''; }
2266
2267         return QWeb.render('ListView.row.button', {
2268             widget: this,
2269             prefix: instance.session.prefix,
2270             disabled: attrs.readonly
2271                 || isNaN(row_data.id.value)
2272                 || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
2273         });
2274     }
2275 });
2276 instance.web.list.Boolean = instance.web.list.Column.extend({
2277     /**
2278      * Return a potentially disabled checkbox input
2279      *
2280      * @private
2281      */
2282     _format: function (row_data, options) {
2283         return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
2284                  row_data[this.id].value ? 'checked="checked"' : '');
2285     }
2286 });
2287 instance.web.list.Binary = instance.web.list.Column.extend({
2288     /**
2289      * Return a link to the binary data as a file
2290      *
2291      * @private
2292      */
2293     _format: function (row_data, options) {
2294         var text = _t("Download");
2295         var value = row_data[this.id].value;
2296         var download_url;
2297         if (value && value.substr(0, 10).indexOf(' ') == -1) {
2298             download_url = "data:application/octet-stream;base64," + value;
2299         } else {
2300             download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
2301             if (this.filename) {
2302                 download_url += '&filename_field=' + this.filename;
2303             }
2304         }
2305         if (this.filename && row_data[this.filename]) {
2306             text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
2307                     row_data[this.filename].value, {type: 'char'}));
2308         }
2309         return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
2310             text: text,
2311             href: download_url,
2312             size: instance.web.binary_to_binsize(value),
2313         });
2314     }
2315 });
2316 instance.web.list.Char = instance.web.list.Column.extend({
2317     replacement: '*',
2318     /**
2319      * If password field, only display replacement characters (if value is
2320      * non-empty)
2321      */
2322     _format: function (row_data, options) {
2323         var value = row_data[this.id].value;
2324         if (value && this.password === 'True') {
2325             return value.replace(/[\s\S]/g, _.escape(this.replacement));
2326         }
2327         return this._super(row_data, options);
2328     }
2329 });
2330 instance.web.list.ProgressBar = instance.web.list.Column.extend({
2331     /**
2332      * Return a formatted progress bar display
2333      *
2334      * @private
2335      */
2336     _format: function (row_data, options) {
2337         return _.template(
2338             '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
2339                 value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
2340             });
2341     }
2342 });
2343 instance.web.list.Handle = instance.web.list.Column.extend({
2344     init: function () {
2345         this._super.apply(this, arguments);
2346         // Handle overrides the field to not be form-editable.
2347         this.modifiers.readonly = true;
2348     },
2349     /**
2350      * Return styling hooks for a drag handle
2351      *
2352      * @private
2353      */
2354     _format: function (row_data, options) {
2355         return '<div class="oe_list_handle">';
2356     }
2357 });
2358 instance.web.list.Many2OneButton = instance.web.list.Column.extend({
2359     _format: function (row_data, options) {
2360         this.has_value = !!row_data[this.id].value;
2361         this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
2362         this.string = this.has_value ? _t('View') : _t('Create');
2363         return QWeb.render('Many2OneButton.cell', {
2364             'widget': this,
2365             'prefix': instance.session.prefix,
2366         });
2367     },
2368 });
2369 instance.web.list.Many2Many = instance.web.list.Column.extend({
2370     _format: function (row_data, options) {
2371         if (!_.isEmpty(row_data[this.id].value)) {
2372             // If value, use __display version for printing
2373             row_data[this.id] = row_data[this.id + '__display'];
2374         }
2375         return this._super(row_data, options);
2376     }
2377 });
2378 instance.web.list.Reference = instance.web.list.Column.extend({
2379     _format: function (row_data, options) {
2380         if (!_.isEmpty(row_data[this.id].value)) {
2381             // If value, use __display version for printing
2382             if (!!row_data[this.id + '__display']) {
2383                 row_data[this.id] = row_data[this.id + '__display'];
2384             } else {
2385                 row_data[this.id] = {'value': ''};
2386             }
2387         }
2388         return this._super(row_data, options);
2389     }
2390 });
2391 })();
2392 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: