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