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