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