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