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