Home | History | Annotate | Download | only in quicksearchbox
      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 
     17 package com.android.quicksearchbox;
     18 
     19 import com.google.common.annotations.VisibleForTesting;
     20 import 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  */
     27 public class ShortcutPromoter extends AbstractPromoter {
     28 
     29     public ShortcutPromoter(Config config, Promoter next, SuggestionFilter filter) {
     30         super(filter, next, config);
     31     }
     32 
     33     @Override
     34     public void doPickPromoted(Suggestions suggestions, int maxPromoted,
     35             ListSuggestionCursor promoted) {
     36         promoteShortcuts(suggestions.getShortcuts(), maxPromoted, promoted);
     37     }
     38 
     39     @VisibleForTesting
     40     void promoteShortcuts(SuggestionCursor shortcuts, int maxPromoted,
     41             ListSuggestionCursor promoted) {
     42         int shortcutCount = shortcuts == null ? 0 : shortcuts.getCount();
     43         if (shortcutCount == 0) return;
     44         HashMultiset<Source> sourceShortcutCounts = HashMultiset.create(shortcutCount);
     45         for (int i = 0; i < shortcutCount && promoted.getCount() < maxPromoted; i++) {
     46             shortcuts.moveTo(i);
     47             Source source = shortcuts.getSuggestionSource();
     48             if (source != null && accept(shortcuts)) {
     49                 int prevCount = sourceShortcutCounts.add(source, 1);
     50                 int maxShortcuts = source.getMaxShortcuts(getConfig());
     51                 if (prevCount < maxShortcuts) {
     52                     promoted.add(new SuggestionPosition(shortcuts));
     53                 }
     54             }
     55         }
     56     }
     57 
     58 }
     59