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