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