ShortcutPromoter.java revision b83882b9efa37ec0f20a0f1c85cf5ccc93194aee
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.quicksearchbox;
18
19import com.google.common.annotations.VisibleForTesting;
20import com.google.common.collect.HashMultiset;
21
22/**
23 * A promoter limits the maximum number of shortcuts per source
24 * (from non-web sources) and blends results
25 * from multiple sources.
26 */
27public class BlendingPromoter extends RankAwarePromoter {
28
29    public BlendingPromoter(Config config) {
30        super(config);
31    }
32
33    @Override
34    public void pickPromoted(Suggestions suggestions, int maxPromoted,
35            ListSuggestionCursor promoted) {
36        promoteShortcuts(suggestions.getShortcuts(), maxPromoted, promoted);
37
38        super.pickPromoted(suggestions, maxPromoted, promoted);
39    }
40
41    @VisibleForTesting
42    void promoteShortcuts(SuggestionCursor shortcuts, int maxPromoted,
43            ListSuggestionCursor promoted) {
44        int shortcutCount = shortcuts == null ? 0 : shortcuts.getCount();
45        if (shortcutCount == 0) return;
46        int maxShortcutsPerWebSource = getConfig().getMaxShortcutsPerWebSource();
47        int maxShortcutsPerNonWebSource = getConfig().getMaxShortcutsPerNonWebSource();
48        HashMultiset<Source> sourceShortcutCounts = HashMultiset.create(shortcutCount);
49        for (int i = 0; i < shortcutCount && promoted.getCount() < maxPromoted; i++) {
50            shortcuts.moveTo(i);
51            Source source = shortcuts.getSuggestionSource();
52            if (source != null && accept(shortcuts)) {
53                int prevCount = sourceShortcutCounts.add(source, 1);
54                int maxShortcuts = source.isWebSuggestionSource()
55                        ? maxShortcutsPerWebSource : maxShortcutsPerNonWebSource;
56                if (prevCount < maxShortcuts) {
57                    promoted.add(new SuggestionPosition(shortcuts));
58                }
59            }
60        }
61    }
62
63}
64