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 package com.android.quicksearchbox;
     17 
     18 import java.util.HashSet;
     19 import java.util.Set;
     20 
     21 /**
     22  * Promotes shortcuts and suggestions from a single corpus.
     23  */
     24 public class SingleCorpusPromoter implements Promoter {
     25 
     26     private final Corpus mCorpus;
     27 
     28     private final int mMaxShortcuts;
     29 
     30     private final Set<String> mAllowedSources;
     31 
     32     public SingleCorpusPromoter(Corpus corpus, int maxShortcuts) {
     33         mCorpus = corpus;
     34         mMaxShortcuts = maxShortcuts;
     35         mAllowedSources = new HashSet<String>();
     36         for (Source source : corpus.getSources()) {
     37             mAllowedSources.add(source.getName());
     38         }
     39     }
     40 
     41     public void pickPromoted(Suggestions suggestions, int maxPromoted,
     42             ListSuggestionCursor promoted) {
     43         // Add shortcuts
     44         SuggestionCursor shortcuts = suggestions.getShortcuts();
     45         promoteUntilFull(shortcuts, mMaxShortcuts, promoted);
     46         // Add suggestions
     47         CorpusResult corpusResult = suggestions.getCorpusResult(mCorpus);
     48         promoteUntilFull(corpusResult, maxPromoted, promoted);
     49     }
     50 
     51     private void promoteUntilFull(SuggestionCursor c, int maxSize, ListSuggestionCursor promoted) {
     52         if (c == null) return;
     53         int count = c.getCount();
     54         for (int i = 0; i < count && promoted.getCount() < maxSize; i++) {
     55             c.moveTo(i);
     56             if (accept(c)) {
     57                 promoted.add(new SuggestionPosition(c, i));
     58             }
     59         }
     60     }
     61 
     62     protected boolean accept(Suggestion s) {
     63         return mAllowedSources.contains(s.getSuggestionSource().getName());
     64     }
     65 
     66 }
     67