DefaultCorpusRanker.java revision ce4cdcf739b57563ddcdbed6944128b8c1f7522a
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 android.util.Log; 20 21import java.util.ArrayList; 22import java.util.Collection; 23import java.util.Collections; 24import java.util.Comparator; 25import java.util.List; 26import java.util.Map; 27 28public class DefaultCorpusRanker extends AbstractCorpusRanker { 29 30 private static final boolean DBG = true; 31 private static final String TAG = "QSB.DefaultCorpusRanker"; 32 33 private final ShortcutRepository mShortcuts; 34 35 public DefaultCorpusRanker(Corpora corpora, ShortcutRepository shortcuts) { 36 super(corpora); 37 mShortcuts = shortcuts; 38 } 39 40 private static class CorpusComparator implements Comparator<Corpus> { 41 private final Corpora mCorpora; 42 private final Map<String,Integer> mClickScores; 43 44 public CorpusComparator(Corpora corpora, Map<String,Integer> clickScores) { 45 mCorpora = corpora; 46 mClickScores = clickScores; 47 } 48 49 public int compare(Corpus corpus1, Corpus corpus2) { 50 // Note that this is reversed from the usual order 51 return getCorpusScore(corpus2) - getCorpusScore(corpus1); 52 } 53 54 /** 55 * Scores a corpus. Higher score is better. 56 */ 57 private int getCorpusScore(Corpus corpus) { 58 // Web corpus always comes first 59 if (corpus.isWebCorpus()) { 60 return Integer.MAX_VALUE; 61 } 62 // Then use click score 63 Integer clickScore = mClickScores.get(corpus.getName()); 64 if (clickScore != null) { 65 return clickScore; 66 } 67 // Boost default enabled corpora that don't have click scores 68 if (mCorpora.isCorpusDefaultEnabled(corpus)) { 69 return 1; 70 } 71 return 0; 72 } 73 } 74 75 @Override 76 public List<Corpus> rankCorpora(Corpora corpora) { 77 Collection<Corpus> enabledCorpora = corpora.getEnabledCorpora(); 78 if (DBG) Log.d(TAG, "Ranking: " + enabledCorpora); 79 80 Map<String,Integer> clickScores = mShortcuts.getCorpusScores(); 81 ArrayList<Corpus> ordered = new ArrayList<Corpus>(enabledCorpora); 82 Collections.sort(ordered, new CorpusComparator(corpora, clickScores)); 83 84 if (DBG) Log.d(TAG, "Click scores: " + clickScores); 85 if (DBG) Log.d(TAG, "Ordered: " + ordered); 86 return ordered; 87 } 88 89} 90