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