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