[MERGE] forward port of branch saas-3 up to 7ab4137
[odoo/odoo.git] / addons / web / static / src / js / search.js
1
2 (function() {
3
4 var instance = openerp;
5 openerp.web.search = {};
6
7 var QWeb = instance.web.qweb,
8       _t =  instance.web._t,
9      _lt = instance.web._lt;
10 _.mixin({
11     sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
12 });
13
14 /** @namespace */
15 var my = instance.web.search = {};
16
17 var B = Backbone;
18 my.FacetValue = B.Model.extend({
19
20 });
21 my.FacetValues = B.Collection.extend({
22     model: my.FacetValue
23 });
24 my.Facet = B.Model.extend({
25     initialize: function (attrs) {
26         var values = attrs.values;
27         delete attrs.values;
28
29         B.Model.prototype.initialize.apply(this, arguments);
30
31         this.values = new my.FacetValues(values || []);
32         this.values.on('add remove change reset', function (_, options) {
33             this.trigger('change', this, options);
34         }, this);
35     },
36     get: function (key) {
37         if (key !== 'values') {
38             return B.Model.prototype.get.call(this, key);
39         }
40         return this.values.toJSON();
41     },
42     set: function (key, value) {
43         if (key !== 'values') {
44             return B.Model.prototype.set.call(this, key, value);
45         }
46         this.values.reset(value);
47     },
48     toJSON: function () {
49         var out = {};
50         var attrs = this.attributes;
51         for(var att in attrs) {
52             if (!attrs.hasOwnProperty(att) || att === 'field') {
53                 continue;
54             }
55             out[att] = attrs[att];
56         }
57         out.values = this.values.toJSON();
58         return out;
59     }
60 });
61 my.SearchQuery = B.Collection.extend({
62     model: my.Facet,
63     initialize: function () {
64         B.Collection.prototype.initialize.apply(
65             this, arguments);
66         this.on('change', function (facet) {
67             if(!facet.values.isEmpty()) { return; }
68
69             this.remove(facet, {silent: true});
70         }, this);
71     },
72     add: function (values, options) {
73         options = options || {};
74
75         if (!values) {
76             values = [];
77         } else if (!(values instanceof Array)) {
78             values = [values];
79         }
80
81         _(values).each(function (value) {
82             var model = this._prepareModel(value, options);
83             var previous = this.detect(function (facet) {
84                 return facet.get('category') === model.get('category')
85                     && facet.get('field') === model.get('field');
86             });
87             if (previous) {
88                 previous.values.add(model.get('values'), _.omit(options, 'at', 'merge'));
89                 return;
90             }
91             B.Collection.prototype.add.call(this, model, options);
92         }, this);
93         // warning: in backbone 1.0+ add is supposed to return the added models,
94         // but here toggle may delegate to add and return its value directly.
95         // return value of neither seems actually used but should be tested
96         // before change, probably
97         return this;
98     },
99     toggle: function (value, options) {
100         options = options || {};
101
102         var facet = this.detect(function (facet) {
103             return facet.get('category') === value.category
104                 && facet.get('field') === value.field;
105         });
106         if (!facet) {
107             return this.add(value, options);
108         }
109
110         var changed = false;
111         _(value.values).each(function (val) {
112             var already_value = facet.values.detect(function (v) {
113                 return v.get('value') === val.value
114                     && v.get('label') === val.label;
115             });
116             // toggle value
117             if (already_value) {
118                 facet.values.remove(already_value, {silent: true});
119             } else {
120                 facet.values.add(val, {silent: true});
121             }
122             changed = true;
123         });
124         // "Commit" changes to values array as a single call, so observers of
125         // change event don't get misled by intermediate incomplete toggling
126         // states
127         facet.trigger('change', facet);
128         return this;
129     }
130 });
131
132 function assert(condition, message) {
133     if(!condition) {
134         throw new Error(message);
135     }
136 }
137 my.InputView = instance.web.Widget.extend({
138     template: 'SearchView.InputView',
139     events: {
140         focus: function () { this.trigger('focused', this); },
141         blur: function () { this.$el.text(''); this.trigger('blurred', this); },
142         keydown: 'onKeydown',
143         paste: 'onPaste',
144     },
145     getSelection: function () {
146         this.el.normalize();
147         // get Text node
148         var root = this.el.childNodes[0];
149         if (!root || !root.textContent) {
150             // if input does not have a child node, or the child node is an
151             // empty string, then the selection can only be (0, 0)
152             return {start: 0, end: 0};
153         }
154         var range = window.getSelection().getRangeAt(0);
155         // In Firefox, depending on the way text is selected (drag, double- or
156         // triple-click) the range may start or end on the parent of the
157         // selected text node‽ Check for this condition and fixup the range
158         // note: apparently with C-a this can go even higher?
159         if (range.startContainer === this.el && range.startOffset === 0) {
160             range.setStart(root, 0);
161         }
162         if (range.endContainer === this.el && range.endOffset === 1) {
163             range.setEnd(root, root.length);
164         }
165         assert(range.startContainer === root,
166                "selection should be in the input view");
167         assert(range.endContainer === root,
168                "selection should be in the input view");
169         return {
170             start: range.startOffset,
171             end: range.endOffset
172         };
173     },
174     onKeydown: function (e) {
175         this.el.normalize();
176         var sel;
177         switch (e.which) {
178         // Do not insert newline, but let it bubble so searchview can use it
179         case $.ui.keyCode.ENTER:
180             e.preventDefault();
181             break;
182
183         // FIXME: may forget content if non-empty but caret at index 0, ok?
184         case $.ui.keyCode.BACKSPACE:
185             sel = this.getSelection();
186             if (sel.start === 0 && sel.start === sel.end) {
187                 e.preventDefault();
188                 var preceding = this.getParent().siblingSubview(this, -1);
189                 if (preceding && (preceding instanceof my.FacetView)) {
190                     preceding.model.destroy();
191                 }
192             }
193             break;
194
195         // let left/right events propagate to view if caret is at input border
196         // and not a selection
197         case $.ui.keyCode.LEFT:
198             sel = this.getSelection();
199             if (sel.start !== 0 || sel.start !== sel.end) {
200                 e.stopPropagation();
201             }
202             break;
203         case $.ui.keyCode.RIGHT:
204             sel = this.getSelection();
205             var len = this.$el.text().length;
206             if (sel.start !== len || sel.start !== sel.end) {
207                 e.stopPropagation();
208             }
209             break;
210         }
211     },
212     setCursorAtEnd: function () {
213         this.el.normalize();
214         var sel = window.getSelection();
215         sel.removeAllRanges();
216         var range = document.createRange();
217         // in theory, range.selectNodeContents should work here. In practice,
218         // MSIE9 has issues from time to time, instead of selecting the inner
219         // text node it would select the reference node instead (e.g. in demo
220         // data, company news, copy across the "Company News" link + the title,
221         // from about half the link to half the text, paste in search box then
222         // hit the left arrow key, getSelection would blow up).
223         //
224         // Explicitly selecting only the inner text node (only child node
225         // since we've normalized the parent) avoids the issue
226         range.selectNode(this.el.childNodes[0]);
227         range.collapse(false);
228         sel.addRange(range);
229     },
230     onPaste: function () {
231         this.el.normalize();
232         // In MSIE and Webkit, it is possible to get various representations of
233         // the clipboard data at this point e.g.
234         // window.clipboardData.getData('Text') and
235         // event.clipboardData.getData('text/plain') to ensure we have a plain
236         // text representation of the object (and probably ensure the object is
237         // pastable as well, so nobody puts an image in the search view)
238         // (nb: since it's not possible to alter the content of the clipboard
239         // — at least in Webkit — to ensure only textual content is available,
240         // using this would require 1. getting the text data; 2. manually
241         // inserting the text data into the content; and 3. cancelling the
242         // paste event)
243         //
244         // But Firefox doesn't support the clipboard API (as of FF18)
245         // although it correctly triggers the paste event (Opera does not even
246         // do that) => implement lowest-denominator system where onPaste
247         // triggers a followup "cleanup" pass after the data has been pasted
248         setTimeout(function () {
249             // Read text content (ignore pasted HTML)
250             var data = this.$el.text();
251             if (!data)
252                 return; 
253             // paste raw text back in
254             this.$el.empty().text(data);
255             this.el.normalize();
256             // Set the cursor at the end of the text, so the cursor is not lost
257             // in some kind of error-spawning limbo.
258             this.setCursorAtEnd();
259         }.bind(this), 0);
260     }
261 });
262 my.FacetView = instance.web.Widget.extend({
263     template: 'SearchView.FacetView',
264     events: {
265         'focus': function () { this.trigger('focused', this); },
266         'blur': function () { this.trigger('blurred', this); },
267         'click': function (e) {
268             if ($(e.target).is('.oe_facet_remove')) {
269                 this.model.destroy();
270                 return false;
271             }
272             this.$el.focus();
273             e.stopPropagation();
274         },
275         'keydown': function (e) {
276             var keys = $.ui.keyCode;
277             switch (e.which) {
278             case keys.BACKSPACE:
279             case keys.DELETE:
280                 this.model.destroy();
281                 return false;
282             }
283         }
284     },
285     init: function (parent, model) {
286         this._super(parent);
287         this.model = model;
288         this.model.on('change', this.model_changed, this);
289     },
290     destroy: function () {
291         this.model.off('change', this.model_changed, this);
292         this._super();
293     },
294     start: function () {
295         var self = this;
296         var $e = this.$('> span:last-child');
297         return $.when(this._super()).then(function () {
298             return $.when.apply(null, self.model.values.map(function (value) {
299                 return new my.FacetValueView(self, value).appendTo($e);
300             }));
301         });
302     },
303     model_changed: function () {
304         this.$el.text(this.$el.text() + '*');
305     }
306 });
307 my.FacetValueView = instance.web.Widget.extend({
308     template: 'SearchView.FacetView.Value',
309     init: function (parent, model) {
310         this._super(parent);
311         this.model = model;
312         this.model.on('change', this.model_changed, this);
313     },
314     destroy: function () {
315         this.model.off('change', this.model_changed, this);
316         this._super();
317     },
318     model_changed: function () {
319         this.$el.text(this.$el.text() + '*');
320     }
321 });
322
323 instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
324     template: "SearchView",
325     events: {
326         // focus last input if view itself is clicked
327         'click': function (e) {
328             if (e.target === this.$('.oe_searchview_facets')[0]) {
329                 this.$('.oe_searchview_input:last').focus();
330             }
331         },
332         // search button
333         'click button.oe_searchview_search': function (e) {
334             e.stopImmediatePropagation();
335             this.do_search();
336         },
337         'click .oe_searchview_clear': function (e) {
338             e.stopImmediatePropagation();
339             this.query.reset();
340         },
341         'click .oe_searchview_unfold_drawer': function (e) {
342             e.stopImmediatePropagation();
343             if (this.drawer) 
344                 this.drawer.toggle();
345         },
346         'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
347             switch(e.which) {
348             case $.ui.keyCode.LEFT:
349                 this.focusPreceding(e.target);
350                 e.preventDefault();
351                 break;
352             case $.ui.keyCode.RIGHT:
353                 if (!this.autocomplete.is_expandable()) {
354                     this.focusFollowing(e.target);
355                 }
356                 e.preventDefault();
357                 break;
358             }
359         },
360         'autocompleteopen': function () {
361             this.$el.autocomplete('widget').css('z-index', 9999);
362         },
363     },
364     /**
365      * @constructs instance.web.SearchView
366      * @extends instance.web.Widget
367      *
368      * @param parent
369      * @param dataset
370      * @param view_id
371      * @param defaults
372      * @param {Object} [options]
373      * @param {Boolean} [options.hidden=false] hide the search view
374      * @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
375      */
376     init: function(parent, dataset, view_id, defaults, options) {
377         this.options = _.defaults(options || {}, {
378             hidden: false,
379             disable_custom_filters: false,
380         });
381         this._super(parent);
382         this.dataset = dataset;
383         this.model = dataset.model;
384         this.view_id = view_id;
385
386         this.defaults = defaults || {};
387         this.has_defaults = !_.isEmpty(this.defaults);
388
389         this.headless = this.options.hidden && !this.has_defaults;
390
391         this.input_subviews = [];
392         this.view_manager = null;
393         this.$view_manager_header = null;
394
395         this.ready = $.Deferred();
396         this.drawer_ready = $.Deferred();
397         this.fields_view_get = $.Deferred();
398         this.drawer = new instance.web.SearchViewDrawer(parent, this);
399
400     },
401     start: function() {
402         var self = this;
403         var p = this._super();
404
405         this.$view_manager_header = this.$el.parents(".oe_view_manager_header").first();
406
407         this.setup_global_completion();
408         this.query = new my.SearchQuery()
409                 .on('add change reset remove', this.proxy('do_search'))
410                 .on('change', this.proxy('renderChangedFacets'))
411                 .on('add reset remove', this.proxy('renderFacets'));
412
413         if (this.options.hidden) {
414             this.$el.hide();
415         }
416         if (this.headless) {
417             this.ready.resolve();
418         } else {
419             var load_view = instance.web.fields_view_get({
420                 model: this.dataset._model,
421                 view_id: this.view_id,
422                 view_type: 'search',
423                 context: this.dataset.get_context(),
424             });
425
426             this.alive($.when(load_view)).then(function (r) {
427                 self.fields_view_get.resolve(r);
428                 return self.search_view_loaded(r);
429             }).fail(function () {
430                 self.ready.reject.apply(null, arguments);
431             });
432         }
433
434         var view_manager = this.getParent();
435         while (!(view_manager instanceof instance.web.ViewManager) &&
436                 view_manager && view_manager.getParent) {
437             view_manager = view_manager.getParent();
438         }
439
440         if (view_manager) {
441             this.view_manager = view_manager;
442             view_manager.on('switch_mode', this, function (e) {
443                 self.drawer.toggle(e === 'graph');
444             });
445         }
446         return $.when(p, this.ready);
447     },
448
449     set_drawer: function (drawer) {
450         this.drawer = drawer;
451     },
452
453     show: function () {
454         this.$el.show();
455     },
456     hide: function () {
457         this.$el.hide();
458     },
459
460     subviewForRoot: function (subview_root) {
461         return _(this.input_subviews).detect(function (subview) {
462             return subview.$el[0] === subview_root;
463         });
464     },
465     siblingSubview: function (subview, direction, wrap_around) {
466         var index = _(this.input_subviews).indexOf(subview) + direction;
467         if (wrap_around && index < 0) {
468             index = this.input_subviews.length - 1;
469         } else if (wrap_around && index >= this.input_subviews.length) {
470             index = 0;
471         }
472         return this.input_subviews[index];
473     },
474     focusPreceding: function (subview_root) {
475         return this.siblingSubview(
476             this.subviewForRoot(subview_root), -1, true)
477                 .$el.focus();
478     },
479     focusFollowing: function (subview_root) {
480         return this.siblingSubview(
481             this.subviewForRoot(subview_root), +1, true)
482                 .$el.focus();
483     },
484
485     /**
486      * Sets up search view's view-wide auto-completion widget
487      */
488     setup_global_completion: function () {
489         var self = this;
490         this.autocomplete = new instance.web.search.AutoComplete(this, {
491             source: this.proxy('complete_global_search'),
492             select: this.proxy('select_completion'),
493             delay: 0,
494             get_search_string: function () {
495                 return self.$('div.oe_searchview_input').text();
496             },
497             width: this.$el.width(),
498         });
499         this.autocomplete.appendTo(this.$el);
500     },
501     /**
502      * Provide auto-completion result for req.term (an array to `resp`)
503      *
504      * @param {Object} req request to complete
505      * @param {String} req.term searched term to complete
506      * @param {Function} resp response callback
507      */
508     complete_global_search:  function (req, resp) {
509         $.when.apply(null, _(this.drawer.inputs).chain()
510             .filter(function (input) { return input.visible(); })
511             .invoke('complete', req.term)
512             .value()).then(function () {
513                 resp(_(arguments).chain()
514                     .compact()
515                     .flatten(true)
516                     .value());
517                 });
518     },
519
520     /**
521      * Action to perform in case of selection: create a facet (model)
522      * and add it to the search collection
523      *
524      * @param {Object} e selection event, preventDefault to avoid setting value on object
525      * @param {Object} ui selection information
526      * @param {Object} ui.item selected completion item
527      */
528     select_completion: function (e, ui) {
529         e.preventDefault();
530
531         var input_index = _(this.input_subviews).indexOf(
532             this.subviewForRoot(
533                 this.$('div.oe_searchview_input:focus')[0]));
534         this.query.add(ui.item.facet, {at: input_index / 2});
535     },
536     childFocused: function () {
537         this.$el.addClass('oe_focused');
538     },
539     childBlurred: function () {
540         var val = this.$el.val();
541         this.$el.val('');
542         this.$el.removeClass('oe_focused')
543                      .trigger('blur');
544         this.autocomplete.close();
545     },
546     /**
547      * Call the renderFacets method with the correct arguments.
548      * This is due to the fact that change events are called with two arguments
549      * (model, options) while add, reset and remove events are called with
550      * (collection, model, options) as arguments
551      */
552     renderChangedFacets: function (model, options) {
553         this.renderFacets(undefined, model, options);
554     },
555     /**
556      * @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
557      * @param {openerp.web.search.Facet} 
558      * @param {Object} [options]
559      */
560     renderFacets: function (collection, model, options) {
561         var self = this;
562         var started = [];
563         var $e = this.$('div.oe_searchview_facets');
564         _.invoke(this.input_subviews, 'destroy');
565         this.input_subviews = [];
566
567         var i = new my.InputView(this);
568         started.push(i.appendTo($e));
569         this.input_subviews.push(i);
570         this.query.each(function (facet) {
571             var f = new my.FacetView(this, facet);
572             started.push(f.appendTo($e));
573             self.input_subviews.push(f);
574
575             var i = new my.InputView(this);
576             started.push(i.appendTo($e));
577             self.input_subviews.push(i);
578         }, this);
579         _.each(this.input_subviews, function (childView) {
580             childView.on('focused', self, self.proxy('childFocused'));
581             childView.on('blurred', self, self.proxy('childBlurred'));
582         });
583
584         $.when.apply(null, started).then(function () {
585             if (options && options.focus_input === false) return;
586             var input_to_focus;
587             // options.at: facet inserted at given index, focus next input
588             // otherwise just focus last input
589             if (!options || typeof options.at !== 'number') {
590                 input_to_focus = _.last(self.input_subviews);
591             } else {
592                 input_to_focus = self.input_subviews[(options.at + 1) * 2];
593             }
594             input_to_focus.$el.focus();
595         });
596     },
597
598     search_view_loaded: function(data) {
599         var self = this;
600         this.fields_view = data;
601         if (data.type !== 'search' ||
602             data.arch.tag !== 'search') {
603                 throw new Error(_.str.sprintf(
604                     "Got non-search view after asking for a search view: type %s, arch root %s",
605                     data.type, data.arch.tag));
606         }
607
608         return this.drawer_ready
609             .then(this.proxy('setup_default_query'))
610             .then(function () { 
611                 self.trigger("search_view_loaded", data);
612                 self.ready.resolve();
613             });
614     },
615     setup_default_query: function () {
616         // Hacky implementation of CustomFilters#facet_for_defaults ensure
617         // CustomFilters will be ready (and CustomFilters#filters will be
618         // correctly filled) by the time this method executes.
619         var custom_filters = this.drawer.custom_filters.filters;
620         if (!this.options.disable_custom_filters && !_(custom_filters).isEmpty()) {
621             // Check for any is_default custom filter
622             var personal_filter = _(custom_filters).find(function (filter) {
623                 return filter.user_id && filter.is_default;
624             });
625             if (personal_filter) {
626                 this.drawer.custom_filters.toggle_filter(personal_filter, true);
627                 return;
628             }
629
630             var global_filter = _(custom_filters).find(function (filter) {
631                 return !filter.user_id && filter.is_default;
632             });
633             if (global_filter) {
634                 this.drawer.custom_filters.toggle_filter(global_filter, true);
635                 return;
636             }
637         }
638         // No custom filter, or no is_default custom filter, apply view defaults
639         this.query.reset(_(arguments).compact(), {preventSearch: true});
640     },
641     /**
642      * Extract search data from the view's facets.
643      *
644      * Result is an object with 4 (own) properties:
645      *
646      * errors
647      *     An array of any error generated during data validation and
648      *     extraction, contains the validation error objects
649      * domains
650      *     Array of domains
651      * contexts
652      *     Array of contexts
653      * groupbys
654      *     Array of domains, in groupby order rather than view order
655      *
656      * @return {Object}
657      */
658     build_search_data: function () {
659         var domains = [], contexts = [], groupbys = [], errors = [];
660
661         this.query.each(function (facet) {
662             var field = facet.get('field');
663             try {
664                 var domain = field.get_domain(facet);
665                 if (domain) {
666                     domains.push(domain);
667                 }
668                 var context = field.get_context(facet);
669                 if (context) {
670                     contexts.push(context);
671                 }
672                 var group_by = field.get_groupby(facet);
673                 if (group_by) {
674                     groupbys.push.apply(groupbys, group_by);
675                 }
676             } catch (e) {
677                 if (e instanceof instance.web.search.Invalid) {
678                     errors.push(e);
679                 } else {
680                     throw e;
681                 }
682             }
683         });
684         return {
685             domains: domains,
686             contexts: contexts,
687             groupbys: groupbys,
688             errors: errors
689         };
690     }, 
691     /**
692      * Performs the search view collection of widget data.
693      *
694      * If the collection went well (all fields are valid), then triggers
695      * :js:func:`instance.web.SearchView.on_search`.
696      *
697      * If at least one field failed its validation, triggers
698      * :js:func:`instance.web.SearchView.on_invalid` instead.
699      *
700      * @param [_query]
701      * @param {Object} [options]
702      */
703     do_search: function (_query, options) {
704         if (options && options.preventSearch) {
705             return;
706         }
707         var search = this.build_search_data();
708         if (!_.isEmpty(search.errors)) {
709             this.on_invalid(search.errors);
710             return;
711         }
712         this.trigger('search_data', search.domains, search.contexts, search.groupbys);
713     },
714     /**
715      * Triggered after the SearchView has collected all relevant domains and
716      * contexts.
717      *
718      * It is provided with an Array of domains and an Array of contexts, which
719      * may or may not be evaluated (each item can be either a valid domain or
720      * context, or a string to evaluate in order in the sequence)
721      *
722      * It is also passed an array of contexts used for group_by (they are in
723      * the correct order for group_by evaluation, which contexts may not be)
724      *
725      * @event
726      * @param {Array} domains an array of literal domains or domain references
727      * @param {Array} contexts an array of literal contexts or context refs
728      * @param {Array} groupbys ordered contexts which may or may not have group_by keys
729      */
730     /**
731      * Triggered after a validation error in the SearchView fields.
732      *
733      * Error objects have three keys:
734      * * ``field`` is the name of the invalid field
735      * * ``value`` is the invalid value
736      * * ``message`` is the (in)validation message provided by the field
737      *
738      * @event
739      * @param {Array} errors a never-empty array of error objects
740      */
741     on_invalid: function (errors) {
742         this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
743         this.trigger('invalid_search', errors);
744     },
745
746     // The method appendTo is overwrited to be able to insert the drawer anywhere
747     appendTo: function ($searchview_parent, $searchview_drawer_node) {
748         var $searchview_drawer_node = $searchview_drawer_node || $searchview_parent;
749
750         return $.when(
751             this._super($searchview_parent),
752             this.drawer.appendTo($searchview_drawer_node)
753         );
754     },
755
756     destroy: function () {
757         this.drawer.destroy();
758         this.getParent().destroy.call(this);
759     }
760 });
761
762 instance.web.SearchViewDrawer = instance.web.Widget.extend({
763     template: "SearchViewDrawer",
764
765     init: function(parent, searchview) {
766         this._super(parent);
767         this.searchview = searchview;
768         this.searchview.set_drawer(this);
769         this.ready = searchview.drawer_ready;
770         this.controls = [];
771         this.inputs = [];
772     },
773
774     toggle: function (visibility) {
775         this.$el.toggle(visibility);
776         var $view_manager_body = this.$el.closest('.oe_view_manager_body');
777         if ($view_manager_body.length) {
778             $view_manager_body.scrollTop(0);
779         }
780     },
781
782     start: function() {
783         var self = this;
784         if (this.searchview.headless) return $.when(this._super(), this.searchview.ready);
785         var filters_ready = this.searchview.fields_view_get
786                                 .then(this.proxy('prepare_filters'));
787         return $.when(this._super(), filters_ready).then(function () {
788             var defaults = arguments[1][0];
789             self.ready.resolve.apply(null, defaults);
790         });
791     },
792     prepare_filters: function (data) {
793         this.make_widgets(
794             data['arch'].children,
795             data.fields);
796
797         this.add_common_inputs();
798
799         // build drawer
800         var in_drawer = this.select_for_drawer();
801
802         var $first_col = this.$(".col-md-7"),
803             $snd_col = this.$(".col-md-5");
804
805         var add_custom_filters = in_drawer[0].appendTo($first_col),
806             add_filters = in_drawer[1].appendTo($first_col),
807             add_rest = $.when.apply(null, _(in_drawer.slice(2)).invoke('appendTo', $snd_col)),
808             defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
809                 'facet_for_defaults', this.searchview.defaults));
810
811         return $.when(defaults_fetched, add_custom_filters, add_filters, add_rest);
812     },
813     /**
814      * Sets up thingie where all the mess is put?
815      */
816     select_for_drawer: function () {
817         return _(this.inputs).filter(function (input) {
818             return input.in_drawer();
819         });
820     },
821
822     /**
823      * Builds a list of widget rows (each row is an array of widgets)
824      *
825      * @param {Array} items a list of nodes to convert to widgets
826      * @param {Object} fields a mapping of field names to (ORM) field attributes
827      * @param {Object} [group] group to put the new controls in
828      */
829     make_widgets: function (items, fields, group) {
830         if (!group) {
831             group = new instance.web.search.Group(
832                 this, 'q', {attrs: {string: _t("Filters")}});
833         }
834         var self = this;
835         var filters = [];
836         _.each(items, function (item) {
837             if (filters.length && item.tag !== 'filter') {
838                 group.push(new instance.web.search.FilterGroup(filters, group));
839                 filters = [];
840             }
841
842             switch (item.tag) {
843             case 'separator': case 'newline':
844                 break;
845             case 'filter':
846                 filters.push(new instance.web.search.Filter(item, group));
847                 break;
848             case 'group':
849                 self.add_separator();
850                 self.make_widgets(item.children, fields,
851                     new instance.web.search.Group(group, 'w', item));
852                 self.add_separator();
853                 break;
854             case 'field':
855                 var field = this.make_field(
856                     item, fields[item['attrs'].name], group);
857                 group.push(field);
858                 // filters
859                 self.make_widgets(item.children, fields, group);
860                 break;
861             }
862         }, this);
863
864         if (filters.length) {
865             group.push(new instance.web.search.FilterGroup(filters, this));
866         }
867     },
868
869     add_separator: function () {
870         if (!(_.last(this.inputs) instanceof instance.web.search.Separator))
871             new instance.web.search.Separator(this);
872     },
873     /**
874      * Creates a field for the provided field descriptor item (which comes
875      * from fields_view_get)
876      *
877      * @param {Object} item fields_view_get node for the field
878      * @param {Object} field fields_get result for the field
879      * @param {Object} [parent]
880      * @returns instance.web.search.Field
881      */
882     make_field: function (item, field, parent) {
883         // M2O combined with selection widget is pointless and broken in search views,
884         // but has been used in the past for unsupported hacks -> ignore it
885         if (field.type === "many2one" && item.attrs.widget === "selection"){
886             item.attrs.widget = undefined;
887         }
888         var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]);
889         if(obj) {
890             return new (obj) (item, field, parent || this);
891         } else {
892             console.group('Unknown field type ' + field.type);
893             console.error('View node', item);
894             console.info('View field', field);
895             console.info('In view', this);
896             console.groupEnd();
897             return null;
898         }
899     },
900
901     add_common_inputs: function() {
902         // add custom filters to this.inputs
903         this.custom_filters = new instance.web.search.CustomFilters(this);
904         // add Filters to this.inputs, need view.controls filled
905         (new instance.web.search.Filters(this));
906         (new instance.web.search.SaveFilter(this, this.custom_filters));
907         // add Advanced to this.inputs
908         (new instance.web.search.Advanced(this));
909     },
910
911 });
912
913 /**
914  * Registry of search fields, called by :js:class:`instance.web.SearchView` to
915  * find and instantiate its field widgets.
916  */
917 instance.web.search.fields = new instance.web.Registry({
918     'char': 'instance.web.search.CharField',
919     'text': 'instance.web.search.CharField',
920     'html': 'instance.web.search.CharField',
921     'boolean': 'instance.web.search.BooleanField',
922     'integer': 'instance.web.search.IntegerField',
923     'id': 'instance.web.search.IntegerField',
924     'float': 'instance.web.search.FloatField',
925     'selection': 'instance.web.search.SelectionField',
926     'datetime': 'instance.web.search.DateTimeField',
927     'date': 'instance.web.search.DateField',
928     'many2one': 'instance.web.search.ManyToOneField',
929     'many2many': 'instance.web.search.CharField',
930     'one2many': 'instance.web.search.CharField'
931 });
932 instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{
933     /**
934      * Exception thrown by search widgets when they hold invalid values,
935      * which they can not return when asked.
936      *
937      * @constructs instance.web.search.Invalid
938      * @extends instance.web.Class
939      *
940      * @param field the name of the field holding an invalid value
941      * @param value the invalid value
942      * @param message validation failure message
943      */
944     init: function (field, value, message) {
945         this.field = field;
946         this.value = value;
947         this.message = message;
948     },
949     toString: function () {
950         return _.str.sprintf(
951             _t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
952             {fieldname: this.field, value: this.value, message: this.message}
953         );
954     }
955 });
956 instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{
957     template: null,
958     /**
959      * Root class of all search widgets
960      *
961      * @constructs instance.web.search.Widget
962      * @extends instance.web.Widget
963      *
964      * @param parent parent of this widget
965      */
966     init: function (parent) {
967         this._super(parent);
968         var ancestor = parent;
969         do {
970             this.drawer = ancestor;
971         } while (!(ancestor instanceof instance.web.SearchViewDrawer)
972                && (ancestor = (ancestor.getParent && ancestor.getParent())));
973         this.view = this.drawer.searchview || this.drawer;
974     }
975 });
976
977 instance.web.search.add_expand_listener = function($root) {
978     $root.find('a.searchview_group_string').click(function (e) {
979         $root.toggleClass('folded expanded');
980         e.stopPropagation();
981         e.preventDefault();
982     });
983 };
984 instance.web.search.Group = instance.web.search.Widget.extend({
985     init: function (parent, icon, node) {
986         this._super(parent);
987         var attrs = node.attrs;
988         this.modifiers = attrs.modifiers =
989             attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
990         this.attrs = attrs;
991         this.icon = icon;
992         this.name = attrs.string;
993         this.children = [];
994
995         this.drawer.controls.push(this);
996     },
997     push: function (input) {
998         this.children.push(input);
999     },
1000     visible: function () {
1001         return !this.modifiers.invisible;
1002     },
1003 });
1004
1005 instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{
1006     _in_drawer: false,
1007     /**
1008      * @constructs instance.web.search.Input
1009      * @extends instance.web.search.Widget
1010      *
1011      * @param parent
1012      */
1013     init: function (parent) {
1014         this._super(parent);
1015         this.load_attrs({});
1016         this.drawer.inputs.push(this);
1017     },
1018     /**
1019      * Fetch auto-completion values for the widget.
1020      *
1021      * The completion values should be an array of objects with keys category,
1022      * label, value prefixed with an object with keys type=section and label
1023      *
1024      * @param {String} value value to complete
1025      * @returns {jQuery.Deferred<null|Array>}
1026      */
1027     complete: function (value) {
1028         return $.when(null);
1029     },
1030     /**
1031      * Returns a Facet instance for the provided defaults if they apply to
1032      * this widget, or null if they don't.
1033      *
1034      * This default implementation will try calling
1035      * :js:func:`instance.web.search.Input#facet_for` if the widget's name
1036      * matches the input key
1037      *
1038      * @param {Object} defaults
1039      * @returns {jQuery.Deferred<null|Object>}
1040      */
1041     facet_for_defaults: function (defaults) {
1042         if (!this.attrs ||
1043             !(this.attrs.name in defaults && defaults[this.attrs.name])) {
1044             return $.when(null);
1045         }
1046         return this.facet_for(defaults[this.attrs.name]);
1047     },
1048     in_drawer: function () {
1049         return !!this._in_drawer;
1050     },
1051     get_context: function () {
1052         throw new Error(
1053             "get_context not implemented for widget " + this.attrs.type);
1054     },
1055     get_groupby: function () {
1056         throw new Error(
1057             "get_groupby not implemented for widget " + this.attrs.type);
1058     },
1059     get_domain: function () {
1060         throw new Error(
1061             "get_domain not implemented for widget " + this.attrs.type);
1062     },
1063     load_attrs: function (attrs) {
1064         attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
1065         this.attrs = attrs;
1066     },
1067     /**
1068      * Returns whether the input is "visible". The default behavior is to
1069      * query the ``modifiers.invisible`` flag on the input's description or
1070      * view node.
1071      *
1072      * @returns {Boolean}
1073      */
1074     visible: function () {
1075         if (this.attrs.modifiers.invisible) {
1076             return false;
1077         }
1078         var parent = this;
1079         while ((parent = parent.getParent()) &&
1080                (   (parent instanceof instance.web.search.Group)
1081                 || (parent instanceof instance.web.search.Input))) {
1082             if (!parent.visible()) {
1083                 return false;
1084             }
1085         }
1086         return true;
1087     },
1088 });
1089 instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
1090     template: 'SearchView.filters',
1091     icon: 'q',
1092     completion_label: _lt("Filter on: %s"),
1093     /**
1094      * Inclusive group of filters, creates a continuous "button" with clickable
1095      * sections (the normal display for filters is to be a self-contained button)
1096      *
1097      * @constructs instance.web.search.FilterGroup
1098      * @extends instance.web.search.Input
1099      *
1100      * @param {Array<instance.web.search.Filter>} filters elements of the group
1101      * @param {instance.web.SearchView} parent parent in which the filters are contained
1102      */
1103     init: function (filters, parent) {
1104         // If all filters are group_by and we're not initializing a GroupbyGroup,
1105         // create a GroupbyGroup instead of the current FilterGroup
1106         if (!(this instanceof instance.web.search.GroupbyGroup) &&
1107               _(filters).all(function (f) {
1108                   if (!f.attrs.context) { return false; }
1109                   var c = instance.web.pyeval.eval('context', f.attrs.context);
1110                   return !_.isEmpty(c.group_by);})) {
1111             return new instance.web.search.GroupbyGroup(filters, parent);
1112         }
1113         this._super(parent);
1114         this.filters = filters;
1115         this.view.query.on('add remove change reset', this.proxy('search_change'));
1116     },
1117     start: function () {
1118         this.$el.on('click', 'li', this.proxy('toggle_filter'));
1119         return $.when(null);
1120     },
1121     /**
1122      * Handles change of the search query: any of the group's filter which is
1123      * in the search query should be visually checked in the drawer
1124      */
1125     search_change: function () {
1126         var self = this;
1127         var $filters = this.$('> li').removeClass('badge');
1128         var facet = this.view.query.find(_.bind(this.match_facet, this));
1129         if (!facet) { return; }
1130         facet.values.each(function (v) {
1131             var i = _(self.filters).indexOf(v.get('value'));
1132             if (i === -1) { return; }
1133             $filters.filter(function () {
1134                 return Number($(this).data('index')) === i;
1135             }).addClass('badge');
1136         });
1137     },
1138     /**
1139      * Matches the group to a facet, in order to find if the group is
1140      * represented in the current search query
1141      */
1142     match_facet: function (facet) {
1143         return facet.get('field') === this;
1144     },
1145     make_facet: function (values) {
1146         return {
1147             category: _t("Filter"),
1148             icon: this.icon,
1149             values: values,
1150             field: this
1151         };
1152     },
1153     make_value: function (filter) {
1154         return {
1155             label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
1156             value: filter
1157         };
1158     },
1159     facet_for_defaults: function (defaults) {
1160         var self = this;
1161         var fs = _(this.filters).chain()
1162             .filter(function (f) {
1163                 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
1164             }).map(function (f) {
1165                 return self.make_value(f);
1166             }).value();
1167         if (_.isEmpty(fs)) { return $.when(null); }
1168         return $.when(this.make_facet(fs));
1169     },
1170     /**
1171      * Fetches contexts for all enabled filters in the group
1172      *
1173      * @param {openerp.web.search.Facet} facet
1174      * @return {*} combined contexts of the enabled filters in this group
1175      */
1176     get_context: function (facet) {
1177         var contexts = facet.values.chain()
1178             .map(function (f) { return f.get('value').attrs.context; })
1179             .without('{}')
1180             .reject(_.isEmpty)
1181             .value();
1182
1183         if (!contexts.length) { return; }
1184         if (contexts.length === 1) { return contexts[0]; }
1185         return _.extend(new instance.web.CompoundContext(), {
1186             __contexts: contexts
1187         });
1188     },
1189     /**
1190      * Fetches group_by sequence for all enabled filters in the group
1191      *
1192      * @param {VS.model.SearchFacet} facet
1193      * @return {Array} enabled filters in this group
1194      */
1195     get_groupby: function (facet) {
1196         return  facet.values.chain()
1197             .map(function (f) { return f.get('value').attrs.context; })
1198             .without('{}')
1199             .reject(_.isEmpty)
1200             .value();
1201     },
1202     /**
1203      * Handles domains-fetching for all the filters within it: groups them.
1204      *
1205      * @param {VS.model.SearchFacet} facet
1206      * @return {*} combined domains of the enabled filters in this group
1207      */
1208     get_domain: function (facet) {
1209         var domains = facet.values.chain()
1210             .map(function (f) { return f.get('value').attrs.domain; })
1211             .without('[]')
1212             .reject(_.isEmpty)
1213             .value();
1214
1215         if (!domains.length) { return; }
1216         if (domains.length === 1) { return domains[0]; }
1217         for (var i=domains.length; --i;) {
1218             domains.unshift(['|']);
1219         }
1220         return _.extend(new instance.web.CompoundDomain(), {
1221             __domains: domains
1222         });
1223     },
1224     toggle_filter: function (e) {
1225         this.toggle(this.filters[Number($(e.target).data('index'))]);
1226     },
1227     toggle: function (filter) {
1228         this.view.query.toggle(this.make_facet([this.make_value(filter)]));
1229     },
1230     complete: function (item) {
1231         var self = this;
1232         item = item.toLowerCase();
1233         var facet_values = _(this.filters).chain()
1234             .filter(function (filter) { return filter.visible(); })
1235             .filter(function (filter) {
1236                 var at = {
1237                     string: filter.attrs.string || '',
1238                     help: filter.attrs.help || '',
1239                     name: filter.attrs.name || ''
1240                 };
1241                 var include = _.str.include;
1242                 return include(at.string.toLowerCase(), item)
1243                     || include(at.help.toLowerCase(), item)
1244                     || include(at.name.toLowerCase(), item);
1245             })
1246             .map(this.make_value)
1247             .value();
1248         if (_(facet_values).isEmpty()) { return $.when(null); }
1249         return $.when(_.map(facet_values, function (facet_value) {
1250             return {
1251                 label: _.str.sprintf(self.completion_label.toString(),
1252                                      _.escape(facet_value.label)),
1253                 facet: self.make_facet([facet_value])
1254             };
1255         }));
1256     }
1257 });
1258 instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
1259     icon: 'w',
1260     completion_label: _lt("Group by: %s"),
1261     init: function (filters, parent) {
1262         this._super(filters, parent);
1263         // Not flanders: facet unicity is handled through the
1264         // (category, field) pair of facet attributes. This is all well and
1265         // good for regular filter groups where a group matches a facet, but for
1266         // groupby we want a single facet. So cheat: add an attribute on the
1267         // view which proxies to the first GroupbyGroup, so it can be used
1268         // for every GroupbyGroup and still provides the various methods needed
1269         // by the search view. Use weirdo name to avoid risks of conflicts
1270         if (!this.view._s_groupby) {
1271             this.view._s_groupby = {
1272                 help: "See GroupbyGroup#init",
1273                 get_context: this.proxy('get_context'),
1274                 get_domain: this.proxy('get_domain'),
1275                 get_groupby: this.proxy('get_groupby')
1276             };
1277         }
1278     },
1279     match_facet: function (facet) {
1280         return facet.get('field') === this.view._s_groupby;
1281     },
1282     make_facet: function (values) {
1283         return {
1284             category: _t("GroupBy"),
1285             icon: this.icon,
1286             values: values,
1287             field: this.view._s_groupby
1288         };
1289     }
1290 });
1291 instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
1292     template: 'SearchView.filter',
1293     /**
1294      * Implementation of the OpenERP filters (button with a context and/or
1295      * a domain sent as-is to the search view)
1296      *
1297      * Filters are only attributes holder, the actual work (compositing
1298      * domains and contexts, converting between facets and filters) is
1299      * performed by the filter group.
1300      *
1301      * @constructs instance.web.search.Filter
1302      * @extends instance.web.search.Input
1303      *
1304      * @param node
1305      * @param parent
1306      */
1307     init: function (node, parent) {
1308         this._super(parent);
1309         this.load_attrs(node.attrs);
1310     },
1311     facet_for: function () { return $.when(null); },
1312     get_context: function () { },
1313     get_domain: function () { },
1314 });
1315
1316 instance.web.search.Separator = instance.web.search.Input.extend({
1317     _in_drawer: false,
1318
1319     complete: function () {
1320         return {is_separator: true};
1321     }
1322 });
1323
1324 instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
1325     template: 'SearchView.field',
1326     default_operator: '=',
1327     /**
1328      * @constructs instance.web.search.Field
1329      * @extends instance.web.search.Input
1330      *
1331      * @param view_section
1332      * @param field
1333      * @param parent
1334      */
1335     init: function (view_section, field, parent) {
1336         this._super(parent);
1337         this.load_attrs(_.extend({}, field, view_section.attrs));
1338     },
1339     facet_for: function (value) {
1340         return $.when({
1341             field: this,
1342             category: this.attrs.string || this.attrs.name,
1343             values: [{label: String(value), value: value}]
1344         });
1345     },
1346     value_from: function (facetValue) {
1347         return facetValue.get('value');
1348     },
1349     get_context: function (facet) {
1350         var self = this;
1351         // A field needs a context to send when active
1352         var context = this.attrs.context;
1353         if (_.isEmpty(context) || !facet.values.length) {
1354             return;
1355         }
1356         var contexts = facet.values.map(function (facetValue) {
1357             return new instance.web.CompoundContext(context)
1358                 .set_eval_context({self: self.value_from(facetValue)});
1359         });
1360
1361         if (contexts.length === 1) { return contexts[0]; }
1362
1363         return _.extend(new instance.web.CompoundContext(), {
1364             __contexts: contexts
1365         });
1366     },
1367     get_groupby: function () { },
1368     /**
1369      * Function creating the returned domain for the field, override this
1370      * methods in children if you only need to customize the field's domain
1371      * without more complex alterations or tests (and without the need to
1372      * change override the handling of filter_domain)
1373      *
1374      * @param {String} name the field's name
1375      * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1376      * @param {Number|String} facet parsed value for the field
1377      * @returns {Array<Array>} domain to include in the resulting search
1378      */
1379     make_domain: function (name, operator, facet) {
1380         return [[name, operator, this.value_from(facet)]];
1381     },
1382     get_domain: function (facet) {
1383         if (!facet.values.length) { return; }
1384
1385         var value_to_domain;
1386         var self = this;
1387         var domain = this.attrs['filter_domain'];
1388         if (domain) {
1389             value_to_domain = function (facetValue) {
1390                 return new instance.web.CompoundDomain(domain)
1391                     .set_eval_context({self: self.value_from(facetValue)});
1392             };
1393         } else {
1394             value_to_domain = function (facetValue) {
1395                 return self.make_domain(
1396                     self.attrs.name,
1397                     self.attrs.operator || self.default_operator,
1398                     facetValue);
1399             };
1400         }
1401         var domains = facet.values.map(value_to_domain);
1402
1403         if (domains.length === 1) { return domains[0]; }
1404         for (var i = domains.length; --i;) {
1405             domains.unshift(['|']);
1406         }
1407
1408         return _.extend(new instance.web.CompoundDomain(), {
1409             __domains: domains
1410         });
1411     }
1412 });
1413 /**
1414  * Implementation of the ``char`` OpenERP field type:
1415  *
1416  * * Default operator is ``ilike`` rather than ``=``
1417  *
1418  * * The Javascript and the HTML values are identical (strings)
1419  *
1420  * @class
1421  * @extends instance.web.search.Field
1422  */
1423 instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
1424     default_operator: 'ilike',
1425     complete: function (value) {
1426         if (_.isEmpty(value)) { return $.when(null); }
1427         var label = _.str.sprintf(_.str.escapeHTML(
1428             _t("Search %(field)s for: %(value)s")), {
1429                 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1430                 value: '<strong>' + _.escape(value) + '</strong>'});
1431         return $.when([{
1432             label: label,
1433             facet: {
1434                 category: this.attrs.string,
1435                 field: this,
1436                 values: [{label: value, value: value}]
1437             }
1438         }]);
1439     }
1440 });
1441 instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
1442     complete: function (value) {
1443         var val = this.parse(value);
1444         if (isNaN(val)) { return $.when(); }
1445         var label = _.str.sprintf(
1446             _t("Search %(field)s for: %(value)s"), {
1447                 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1448                 value: '<strong>' + _.escape(value) + '</strong>'});
1449         return $.when([{
1450             label: label,
1451             facet: {
1452                 category: this.attrs.string,
1453                 field: this,
1454                 values: [{label: value, value: val}]
1455             }
1456         }]);
1457     },
1458 });
1459 /**
1460  * @class
1461  * @extends instance.web.search.NumberField
1462  */
1463 instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
1464     error_message: _t("not a valid integer"),
1465     parse: function (value) {
1466         try {
1467             return instance.web.parse_value(value, {'widget': 'integer'});
1468         } catch (e) {
1469             return NaN;
1470         }
1471     }
1472 });
1473 /**
1474  * @class
1475  * @extends instance.web.search.NumberField
1476  */
1477 instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
1478     error_message: _t("not a valid number"),
1479     parse: function (value) {
1480         try {
1481             return instance.web.parse_value(value, {'widget': 'float'});
1482         } catch (e) {
1483             return NaN;
1484         }
1485     }
1486 });
1487
1488 /**
1489  * Utility function for m2o & selection fields taking a selection/name_get pair
1490  * (value, name) and converting it to a Facet descriptor
1491  *
1492  * @param {instance.web.search.Field} field holder field
1493  * @param {Array} pair pair value to convert
1494  */
1495 function facet_from(field, pair) {
1496     return {
1497         field: field,
1498         category: field['attrs'].string,
1499         values: [{label: pair[1], value: pair[0]}]
1500     };
1501 }
1502
1503 /**
1504  * @class
1505  * @extends instance.web.search.Field
1506  */
1507 instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
1508     // This implementation is a basic <select> field, but it may have to be
1509     // altered to be more in line with the GTK client, which uses a combo box
1510     // (~ jquery.autocomplete):
1511     // * If an option was selected in the list, behave as currently
1512     // * If something which is not in the list was entered (via the text input),
1513     //   the default domain should become (`ilike` string_value) but **any
1514     //   ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1515     //   is specified. So at least get_domain needs to be quite a bit
1516     //   overridden (if there's no @value and there is no filter_domain and
1517     //   there is no @operator, return [[name, 'ilike', str_val]]
1518     template: 'SearchView.field.selection',
1519     init: function () {
1520         this._super.apply(this, arguments);
1521         // prepend empty option if there is no empty option in the selection list
1522         this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1523             return !item[1];
1524         });
1525     },
1526     complete: function (needle) {
1527         var self = this;
1528         var results = _(this.attrs.selection).chain()
1529             .filter(function (sel) {
1530                 var value = sel[0], label = sel[1];
1531                 if (!value) { return false; }
1532                 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1533             })
1534             .map(function (sel) {
1535                 return {
1536                     label: _.escape(sel[1]),
1537                     facet: facet_from(self, sel)
1538                 };
1539             }).value();
1540         if (_.isEmpty(results)) { return $.when(null); }
1541         return $.when.call(null, [{
1542             label: _.escape(this.attrs.string)
1543         }].concat(results));
1544     },
1545     facet_for: function (value) {
1546         var match = _(this.attrs.selection).detect(function (sel) {
1547             return sel[0] === value;
1548         });
1549         if (!match) { return $.when(null); }
1550         return $.when(facet_from(this, match));
1551     }
1552 });
1553 instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
1554     /**
1555      * @constructs instance.web.search.BooleanField
1556      * @extends instance.web.search.BooleanField
1557      */
1558     init: function () {
1559         this._super.apply(this, arguments);
1560         this.attrs.selection = [
1561             [true, _t("Yes")],
1562             [false, _t("No")]
1563         ];
1564     }
1565 });
1566 /**
1567  * @class
1568  * @extends instance.web.search.DateField
1569  */
1570 instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
1571     value_from: function (facetValue) {
1572         return instance.web.date_to_str(facetValue.get('value'));
1573     },
1574     complete: function (needle) {
1575         try {
1576             var d = instance.web.str_to_date(instance.web.parse_value(needle, {'widget': 'date'}));
1577         } catch (e) {
1578             return false;
1579         }
1580         if (!d) { return $.when(null); }
1581         var date_string = instance.web.format_value(d, this.attrs);
1582         var label = _.str.sprintf(_.str.escapeHTML(
1583             _t("Search %(field)s at: %(value)s")), {
1584                 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1585                 value: '<strong>' + date_string + '</strong>'});
1586         return $.when([{
1587             label: label,
1588             facet: {
1589                 category: this.attrs.string,
1590                 field: this,
1591                 values: [{label: date_string, value: d}]
1592             }
1593         }]);
1594     }
1595 });
1596 /**
1597  * Implementation of the ``datetime`` openerp field type:
1598  *
1599  * * Uses the same widget as the ``date`` field type (a simple date)
1600  *
1601  * * Builds a slighly more complex, it's a datetime range (includes time)
1602  *   spanning the whole day selected by the date widget
1603  *
1604  * @class
1605  * @extends instance.web.DateField
1606  */
1607 instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
1608     value_from: function (facetValue) {
1609         return instance.web.datetime_to_str(facetValue.get('value'));
1610     }
1611 });
1612 instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
1613     default_operator: {},
1614     init: function (view_section, field, parent) {
1615         this._super(view_section, field, parent);
1616         this.model = new instance.web.Model(this.attrs.relation);
1617     },
1618
1619     complete: function (value) {
1620         if (_.isEmpty(value)) { return $.when(null); }
1621         var label = _.str.sprintf(_.str.escapeHTML(
1622             _t("Search %(field)s for: %(value)s")), {
1623                 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1624                 value: '<strong>' + _.escape(value) + '</strong>'});
1625         return $.when([{
1626             label: label,
1627             facet: {
1628                 category: this.attrs.string,
1629                 field: this,
1630                 values: [{label: value, value: value, operator: 'ilike'}]
1631             },
1632             expand: this.expand.bind(this),
1633         }]);
1634     },
1635
1636     expand: function (needle) {
1637         var self = this;
1638         // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1639         var context = instance.web.pyeval.eval(
1640             'contexts', [this.view.dataset.get_context()]);
1641         return this.model.call('name_search', [], {
1642             name: needle,
1643             args: (typeof this.attrs.domain === 'string') ? [] : this.attrs.domain,
1644             limit: 8,
1645             context: context
1646         }).then(function (results) {
1647             if (_.isEmpty(results)) { return null; }
1648             return _(results).map(function (result) {
1649                 return {
1650                     label: _.escape(result[1]),
1651                     facet: facet_from(self, result)
1652                 };
1653             });
1654         });
1655     },
1656     facet_for: function (value) {
1657         var self = this;
1658         if (value instanceof Array) {
1659             if (value.length === 2 && _.isString(value[1])) {
1660                 return $.when(facet_from(this, value));
1661             }
1662             assert(value.length <= 1,
1663                    _t("M2O search fields do not currently handle multiple default values"));
1664             // there are many cases of {search_default_$m2ofield: [id]}, need
1665             // to handle this as if it were a single value.
1666             value = value[0];
1667         }
1668         return this.model.call('name_get', [value]).then(function (names) {
1669             if (_(names).isEmpty()) { return null; }
1670             return facet_from(self, names[0]);
1671         });
1672     },
1673     value_from: function (facetValue) {
1674         return facetValue.get('label');
1675     },
1676     make_domain: function (name, operator, facetValue) {
1677         operator = facetValue.get('operator') || operator;
1678
1679         switch(operator){
1680         case this.default_operator:
1681             return [[name, '=', facetValue.get('value')]];
1682         case 'ilike':
1683             return [[name, 'ilike', facetValue.get('value')]];
1684         case 'child_of':
1685             return [[name, 'child_of', facetValue.get('value')]];
1686         }
1687         return this._super(name, operator, facetValue);
1688     },
1689     get_context: function (facet) {
1690         var values = facet.values;
1691         if (_.isEmpty(this.attrs.context) && values.length === 1) {
1692             var c = {};
1693             c['default_' + this.attrs.name] = values.at(0).get('value');
1694             return c;
1695         }
1696         return this._super(facet);
1697     }
1698 });
1699
1700 instance.web.search.CustomFilters = instance.web.search.Input.extend({
1701     template: 'SearchView.Custom',
1702     _in_drawer: true,
1703     init: function () {
1704         this.is_ready = $.Deferred();
1705         this._super.apply(this,arguments);
1706     },
1707     start: function () {
1708         var self = this;
1709         this.model = new instance.web.Model('ir.filters');
1710         this.filters = {};
1711         this.$filters = {};
1712         this.view.query
1713             .on('remove', function (facet) {
1714                 if (!facet.get('is_custom_filter')) {
1715                     return;
1716                 }
1717                 self.clear_selection();
1718             })
1719             .on('reset', this.proxy('clear_selection'));
1720         return this.model.call('get_filters', [this.view.model, this.get_action_id()])
1721             .then(this.proxy('set_filters'))
1722             .done(function () { self.is_ready.resolve(); })
1723             .fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); });
1724     },
1725     get_action_id: function(){
1726         var action = instance.client.action_manager.inner_action;
1727         if (action) return action.id;
1728     },
1729     /**
1730      * Special implementation delaying defaults until CustomFilters is loaded
1731      */
1732     facet_for_defaults: function () {
1733         return this.is_ready;
1734     },
1735     /**
1736      * Generates a mapping key (in the filters and $filter mappings) for the
1737      * filter descriptor object provided (as returned by ``get_filters``).
1738      *
1739      * The mapping key is guaranteed to be unique for a given (user_id, name)
1740      * pair.
1741      *
1742      * @param {Object} filter
1743      * @param {String} filter.name
1744      * @param {Number|Pair<Number, String>} [filter.user_id]
1745      * @return {String} mapping key corresponding to the filter
1746      */
1747     key_for: function (filter) {
1748         var user_id = filter.user_id,
1749             action_id = filter.action_id;
1750         var uid = (user_id instanceof Array) ? user_id[0] : user_id;
1751         var act_id = (action_id instanceof Array) ? action_id[0] : action_id;
1752         return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
1753     },
1754     /**
1755      * Generates a :js:class:`~instance.web.search.Facet` descriptor from a
1756      * filter descriptor
1757      *
1758      * @param {Object} filter
1759      * @param {String} filter.name
1760      * @param {Object} [filter.context]
1761      * @param {Array} [filter.domain]
1762      * @return {Object}
1763      */
1764     facet_for: function (filter) {
1765         return {
1766             category: _t("Custom Filter"),
1767             icon: 'M',
1768             field: {
1769                 get_context: function () { return filter.context; },
1770                 get_groupby: function () { return [filter.context]; },
1771                 get_domain: function () { return filter.domain; }
1772             },
1773             _id: filter['id'],
1774             is_custom_filter: true,
1775             values: [{label: filter.name, value: null}]
1776         };
1777     },
1778     clear_selection: function () {
1779         this.$('span.badge').removeClass('badge');
1780     },
1781     append_filter: function (filter) {
1782         var self = this;
1783         var key = this.key_for(filter);
1784         var warning = _t("This filter is global and will be removed for everybody if you continue.");
1785
1786         var $filter;
1787         if (key in this.$filters) {
1788             $filter = this.$filters[key];
1789         } else {
1790             var id = filter.id;
1791             this.filters[key] = filter;
1792             $filter = $('<li></li>')
1793                 .appendTo(this.$('.oe_searchview_custom_list'))
1794                 .toggleClass('oe_searchview_custom_default', filter.is_default)
1795                 .append(this.$filters[key] = $('<span>').text(filter.name));
1796
1797             this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
1798                                          : 'oe_searchview_custom_public')
1799
1800             $('<a class="oe_searchview_custom_delete">x</a>')
1801                 .click(function (e) {
1802                     e.stopPropagation();
1803                     if (!(filter.user_id || confirm(warning))) {
1804                         return;
1805                     }
1806                     self.model.call('unlink', [id]).done(function () {
1807                         $filter.remove();
1808                         delete self.$filters[key];
1809                         delete self.filters[key];
1810                         if (_.isEmpty(self.filters)) {
1811                             self.hide();
1812                         }
1813                     });
1814                 })
1815                 .appendTo($filter);
1816         }
1817
1818         this.$filters[key].unbind('click').click(function () {
1819             self.toggle_filter(filter);
1820         });
1821         this.show();
1822     },
1823     toggle_filter: function (filter, preventSearch) {
1824         var current = this.view.query.find(function (facet) {
1825             return facet.get('_id') === filter.id;
1826         });
1827         if (current) {
1828             this.view.query.remove(current);
1829             this.$filters[this.key_for(filter)].removeClass('badge');
1830             return;
1831         }
1832         this.view.query.reset([this.facet_for(filter)], {
1833             preventSearch: preventSearch || false});
1834         this.$filters[this.key_for(filter)].addClass('badge');
1835     },
1836     set_filters: function (filters) {
1837         _(filters).map(_.bind(this.append_filter, this));
1838         if (!filters.length) {
1839             this.hide();
1840         }
1841     },
1842     hide: function () {
1843         this.$el.hide();
1844     },
1845     show: function () {
1846         this.$el.show();
1847     },
1848 });
1849
1850 instance.web.search.SaveFilter = instance.web.search.Input.extend({
1851     template: 'SearchView.SaveFilter',
1852     _in_drawer: true,
1853     init: function (parent, custom_filters) {
1854         this._super(parent);
1855         this.custom_filters = custom_filters;
1856     },
1857     start: function () {
1858         var self = this;
1859         this.model = new instance.web.Model('ir.filters');
1860         this.$el.on('submit', 'form', this.proxy('save_current'));
1861         this.$el.on('click', 'input[type=checkbox]', function() {
1862             $(this).siblings('input[type=checkbox]').prop('checked', false);
1863         });
1864         this.$el.on('click', 'h4', function () {
1865             self.$el.toggleClass('oe_opened');
1866         });
1867     },
1868     save_current: function () {
1869         var self = this;
1870         var $name = this.$('input:first');
1871         var private_filter = !this.$('#oe_searchview_custom_public').prop('checked');
1872         var set_as_default = this.$('#oe_searchview_custom_default').prop('checked');
1873         if (_.isEmpty($name.val())){
1874             this.do_warn(_t("Error"), _t("Filter name is required."));
1875             return false;
1876         }
1877         var search = this.view.build_search_data();
1878         instance.web.pyeval.eval_domains_and_contexts({
1879             domains: search.domains,
1880             contexts: search.contexts,
1881             group_by_seq: search.groupbys || []
1882         }).done(function (results) {
1883             if (!_.isEmpty(results.group_by)) {
1884                 results.context.group_by = results.group_by;
1885             }
1886             // Don't save user_context keys in the custom filter, otherwise end
1887             // up with e.g. wrong uid or lang stored *and used in subsequent
1888             // reqs*
1889             var ctx = results.context;
1890             _(_.keys(instance.session.user_context)).each(function (key) {
1891                 delete ctx[key];
1892             });
1893             var filter = {
1894                 name: $name.val(),
1895                 user_id: private_filter ? instance.session.uid : false,
1896                 model_id: self.view.model,
1897                 context: results.context,
1898                 domain: results.domain,
1899                 is_default: set_as_default,
1900                 action_id: self.custom_filters.get_action_id()
1901             };
1902             // FIXME: current context?
1903             return self.model.call('create_or_replace', [filter]).done(function (id) {
1904                 filter.id = id;
1905                 if (self.custom_filters) {
1906                     self.custom_filters.append_filter(filter);
1907                 }
1908                 self.$el
1909                     .removeClass('oe_opened')
1910                     .find('form')[0].reset();
1911             });
1912         });
1913         return false;
1914     },
1915 });
1916
1917 instance.web.search.Filters = instance.web.search.Input.extend({
1918     template: 'SearchView.Filters',
1919     _in_drawer: true,
1920     start: function () {
1921         var self = this;
1922         var is_group = function (i) { return i instanceof instance.web.search.FilterGroup; };
1923         var visible_filters = _(this.drawer.controls).chain().reject(function (group) {
1924             return _(_(group.children).filter(is_group)).isEmpty()
1925                 || group.modifiers.invisible;
1926         });
1927
1928         var groups = visible_filters.map(function (group) {
1929                 var filters = _(group.children).filter(is_group);
1930                 return {
1931                     name: _.str.sprintf("<span class='oe_i'>%s</span> %s",
1932                             group.icon, group.name),
1933                     filters: filters,
1934                     length: _(filters).chain().map(function (i) {
1935                         return i.filters.length; }).sum().value()
1936                 };
1937             }).value();
1938
1939         var $dl = $('<dl class="dl-horizontal">').appendTo(this.$el);
1940
1941         var rendered_lines = _.map(groups, function (group) {
1942             $('<dt>').html(group.name).appendTo($dl);
1943             var $dd = $('<dd>').appendTo($dl);
1944             return $.when.apply(null, _(group.filters).invoke('appendTo', $dd));
1945         });
1946
1947         return $.when.apply(this, rendered_lines);
1948     },
1949 });
1950
1951 instance.web.search.Advanced = instance.web.search.Input.extend({
1952     template: 'SearchView.advanced',
1953     _in_drawer: true,
1954     start: function () {
1955         var self = this;
1956         this.$el
1957             .on('keypress keydown keyup', function (e) { e.stopPropagation(); })
1958             .on('click', 'h4', function () {
1959                 self.$el.toggleClass('oe_opened');
1960             }).on('click', 'button.oe_add_condition', function () {
1961                 self.append_proposition();
1962             }).on('submit', 'form', function (e) {
1963                 e.preventDefault();
1964                 self.commit_search();
1965             });
1966         return $.when(
1967             this._super(),
1968             new instance.web.Model(this.view.model).call('fields_get', {
1969                     context: this.view.dataset.context
1970                 }).done(function(data) {
1971                     self.fields = {
1972                         id: { string: 'ID', type: 'id', searchable: true }
1973                     };
1974                     _.each(data, function(field_def, field_name) {
1975                         if (field_def.selectable !== false && field_name != 'id') {
1976                             self.fields[field_name] = field_def;
1977                         }
1978                     });
1979         })).done(function () {
1980             self.append_proposition();
1981         });
1982     },
1983     append_proposition: function () {
1984         var self = this;
1985         return (new instance.web.search.ExtendedSearchProposition(this, this.fields))
1986             .appendTo(this.$('ul')).done(function () {
1987                 self.$('button.oe_apply').prop('disabled', false);
1988             });
1989     },
1990     remove_proposition: function (prop) {
1991         // removing last proposition, disable apply button
1992         if (this.getChildren().length <= 1) {
1993             this.$('button.oe_apply').prop('disabled', true);
1994         }
1995         prop.destroy();
1996     },
1997     commit_search: function () {
1998         // Get domain sections from all propositions
1999         var children = this.getChildren();
2000         var propositions = _.invoke(children, 'get_proposition');
2001         var domain = _(propositions).pluck('value');
2002         for (var i = domain.length; --i;) {
2003             domain.unshift('|');
2004         }
2005
2006         this.view.query.add({
2007             category: _t("Advanced"),
2008             values: propositions,
2009             field: {
2010                 get_context: function () { },
2011                 get_domain: function () { return domain;},
2012                 get_groupby: function () { }
2013             }
2014         });
2015
2016         // remove all propositions
2017         _.invoke(children, 'destroy');
2018         // add new empty proposition
2019         this.append_proposition();
2020         // TODO: API on searchview
2021         this.view.$el.removeClass('oe_searchview_open_drawer');
2022     }
2023 });
2024
2025 instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
2026     template: 'SearchView.extended_search.proposition',
2027     events: {
2028         'change .searchview_extended_prop_field': 'changed',
2029         'change .searchview_extended_prop_op': 'operator_changed',
2030         'click .searchview_extended_delete_prop': function (e) {
2031             e.stopPropagation();
2032             this.getParent().remove_proposition(this);
2033         }
2034     },
2035     /**
2036      * @constructs instance.web.search.ExtendedSearchProposition
2037      * @extends instance.web.Widget
2038      *
2039      * @param parent
2040      * @param fields
2041      */
2042     init: function (parent, fields) {
2043         this._super(parent);
2044         this.fields = _(fields).chain()
2045             .map(function(val, key) { return _.extend({}, val, {'name': key}); })
2046             .filter(function (field) { return !field.deprecated && field.searchable; })
2047             .sortBy(function(field) {return field.string;})
2048             .value();
2049         this.attrs = {_: _, fields: this.fields, selected: null};
2050         this.value = null;
2051     },
2052     start: function () {
2053         return this._super().done(this.proxy('changed'));
2054     },
2055     changed: function() {
2056         var nval = this.$(".searchview_extended_prop_field").val();
2057         if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
2058             this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
2059         }
2060     },
2061     operator_changed: function (e) {
2062         var $value = this.$('.searchview_extended_prop_value');
2063         switch ($(e.target).val()) {
2064         case '∃':
2065         case '∄':
2066             $value.hide();
2067             break;
2068         default:
2069             $value.show();
2070         }
2071     },
2072     /**
2073      * Selects the provided field object
2074      *
2075      * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
2076      */
2077     select_field: function(field) {
2078         var self = this;
2079         if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
2080             this.value.destroy();
2081             this.value = null;
2082             this.$('.searchview_extended_prop_op').html('');
2083         }
2084         this.attrs.selected = field;
2085         if(field === null || field === undefined) {
2086             return;
2087         }
2088
2089         var type = field.type;
2090         var Field = instance.web.search.custom_filters.get_object(type);
2091         if(!Field) {
2092             Field = instance.web.search.custom_filters.get_object("char");
2093         }
2094         this.value = new Field(this, field);
2095         _.each(this.value.operators, function(operator) {
2096             $('<option>', {value: operator.value})
2097                 .text(String(operator.text))
2098                 .appendTo(self.$('.searchview_extended_prop_op'));
2099         });
2100         var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
2101         this.value.appendTo($value_loc);
2102
2103     },
2104     get_proposition: function() {
2105         if (this.attrs.selected === null || this.attrs.selected === undefined)
2106             return null;
2107         var field = this.attrs.selected;
2108         var op_select = this.$('.searchview_extended_prop_op')[0];
2109         var operator = op_select.options[op_select.selectedIndex];
2110
2111         return {
2112             label: this.value.get_label(field, operator),
2113             value: this.value.get_domain(field, operator),
2114         };
2115     }
2116 });
2117
2118 instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
2119     init: function (parent, field) {
2120         this._super(parent);
2121         this.field = field;
2122     },
2123     get_label: function (field, operator) {
2124         var format;
2125         switch (operator.value) {
2126         case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
2127         default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
2128         }
2129         return this.format_label(format, field, operator);
2130     },
2131     format_label: function (format, field, operator) {
2132         return _.str.sprintf(format, {
2133             field: field.string,
2134             // According to spec, HTMLOptionElement#label should return
2135             // HTMLOptionElement#text when not defined/empty, but it does
2136             // not in older Webkit (between Safari 5.1.5 and Chrome 17) and
2137             // Gecko (pre Firefox 7) browsers, so we need a manual fallback
2138             // for those
2139             operator: operator.label || operator.text,
2140             value: this
2141         });
2142     },
2143     get_domain: function (field, operator) {
2144         switch (operator.value) {
2145         case '∃': return this.make_domain(field.name, '!=', false);
2146         case '∄': return this.make_domain(field.name, '=', false);
2147         default: return this.make_domain(
2148             field.name, operator.value, this.get_value());
2149         }
2150     },
2151     make_domain: function (field, operator, value) {
2152         return [field, operator, value];
2153     },
2154     /**
2155      * Returns a human-readable version of the value, in case the "logical"
2156      * and the "semantic" values of a field differ (as for selection fields,
2157      * for instance).
2158      *
2159      * The default implementation simply returns the value itself.
2160      *
2161      * @return {String} human-readable version of the value
2162      */
2163     toString: function () {
2164         return this.get_value();
2165     }
2166 });
2167 instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
2168     template: 'SearchView.extended_search.proposition.char',
2169     operators: [
2170         {value: "ilike", text: _lt("contains")},
2171         {value: "not ilike", text: _lt("doesn't contain")},
2172         {value: "=", text: _lt("is equal to")},
2173         {value: "!=", text: _lt("is not equal to")},
2174         {value: "∃", text: _lt("is set")},
2175         {value: "∄", text: _lt("is not set")}
2176     ],
2177     get_value: function() {
2178         return this.$el.val();
2179     }
2180 });
2181 instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
2182     template: 'SearchView.extended_search.proposition.empty',
2183     operators: [
2184         {value: "=", text: _lt("is equal to")},
2185         {value: "!=", text: _lt("is not equal to")},
2186         {value: ">", text: _lt("greater than")},
2187         {value: "<", text: _lt("less than")},
2188         {value: ">=", text: _lt("greater or equal than")},
2189         {value: "<=", text: _lt("less or equal than")},
2190         {value: "∃", text: _lt("is set")},
2191         {value: "∄", text: _lt("is not set")}
2192     ],
2193     /**
2194      * Date widgets live in view_form which is not yet loaded when this is
2195      * initialized -_-
2196      */
2197     widget: function () { return instance.web.DateTimeWidget; },
2198     get_value: function() {
2199         return this.datewidget.get_value();
2200     },
2201     toString: function () {
2202         return instance.web.format_value(this.get_value(), { type:"datetime" });
2203     },
2204     start: function() {
2205         var ready = this._super();
2206         this.datewidget = new (this.widget())(this);
2207         this.datewidget.appendTo(this.$el);
2208         return ready;
2209     }
2210 });
2211 instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
2212     widget: function () { return instance.web.DateWidget; },
2213     toString: function () {
2214         return instance.web.format_value(this.get_value(), { type:"date" });
2215     }
2216 });
2217 instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
2218     template: 'SearchView.extended_search.proposition.integer',
2219     operators: [
2220         {value: "=", text: _lt("is equal to")},
2221         {value: "!=", text: _lt("is not equal to")},
2222         {value: ">", text: _lt("greater than")},
2223         {value: "<", text: _lt("less than")},
2224         {value: ">=", text: _lt("greater or equal than")},
2225         {value: "<=", text: _lt("less or equal than")},
2226         {value: "∃", text: _lt("is set")},
2227         {value: "∄", text: _lt("is not set")}
2228     ],
2229     toString: function () {
2230         return this.$el.val();
2231     },
2232     get_value: function() {
2233         try {
2234             var val =this.$el.val();
2235             return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
2236         } catch (e) {
2237             return "";
2238         }
2239     }
2240 });
2241 instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
2242     operators: [{value: "=", text: _lt("is")}]
2243 });
2244 instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
2245     template: 'SearchView.extended_search.proposition.float',
2246     operators: [
2247         {value: "=", text: _lt("is equal to")},
2248         {value: "!=", text: _lt("is not equal to")},
2249         {value: ">", text: _lt("greater than")},
2250         {value: "<", text: _lt("less than")},
2251         {value: ">=", text: _lt("greater or equal than")},
2252         {value: "<=", text: _lt("less or equal than")},
2253         {value: "∃", text: _lt("is set")},
2254         {value: "∄", text: _lt("is not set")}
2255     ],
2256     toString: function () {
2257         return this.$el.val();
2258     },
2259     get_value: function() {
2260         try {
2261             var val =this.$el.val();
2262             return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
2263         } catch (e) {
2264             return "";
2265         }
2266     }
2267 });
2268 instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
2269     template: 'SearchView.extended_search.proposition.selection',
2270     operators: [
2271         {value: "=", text: _lt("is")},
2272         {value: "!=", text: _lt("is not")},
2273         {value: "∃", text: _lt("is set")},
2274         {value: "∄", text: _lt("is not set")}
2275     ],
2276     toString: function () {
2277         var select = this.$el[0];
2278         var option = select.options[select.selectedIndex];
2279         return option.label || option.text;
2280     },
2281     get_value: function() {
2282         return this.$el.val();
2283     }
2284 });
2285 instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
2286     template: 'SearchView.extended_search.proposition.empty',
2287     operators: [
2288         {value: "=", text: _lt("is true")},
2289         {value: "!=", text: _lt("is false")}
2290     ],
2291     get_label: function (field, operator) {
2292         return this.format_label(
2293             _t('%(field)s %(operator)s'), field, operator);
2294     },
2295     get_value: function() {
2296         return true;
2297     }
2298 });
2299
2300 instance.web.search.custom_filters = new instance.web.Registry({
2301     'char': 'instance.web.search.ExtendedSearchProposition.Char',
2302     'text': 'instance.web.search.ExtendedSearchProposition.Char',
2303     'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
2304     'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
2305     'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
2306
2307     'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
2308     'date': 'instance.web.search.ExtendedSearchProposition.Date',
2309     'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
2310     'float': 'instance.web.search.ExtendedSearchProposition.Float',
2311     'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
2312     'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
2313
2314     'id': 'instance.web.search.ExtendedSearchProposition.Id'
2315 });
2316
2317 instance.web.search.AutoComplete = instance.web.Widget.extend({
2318     template: "SearchView.autocomplete",
2319
2320     // Parameters for autocomplete constructor:
2321     //
2322     // parent: this is used to detect keyboard events
2323     //
2324     // options.source: function ({term:query}, callback).  This function will be called to
2325     //      obtain the search results corresponding to the query string.  It is assumed that
2326     //      options.source will call callback with the results.
2327     // options.delay: delay in millisecond before calling source.  Useful if you don't want
2328     //      to make too many rpc calls
2329     // options.select: function (ev, {item: {facet:facet}}).  Autocomplete widget will call
2330     //      that function when a selection is made by the user
2331     // options.get_search_string: function ().  This function will be called by autocomplete
2332     //      to obtain the current search string.
2333     init: function (parent, options) {
2334         this._super(parent);
2335         this.$input = parent.$el;
2336         this.source = options.source;
2337         this.delay = options.delay;
2338         this.select = options.select,
2339         this.get_search_string = options.get_search_string;
2340         this.width = options.width || 400;
2341
2342         this.current_result = null;
2343
2344         this.searching = true;
2345         this.search_string = null;
2346         this.current_search = null;
2347     },
2348     start: function () {
2349         var self = this;
2350         this.$el.width(this.width);
2351         this.$input.on('keyup', function (ev) {
2352             if (ev.which === $.ui.keyCode.RIGHT) {
2353                 self.searching = true;
2354                 ev.preventDefault();
2355                 return;
2356             }
2357             if (!self.searching) {
2358                 self.searching = true;
2359                 return;
2360             }
2361             self.search_string = self.get_search_string();
2362             if (self.search_string.length) {
2363                 var search_string = self.search_string;
2364                 setTimeout(function () { self.initiate_search(search_string);}, self.delay);
2365             } else {
2366                 self.close();
2367             }
2368         });
2369         this.$input.on('keydown', function (ev) {
2370             switch (ev.which) {
2371                 case $.ui.keyCode.TAB:
2372                 case $.ui.keyCode.ENTER:
2373                     if (self.current_result && self.get_search_string().length) {
2374                         self.select_item(ev);
2375                     }
2376                     break;
2377                 case $.ui.keyCode.DOWN:
2378                     self.move('down');
2379                     self.searching = false;
2380                     ev.preventDefault();
2381                     break;
2382                 case $.ui.keyCode.UP:
2383                     self.move('up');
2384                     self.searching = false;
2385                     ev.preventDefault();
2386                     break;
2387                 case $.ui.keyCode.RIGHT:
2388                     self.searching = false;
2389                     var current = self.current_result
2390                     if (current && current.expand && !current.expanded) {
2391                         self.expand();
2392                         self.searching = true;
2393                     }
2394                     ev.preventDefault();
2395                     break;
2396                 case $.ui.keyCode.ESCAPE:
2397                     self.close();
2398                     self.searching = false;
2399                     break;
2400             }
2401         });
2402     },
2403     initiate_search: function (query) {
2404         if (query === this.search_string && query !== this.current_search) {
2405             this.search(query);
2406         }
2407     },
2408     search: function (query) {
2409         var self = this;
2410         this.current_search = query;
2411         this.source({term:query}, function (results) {
2412             if (results.length) {
2413                 self.render_search_results(results);
2414                 self.focus_element(self.$('li:first-child'));
2415             } else {
2416                 self.close();
2417             }
2418         });
2419     },
2420     render_search_results: function (results) {
2421         var self = this;
2422         var $list = this.$('ul');
2423         $list.empty();
2424         var render_separator = false;
2425         results.forEach(function (result) {
2426             if (result.is_separator) {
2427                 if (render_separator)
2428                     $list.append($('<li>').addClass('oe-separator'));
2429                 render_separator = false;
2430             } else {
2431                 var $item = self.make_list_item(result).appendTo($list);
2432                 result.$el = $item;
2433                 render_separator = true;
2434             }
2435         });
2436         this.show();
2437     },
2438     make_list_item: function (result) {
2439         var self = this;
2440         var $li = $('<li>')
2441             .hover(function (ev) {self.focus_element($li);})
2442             .mousedown(function (ev) {
2443                 if (ev.button === 0) { // left button
2444                     self.select(ev, {item: {facet: result.facet}});
2445                     self.close();
2446                 } else {
2447                     ev.preventDefault();
2448                 }
2449             })
2450             .data('result', result);
2451         if (result.expand) {
2452             var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
2453             $expand.mousedown(function (ev) {
2454                 ev.preventDefault();
2455                 ev.stopPropagation();
2456                 if (result.expanded)
2457                     self.fold();
2458                 else
2459                     self.expand();
2460             });
2461             result.expanded = false;
2462         }
2463         if (result.indent) $li.addClass('oe-indent');
2464         $li.append($('<span>').html(result.label));
2465         return $li;
2466     },
2467     expand: function () {
2468         var self = this;
2469         this.current_result.expand(this.get_search_string()).then(function (results) {
2470             (results || [{label: '(no result)'}]).reverse().forEach(function (result) {
2471                 result.indent = true;
2472                 var $li = self.make_list_item(result);
2473                 self.current_result.$el.after($li);
2474             });
2475             self.current_result.expanded = true;
2476             self.current_result.$el.find('span.oe-expand').html('▼');
2477         });
2478     },
2479     fold: function () {
2480         var $next = this.current_result.$el.next();
2481         while ($next.hasClass('oe-indent')) {
2482             $next.remove();
2483             $next = this.current_result.$el.next();
2484         }
2485         this.current_result.expanded = false;
2486         this.current_result.$el.find('span.oe-expand').html('▶');
2487     },
2488     focus_element: function ($li) {
2489         this.$('li').removeClass('oe-selection-focus');
2490         $li.addClass('oe-selection-focus');
2491         this.current_result = $li.data('result');
2492     },
2493     select_item: function (ev) {
2494         if (this.current_result.facet) {
2495             this.select(ev, {item: {facet: this.current_result.facet}});
2496             this.close();
2497         }
2498     },
2499     show: function () {
2500         this.$el.show();
2501     },
2502     close: function () {
2503         this.current_search = null;
2504         this.search_string = null;
2505         this.searching = true;
2506         this.$el.hide();
2507     },
2508     move: function (direction) {
2509         var $next;
2510         if (direction === 'down') {
2511             $next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
2512             if (!$next.length) $next = this.$('li:first-child');
2513         } else {
2514             $next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
2515             if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
2516         }
2517         this.focus_element($next);
2518     },
2519     is_expandable: function () {
2520         return !!this.$('.oe-selection-focus .oe-expand').length;
2521     },
2522 });
2523
2524 })();
2525
2526 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: