Refactoring to prepare for external shortcuts

This change is meant to have no user-visible effects

Change-Id: Idf3a6d892ba84307a887785725aa072bd28c59b6
diff --git a/src/com/android/quicksearchbox/AbstractSuggestionCursor.java b/src/com/android/quicksearchbox/AbstractSuggestionCursor.java
index c00a3c8..7e66aef 100644
--- a/src/com/android/quicksearchbox/AbstractSuggestionCursor.java
+++ b/src/com/android/quicksearchbox/AbstractSuggestionCursor.java
@@ -16,6 +16,11 @@
 
 package com.android.quicksearchbox;
 
+import android.app.SearchManager;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+
 
 /**
  * Base class for suggestion cursors.
@@ -32,6 +37,46 @@
         return mUserQuery;
     }
 
+    public Intent getSuggestionIntent(Bundle appSearchData) {
+        Source source = getSuggestionSource();
+        String action = getSuggestionIntentAction();
+        // use specific action if supplied, or default action if supplied, or fixed default
+        if (action == null) {
+            action = source.getDefaultIntentAction();
+            if (action == null) {
+                action = Intent.ACTION_SEARCH;
+            }
+        }
+
+        String data = getSuggestionIntentDataString();
+        String query = getSuggestionQuery();
+        String userQuery = getUserQuery();
+        String extraData = getSuggestionIntentExtraData();
+
+        // Now build the Intent
+        Intent intent = new Intent(action);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        // We need CLEAR_TOP to avoid reusing an old task that has other activities
+        // on top of the one we want.
+        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
+        if (data != null) {
+            intent.setData(Uri.parse(data));
+        }
+        intent.putExtra(SearchManager.USER_QUERY, userQuery);
+        if (query != null) {
+            intent.putExtra(SearchManager.QUERY, query);
+        }
+        if (extraData != null) {
+            intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
+        }
+        if (appSearchData != null) {
+            intent.putExtra(SearchManager.APP_DATA, appSearchData);
+        }
+
+        intent.setComponent(source.getIntentComponent());
+        return intent;
+    }
+
     public String getSuggestionDisplayQuery() {
         String query = getSuggestionQuery();
         if (query != null) {
diff --git a/src/com/android/quicksearchbox/Launcher.java b/src/com/android/quicksearchbox/Launcher.java
deleted file mode 100644
index 0f90da8..0000000
--- a/src/com/android/quicksearchbox/Launcher.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.quicksearchbox;
-
-import android.app.SearchManager;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.net.Uri;
-import android.os.Bundle;
-import android.speech.RecognizerIntent;
-import android.util.Log;
-
-/**
- * Launches suggestions and searches.
- *
- */
-public class Launcher {
-
-    private static final String TAG = "Launcher";
-
-    private final Context mContext;
-
-    /**
-     * Data sent by the app that launched QSB.
-     */
-    public Launcher(Context context) {
-        mContext = context;
-    }
-
-    /**
-     * Gets the corpus to use for any searches. This is the web corpus in "All" mode,
-     * and the selected corpus otherwise.
-     */
-    public Corpus getSearchCorpus(Corpora corpora, Corpus selectedCorpus) {
-        if (selectedCorpus != null) {
-            return selectedCorpus;
-        } else {
-            Corpus webCorpus = corpora.getWebCorpus();
-            if (webCorpus == null) {
-                Log.e(TAG, "No web corpus");
-            }
-            return webCorpus;
-        }
-    }
-
-    public boolean shouldShowVoiceSearch(Corpus corpus) {
-        if (corpus != null && !corpus.voiceSearchEnabled()) {
-            return false;
-        }
-        return isVoiceSearchAvailable();
-    }
-
-    private boolean isVoiceSearchAvailable() {
-        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
-        ResolveInfo ri = mContext.getPackageManager().
-                resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
-        return ri != null;
-    }
-
-    public Intent getSuggestionIntent(SuggestionCursor cursor, int position,
-            Bundle appSearchData) {
-        cursor.moveTo(position);
-        Source source = cursor.getSuggestionSource();
-        String action = cursor.getSuggestionIntentAction();
-        // use specific action if supplied, or default action if supplied, or fixed default
-        if (action == null) {
-            action = source.getDefaultIntentAction();
-            if (action == null) {
-                action = Intent.ACTION_SEARCH;
-            }
-        }
-
-        String data = cursor.getSuggestionIntentDataString();
-        String query = cursor.getSuggestionQuery();
-        String userQuery = cursor.getUserQuery();
-        String extraData = cursor.getSuggestionIntentExtraData();
-
-        // Now build the Intent
-        Intent intent = new Intent(action);
-        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        // We need CLEAR_TOP to avoid reusing an old task that has other activities
-        // on top of the one we want.
-        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        if (data != null) {
-            intent.setData(Uri.parse(data));
-        }
-        intent.putExtra(SearchManager.USER_QUERY, userQuery);
-        if (query != null) {
-            intent.putExtra(SearchManager.QUERY, query);
-        }
-        if (extraData != null) {
-            intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
-        }
-        if (appSearchData != null) {
-            intent.putExtra(SearchManager.APP_DATA, appSearchData);
-        }
-
-        intent.setComponent(cursor.getSuggestionSource().getComponentName());
-        return intent;
-    }
-
-    public void launchIntent(Intent intent) {
-        if (intent == null) {
-            return;
-        }
-        try {
-            mContext.startActivity(intent);
-        } catch (RuntimeException ex) {
-            // Since the intents for suggestions specified by suggestion providers,
-            // guard against them not being handled, not allowed, etc.
-            Log.e(TAG, "Failed to start " + intent.toUri(0), ex);
-        }
-    }
-
-}
diff --git a/src/com/android/quicksearchbox/QsbApplication.java b/src/com/android/quicksearchbox/QsbApplication.java
index d565d14..7d41989 100644
--- a/src/com/android/quicksearchbox/QsbApplication.java
+++ b/src/com/android/quicksearchbox/QsbApplication.java
@@ -99,6 +99,10 @@
         return mUiThreadHandler;
     }
 
+    public void runOnUiThread(Runnable action) {
+        getMainThreadHandler().post(action);
+    }
+
     /**
      * Gets the QSB configuration object.
      * May be called from any thread.
@@ -262,6 +266,7 @@
                 promoter,
                 getShortcutRepository(),
                 getCorpora(),
+                getCorpusRanker(),
                 getLogger());
         return provider;
     }
diff --git a/src/com/android/quicksearchbox/SearchActivity.java b/src/com/android/quicksearchbox/SearchActivity.java
index 96f2f4b..7f22694 100644
--- a/src/com/android/quicksearchbox/SearchActivity.java
+++ b/src/com/android/quicksearchbox/SearchActivity.java
@@ -49,7 +49,6 @@
 
 import java.io.File;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.List;
 
 /**
@@ -99,7 +98,7 @@
     protected ImageButton mVoiceSearchButton;
     protected ImageButton mCorpusIndicator;
 
-    private Launcher mLauncher;
+    private VoiceSearch mVoiceSearch;
 
     private Corpus mCorpus;
     private Bundle mAppSearchData;
@@ -148,7 +147,7 @@
         mVoiceSearchButton = (ImageButton) findViewById(R.id.search_voice_btn);
         mCorpusIndicator = (ImageButton) findViewById(R.id.corpus_indicator);
 
-        mLauncher = new Launcher(this);
+        mVoiceSearch = new VoiceSearch(this);
 
         mQueryTextView.addTextChangedListener(new SearchTextWatcher());
         mQueryTextView.setOnKeyListener(new QueryTextViewKeyListener());
@@ -455,7 +454,7 @@
     }
 
     protected void updateVoiceSearchButton(boolean queryEmpty) {
-        if (queryEmpty && mLauncher.shouldShowVoiceSearch(mCorpus)) {
+        if (queryEmpty && mVoiceSearch.shouldShowVoiceSearch(mCorpus)) {
             mVoiceSearchButton.setVisibility(View.VISIBLE);
             mQueryTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE);
         } else {
@@ -494,7 +493,7 @@
         // Don't do empty queries
         if (TextUtils.getTrimmedLength(query) == 0) return false;
 
-        Corpus searchCorpus = mLauncher.getSearchCorpus(getCorpora(), mCorpus);
+        Corpus searchCorpus = getSearchCorpus();
         if (searchCorpus == null) return false;
 
         mTookAction = true;
@@ -512,13 +511,13 @@
 
         // Start search
         Intent intent = searchCorpus.createSearchIntent(query, mAppSearchData);
-        mLauncher.launchIntent(intent);
+        launchIntent(intent);
         return true;
     }
 
     protected void onVoiceSearchClicked() {
         if (DBG) Log.d(TAG, "Voice Search clicked");
-        Corpus searchCorpus = mLauncher.getSearchCorpus(getCorpora(), mCorpus);
+        Corpus searchCorpus = getSearchCorpus();
         if (searchCorpus == null) return;
 
         mTookAction = true;
@@ -528,13 +527,42 @@
 
         // Start voice search
         Intent intent = searchCorpus.createVoiceSearchIntent(mAppSearchData);
-        mLauncher.launchIntent(intent);
+        launchIntent(intent);
+    }
+
+    /**
+     * Gets the corpus to use for any searches. This is the web corpus in "All" mode,
+     * and the selected corpus otherwise.
+     */
+    private Corpus getSearchCorpus() {
+        if (mCorpus != null) {
+            return mCorpus;
+        } else {
+            Corpus webCorpus = getCorpora().getWebCorpus();
+            if (webCorpus == null) {
+                Log.e(TAG, "No web corpus");
+            }
+            return webCorpus;
+        }
     }
 
     protected SuggestionCursor getCurrentSuggestions() {
         return mSuggestionsAdapter.getCurrentSuggestions();
     }
 
+    protected void launchIntent(Intent intent) {
+        if (intent == null) {
+            return;
+        }
+        try {
+            startActivity(intent);
+        } catch (RuntimeException ex) {
+            // Since the intents for suggestions specified by suggestion providers,
+            // guard against them not being handled, not allowed, etc.
+            Log.e(TAG, "Failed to start " + intent.toUri(0), ex);
+        }
+    }
+
     protected boolean launchSuggestion(int position) {
         SuggestionCursor suggestions = getCurrentSuggestions();
         if (position < 0 || position >= suggestions.getCount()) {
@@ -553,8 +581,9 @@
         getShortcutRepository().reportClick(suggestions, position);
 
         // Launch intent
-        Intent intent = mLauncher.getSuggestionIntent(suggestions, position, mAppSearchData);
-        mLauncher.launchIntent(intent);
+        suggestions.moveTo(position);
+        Intent intent = suggestions.getSuggestionIntent(mAppSearchData);
+        launchIntent(intent);
 
         return true;
     }
@@ -642,14 +671,6 @@
         }
     }
 
-    private List<Corpus> getCorporaToQuery() {
-        if (mCorpus == null) {
-            return getCorpusRanker().getRankedCorpora();
-        } else {
-            return Collections.singletonList(mCorpus);
-        }
-    }
-
     private int getMaxSuggestions() {
         Config config = getConfig();
         return mCorpus == null
@@ -674,9 +695,8 @@
         }
 
         query = ltrim(query);
-        List<Corpus> corporaToQuery = getCorporaToQuery();
         Suggestions suggestions = getSuggestionsProvider().getSuggestions(
-                query, corporaToQuery, getMaxSuggestions());
+                query, mCorpus, getMaxSuggestions());
         mSuggestionsAdapter.setSuggestions(suggestions);
     }
 
diff --git a/src/com/android/quicksearchbox/SearchWidgetProvider.java b/src/com/android/quicksearchbox/SearchWidgetProvider.java
index 34d69cb..9a0e62c 100644
--- a/src/com/android/quicksearchbox/SearchWidgetProvider.java
+++ b/src/com/android/quicksearchbox/SearchWidgetProvider.java
@@ -186,10 +186,10 @@
 
     private static Intent getVoiceSearchIntent(Context context, Corpus corpus,
             Bundle widgetAppData) {
-        Launcher launcher = new Launcher(context);
-        if (!launcher.shouldShowVoiceSearch(corpus)) return null;
+        VoiceSearch voiceSearch = new VoiceSearch(context);
+        if (!voiceSearch.shouldShowVoiceSearch(corpus)) return null;
         if (corpus == null) {
-            return WebCorpus.createVoiceWebSearchIntent(widgetAppData);
+            return voiceSearch.createVoiceWebSearchIntent(widgetAppData);
         } else {
             return corpus.createVoiceSearchIntent(widgetAppData);
         }
diff --git a/src/com/android/quicksearchbox/SearchableCorpora.java b/src/com/android/quicksearchbox/SearchableCorpora.java
index 4a38d81..582a0c1 100644
--- a/src/com/android/quicksearchbox/SearchableCorpora.java
+++ b/src/com/android/quicksearchbox/SearchableCorpora.java
@@ -20,6 +20,7 @@
 import android.content.SharedPreferences;
 import android.database.DataSetObservable;
 import android.database.DataSetObserver;
+import android.text.TextUtils;
 import android.util.Log;
 
 import java.util.ArrayList;
@@ -105,6 +106,10 @@
 
     public Source getSource(String name) {
         checkLoaded();
+        if (TextUtils.isEmpty(name)) {
+            Log.w(TAG, "Empty source name");
+            return null;
+        }
         return mSources.getSource(name);
     }
 
diff --git a/src/com/android/quicksearchbox/SearchableCorpusFactory.java b/src/com/android/quicksearchbox/SearchableCorpusFactory.java
index 45a1831..97446b4 100644
--- a/src/com/android/quicksearchbox/SearchableCorpusFactory.java
+++ b/src/com/android/quicksearchbox/SearchableCorpusFactory.java
@@ -19,6 +19,7 @@
 import com.android.quicksearchbox.util.Factory;
 
 import android.content.Context;
+import android.util.Log;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -30,6 +31,8 @@
  */
 public class SearchableCorpusFactory implements CorpusFactory {
 
+    private static final String TAG = "QSB.SearchableCorpusFactory";
+
     private final Context mContext;
 
     private final Factory<Executor> mWebCorpusExecutorFactory;
@@ -61,8 +64,10 @@
      * @param sources All available sources.
      */
     protected void addSpecialCorpora(ArrayList<Corpus> corpora, Sources sources) {
-        corpora.add(createWebCorpus(sources));
-        corpora.add(createAppsCorpus(sources));
+        Corpus webCorpus = createWebCorpus(sources);
+        if (webCorpus != null) corpora.add(webCorpus);
+        Corpus appsCorpus = createAppsCorpus(sources);
+        if (appsCorpus != null) corpora.add(appsCorpus);
     }
 
     /**
@@ -82,14 +87,23 @@
         // Creates corpora for all unclaimed sources
         for (Source source : sources.getSources()) {
             if (!claimedSources.contains(source)) {
-                corpora.add(createSingleSourceCorpus(source));
+                Corpus corpus = createSingleSourceCorpus(source);
+                if (corpus != null) corpora.add(corpus);
             }
         }
     }
 
     protected Corpus createWebCorpus(Sources sources) {
         Source webSource = sources.getWebSearchSource();
+        if (webSource != null && !webSource.canRead()) {
+            Log.w(TAG, "Can't read web source " + webSource.getName());
+            webSource = null;
+        }
         Source browserSource = getBrowserSource(sources);
+        if (browserSource != null && !browserSource.canRead()) {
+            Log.w(TAG, "Can't read browser source " + browserSource.getName());
+            browserSource = null;
+        }
         Executor executor = createWebCorpusExecutor();
         return new WebCorpus(mContext, executor, webSource, browserSource);
     }
@@ -100,6 +114,7 @@
     }
 
     protected Corpus createSingleSourceCorpus(Source source) {
+        if (!source.canRead()) return null;
         return new SingleSourceCorpus(mContext, source);
     }
 
diff --git a/src/com/android/quicksearchbox/SearchableSource.java b/src/com/android/quicksearchbox/SearchableSource.java
index a5c8e96..aa00c21 100644
--- a/src/com/android/quicksearchbox/SearchableSource.java
+++ b/src/com/android/quicksearchbox/SearchableSource.java
@@ -69,7 +69,7 @@
     // Cached icon for the activity
     private Drawable.ConstantState mSourceIcon = null;
 
-    private final IconLoader mIconLoader;
+    private IconLoader mIconLoader;
 
     public SearchableSource(Context context, SearchableInfo searchable)
             throws NameNotFoundException {
@@ -81,7 +81,6 @@
         mActivityInfo = pm.getActivityInfo(componentName, 0);
         PackageInfo pkgInfo = pm.getPackageInfo(componentName.getPackageName(), 0);
         mVersionCode = pkgInfo.versionCode;
-        mIconLoader = createIconLoader(context, searchable.getSuggestPackage());
     }
 
     protected Context getContext() {
@@ -98,8 +97,9 @@
     public boolean canRead() {
         String authority = mSearchable.getSuggestAuthority();
         if (authority == null) {
-            Log.w(TAG, getName() + " has no searchSuggestAuthority");
-            return false;
+            // TODO: maybe we should have a way to distinguish between having suggestions
+            // and being readable.
+            return true;
         }
 
         Uri.Builder uriBuilder = new Uri.Builder()
@@ -161,12 +161,20 @@
         return false;
     }
 
-    private IconLoader createIconLoader(Context context, String providerPackage) {
-        if (providerPackage == null) return null;
-        return new CachingIconLoader(new PackageIconLoader(context, providerPackage));
+    private IconLoader getIconLoader() {
+        if (mIconLoader == null) {
+            // Get icons from the package containing the suggestion provider, if any
+            String iconPackage = mSearchable.getSuggestPackage();
+            if (iconPackage == null) {
+                // Fall back to the package containing the searchable activity
+                iconPackage = mSearchable.getSearchActivity().getPackageName();
+            }
+            mIconLoader = new CachingIconLoader(new PackageIconLoader(mContext, iconPackage));
+        }
+        return mIconLoader;
     }
 
-    public ComponentName getComponentName() {
+    public ComponentName getIntentComponent() {
         return mSearchable.getSearchActivity();
     }
 
@@ -179,11 +187,11 @@
     }
 
     public Drawable getIcon(String drawableId) {
-        return mIconLoader == null ? null : mIconLoader.getIcon(drawableId);
+        return getIconLoader().getIcon(drawableId);
     }
 
     public Uri getIconUri(String drawableId) {
-        return mIconLoader == null ? null : mIconLoader.getIconUri(drawableId);
+        return getIconLoader().getIconUri(drawableId);
     }
 
     public CharSequence getLabel() {
@@ -236,7 +244,7 @@
     }
 
     public Intent createSearchIntent(String query, Bundle appData) {
-        return createSourceSearchIntent(getComponentName(), query, appData);
+        return createSourceSearchIntent(getIntentComponent(), query, appData);
     }
 
     public static Intent createSourceSearchIntent(ComponentName activity, String query,
@@ -261,7 +269,7 @@
 
     public Intent createVoiceSearchIntent(Bundle appData) {
         if (mSearchable.getVoiceSearchLaunchWebSearch()) {
-            return WebCorpus.createVoiceWebSearchIntent(appData);
+            return new VoiceSearch(mContext).createVoiceWebSearchIntent(appData);
         } else if (mSearchable.getVoiceSearchLaunchRecognizer()) {
             return createVoiceAppSearchIntent(appData);
         }
diff --git a/src/com/android/quicksearchbox/SearchableSources.java b/src/com/android/quicksearchbox/SearchableSources.java
index a8f0e62..5c611e5 100644
--- a/src/com/android/quicksearchbox/SearchableSources.java
+++ b/src/com/android/quicksearchbox/SearchableSources.java
@@ -164,7 +164,7 @@
         }
         for (SearchableInfo searchable : searchables) {
             SearchableSource source = createSearchableSource(searchable);
-            if (source != null && source.canRead()) {
+            if (source != null) {
                 if (DBG) Log.d(TAG, "Created source " + source);
                 addSource(source);
             }
diff --git a/src/com/android/quicksearchbox/ShortcutRepository.java b/src/com/android/quicksearchbox/ShortcutRepository.java
index fbbe155..bfc24ef 100644
--- a/src/com/android/quicksearchbox/ShortcutRepository.java
+++ b/src/com/android/quicksearchbox/ShortcutRepository.java
@@ -16,7 +16,7 @@
 
 package com.android.quicksearchbox;
 
-import java.util.List;
+import java.util.Collection;
 import java.util.Map;
 
 /**
@@ -54,7 +54,7 @@
      * @param maxShortcuts The maximum number of shortcuts to return.
      * @return A cursor containing shortcutted results for the query.
      */
-    SuggestionCursor getShortcutsForQuery(String query, List<Corpus> allowedCorpora,
+    SuggestionCursor getShortcutsForQuery(String query, Collection<Corpus> allowedCorpora,
             int maxShortcuts);
 
     /**
diff --git a/src/com/android/quicksearchbox/ShortcutRepositoryImplLog.java b/src/com/android/quicksearchbox/ShortcutRepositoryImplLog.java
index ea8150c..1331afb 100644
--- a/src/com/android/quicksearchbox/ShortcutRepositoryImplLog.java
+++ b/src/com/android/quicksearchbox/ShortcutRepositoryImplLog.java
@@ -34,8 +34,8 @@
 import android.util.Log;
 
 import java.io.File;
+import java.util.Collection;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Executor;
 
@@ -223,7 +223,7 @@
         reportClickAtTime(suggestions, position, now);
     }
 
-    public SuggestionCursor getShortcutsForQuery(String query, List<Corpus> allowedCorpora,
+    public SuggestionCursor getShortcutsForQuery(String query, Collection<Corpus> allowedCorpora,
             int maxShortcuts) {
         ShortcutCursor shortcuts = getShortcutsForQuery(query, allowedCorpora, maxShortcuts,
                         System.currentTimeMillis());
@@ -245,7 +245,7 @@
     }
 
     /* package for testing */ ShortcutCursor getShortcutsForQuery(String query,
-            List<Corpus> allowedCorpora, int maxShortcuts, long now) {
+            Collection<Corpus> allowedCorpora, int maxShortcuts, long now) {
         if (DBG) Log.d(TAG, "getShortcutsForQuery(" + query + "," + allowedCorpora + ")");
         String sql = query.length() == 0 ? mEmptyQueryShortcutQuery : mShortcutQuery;
         String[] params = buildShortcutQueryParams(query, now);
diff --git a/src/com/android/quicksearchbox/Source.java b/src/com/android/quicksearchbox/Source.java
index 04cab39..f32ca15 100644
--- a/src/com/android/quicksearchbox/Source.java
+++ b/src/com/android/quicksearchbox/Source.java
@@ -29,10 +29,9 @@
 public interface Source extends SuggestionCursorProvider<SourceResult> {
 
     /**
-     * Gets the name of the activity that this source is for. When a suggestion is
-     * clicked, the resulting intent will be sent to this activity.
+     * Gets the name activity that intents from this source are sent to.
      */
-    ComponentName getComponentName();
+    ComponentName getIntentComponent();
 
     /**
      * Gets the version code of the source. This is expected to change when the app that
@@ -107,6 +106,11 @@
     Intent createVoiceSearchIntent(Bundle appData);
 
     /**
+     * Checks if the current process can read the suggestions from this source.
+     */
+    boolean canRead();
+
+    /**
      * Gets suggestions from this source.
      *
      * @param query The user query.
@@ -126,11 +130,6 @@
     SuggestionCursor refreshShortcut(String shortcutId, String extraData);
 
     /**
-     * Checks whether this is a web suggestion source.
-     */
-    boolean isWebSuggestionSource();
-
-    /**
      * Checks whether the text in the query field should come from the suggestion intent data.
      */
     boolean shouldRewriteQueryFromData();
diff --git a/src/com/android/quicksearchbox/SuggestionCursor.java b/src/com/android/quicksearchbox/SuggestionCursor.java
index bef015c..23ab5b2 100644
--- a/src/com/android/quicksearchbox/SuggestionCursor.java
+++ b/src/com/android/quicksearchbox/SuggestionCursor.java
@@ -16,7 +16,9 @@
 
 package com.android.quicksearchbox;
 
+import android.content.Intent;
 import android.database.DataSetObserver;
+import android.os.Bundle;
 
 
 /**
@@ -148,6 +150,11 @@
      */
     String getSuggestionQuery();
 
+    /**
+     * Gets the intent launched by this suggestion.
+     */
+    Intent getSuggestionIntent(Bundle appSearchData);
+
     String getSuggestionDisplayQuery();
 
     /**
diff --git a/src/com/android/quicksearchbox/SuggestionsProvider.java b/src/com/android/quicksearchbox/SuggestionsProvider.java
index b7ac4b9..3070a10 100644
--- a/src/com/android/quicksearchbox/SuggestionsProvider.java
+++ b/src/com/android/quicksearchbox/SuggestionsProvider.java
@@ -16,7 +16,6 @@
 
 package com.android.quicksearchbox;
 
-import java.util.List;
 
 /**
  * Provides a set of suggestion results for a query..
@@ -27,10 +26,10 @@
      * Gets suggestions for a query.
      *
      * @param query The query.
-     * @param corpora The corpora to query.
+     * @param singleCorpus The corpora to query, {@code null} for all enabled corpora.
      * @param maxSuggestions The maximum number of suggestions to return.
      */
-    Suggestions getSuggestions(String query, List<Corpus> corpora, int maxSuggestions);
+    Suggestions getSuggestions(String query, Corpus singleCorpus, int maxSuggestions);
 
     void close();
 }
diff --git a/src/com/android/quicksearchbox/SuggestionsProviderImpl.java b/src/com/android/quicksearchbox/SuggestionsProviderImpl.java
index a492df4..2c7b493 100644
--- a/src/com/android/quicksearchbox/SuggestionsProviderImpl.java
+++ b/src/com/android/quicksearchbox/SuggestionsProviderImpl.java
@@ -24,6 +24,8 @@
 import android.util.Log;
 
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -47,12 +49,14 @@
 
     private final ShortcutRepository mShortcutRepo;
 
-    private final Logger mLogger;
-
     private final ShouldQueryStrategy mShouldQueryStrategy = new ShouldQueryStrategy();
 
     private final Corpora mCorpora;
 
+    private final CorpusRanker mCorpusRanker;
+
+    private final Logger mLogger;
+
     private BatchingNamedTaskExecutor mBatchingExecutor;
 
     public SuggestionsProviderImpl(Config config,
@@ -61,14 +65,16 @@
             Promoter promoter,
             ShortcutRepository shortcutRepo,
             Corpora corpora,
+            CorpusRanker corpusRanker,
             Logger logger) {
         mConfig = config;
         mQueryExecutor = queryExecutor;
         mPublishThread = publishThread;
         mPromoter = promoter;
         mShortcutRepo = shortcutRepo;
-        mLogger = logger;
         mCorpora = corpora;
+        mCorpusRanker = corpusRanker;
+        mLogger = logger;
     }
 
     public void close() {
@@ -85,16 +91,19 @@
         }
     }
 
-    protected SuggestionCursor getShortcutsForQuery(String query, List<Corpus> corpora,
+    protected SuggestionCursor getShortcutsForQuery(String query, Corpus singleCorpus,
             int maxShortcuts) {
         if (mShortcutRepo == null) return null;
-        return mShortcutRepo.getShortcutsForQuery(query, corpora, maxShortcuts);
+        Collection<Corpus> allowedCorpora = mCorpora.getEnabledCorpora();
+        return mShortcutRepo.getShortcutsForQuery(query, allowedCorpora, maxShortcuts);
     }
 
     /**
      * Gets the sources that should be queried for the given query.
      */
-    private List<Corpus> getCorporaToQuery(String query, List<Corpus> orderedCorpora) {
+    private List<Corpus> getCorporaToQuery(String query, Corpus singleCorpus) {
+        if (singleCorpus != null) return Collections.singletonList(singleCorpus);
+        List<Corpus> orderedCorpora = mCorpusRanker.getRankedCorpora();
         ArrayList<Corpus> corporaToQuery = new ArrayList<Corpus>(orderedCorpora.size());
         for (Corpus corpus : orderedCorpora) {
             if (shouldQueryCorpus(corpus, query)) {
@@ -119,16 +128,16 @@
         }
     }
 
-    public Suggestions getSuggestions(String query, List<Corpus> corpora, int maxSuggestions) {
+    public Suggestions getSuggestions(String query, Corpus singleCorpus, int maxSuggestions) {
         if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
         cancelPendingTasks();
-        List<Corpus> corporaToQuery = getCorporaToQuery(query, corpora);
+        List<Corpus> corporaToQuery = getCorporaToQuery(query, singleCorpus);
         final Suggestions suggestions = new Suggestions(mPromoter,
                 maxSuggestions,
                 query,
                 corporaToQuery.size());
         int maxShortcuts = mConfig.getMaxShortcutsReturned();
-        SuggestionCursor shortcuts = getShortcutsForQuery(query, corpora, maxShortcuts);
+        SuggestionCursor shortcuts = getShortcutsForQuery(query, singleCorpus, maxShortcuts);
         if (shortcuts != null) {
             suggestions.setShortcuts(shortcuts);
         }
diff --git a/src/com/android/quicksearchbox/VoiceSearch.java b/src/com/android/quicksearchbox/VoiceSearch.java
new file mode 100644
index 0000000..acc5860
--- /dev/null
+++ b/src/com/android/quicksearchbox/VoiceSearch.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.quicksearchbox;
+
+import android.app.SearchManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.Bundle;
+import android.speech.RecognizerIntent;
+
+/**
+ * Voice Search integration.
+ */
+public class VoiceSearch {
+
+    private final Context mContext;
+
+    public VoiceSearch(Context context) {
+        mContext = context;
+    }
+
+    public boolean shouldShowVoiceSearch(Corpus corpus) {
+        if (corpus != null && !corpus.voiceSearchEnabled()) {
+            return false;
+        }
+        return isVoiceSearchAvailable();
+    }
+
+    private boolean isVoiceSearchAvailable() {
+        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
+        ResolveInfo ri = mContext.getPackageManager().
+                resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
+        return ri != null;
+    }
+
+    public Intent createVoiceWebSearchIntent(Bundle appData) {
+        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
+                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
+        if (appData != null) {
+            intent.putExtra(SearchManager.APP_DATA, appData);
+        }
+        return intent;
+    }
+
+}
diff --git a/src/com/android/quicksearchbox/WebCorpus.java b/src/com/android/quicksearchbox/WebCorpus.java
index 84306bb..67f533f 100644
--- a/src/com/android/quicksearchbox/WebCorpus.java
+++ b/src/com/android/quicksearchbox/WebCorpus.java
@@ -25,7 +25,6 @@
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
 import android.os.Bundle;
-import android.speech.RecognizerIntent;
 import android.util.Patterns;
 import android.webkit.URLUtil;
 
@@ -114,18 +113,7 @@
     }
 
     public Intent createVoiceSearchIntent(Bundle appData) {
-        return createVoiceWebSearchIntent(appData);
-    }
-
-    public static Intent createVoiceWebSearchIntent(Bundle appData) {
-        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
-        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
-                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
-        if (appData != null) {
-            intent.putExtra(SearchManager.APP_DATA, appData);
-        }
-        return intent;
+        return new VoiceSearch(getContext()).createVoiceWebSearchIntent(appData);
     }
 
     private int getCorpusIconResource() {
diff --git a/tests/src/com/android/quicksearchbox/MockShortcutRepository.java b/tests/src/com/android/quicksearchbox/MockShortcutRepository.java
index ab7ea38..73c2223 100644
--- a/tests/src/com/android/quicksearchbox/MockShortcutRepository.java
+++ b/tests/src/com/android/quicksearchbox/MockShortcutRepository.java
@@ -16,7 +16,7 @@
 
 package com.android.quicksearchbox;
 
-import java.util.List;
+import java.util.Collection;
 import java.util.Map;
 
 /**
@@ -31,7 +31,7 @@
     public void close() {
     }
 
-    public SuggestionCursor getShortcutsForQuery(String query, List<Corpus> corporaToQuery,
+    public SuggestionCursor getShortcutsForQuery(String query, Collection<Corpus> corporaToQuery,
             int maxShortcuts) {
         // TODO: should look at corporaToQuery
         DataSuggestionCursor cursor = new DataSuggestionCursor(query);
diff --git a/tests/src/com/android/quicksearchbox/MockSource.java b/tests/src/com/android/quicksearchbox/MockSource.java
index f07471c..2b5ff46 100644
--- a/tests/src/com/android/quicksearchbox/MockSource.java
+++ b/tests/src/com/android/quicksearchbox/MockSource.java
@@ -47,7 +47,7 @@
         mVersionCode = versionCode;
     }
 
-    public ComponentName getComponentName() {
+    public ComponentName getIntentComponent() {
         // Not an activity, but no code should treat it as one.
         return new ComponentName("com.android.quicksearchbox",
                 getClass().getName() + "." + mName);
@@ -58,7 +58,7 @@
     }
 
     public String getName() {
-        return getComponentName().flattenToShortString();
+        return getIntentComponent().flattenToShortString();
     }
 
     public String getDefaultIntentAction() {
@@ -101,6 +101,10 @@
         return null;
     }
 
+    public boolean canRead() {
+        return true;
+    }
+
     public SourceResult getSuggestions(String query, int queryLimit) {
         if (query.length() == 0) {
             return null;
@@ -155,6 +159,10 @@
         return null;
     }
 
+    public boolean isExternal() {
+        return false;
+    }
+
     public boolean isWebSuggestionSource() {
         return false;
     }
diff --git a/tests/src/com/android/quicksearchbox/ShortcutPromoterTest.java b/tests/src/com/android/quicksearchbox/ShortcutPromoterTest.java
index 2107e8b..3ae4efa 100644
--- a/tests/src/com/android/quicksearchbox/ShortcutPromoterTest.java
+++ b/tests/src/com/android/quicksearchbox/ShortcutPromoterTest.java
@@ -42,7 +42,7 @@
     protected void setUp() throws Exception {
         mQuery = "foo";
         List<Corpus> corpora = Arrays.asList(MockCorpus.CORPUS_1, MockCorpus.CORPUS_2);
-        mShortcuts = new MockShortcutRepository().getShortcutsForQuery(mQuery, corpora, 8);
+        mShortcuts = new MockShortcutRepository().getShortcutsForQuery(mQuery, null, 8);
         mSuggestions = new ArrayList<CorpusResult>();
         for (Corpus corpus : corpora) {
             mSuggestions.add(corpus.getSuggestions(mQuery, 10));
diff --git a/tests/src/com/android/quicksearchbox/ShortcutRepositoryTest.java b/tests/src/com/android/quicksearchbox/ShortcutRepositoryTest.java
index b41997c..7874552 100644
--- a/tests/src/com/android/quicksearchbox/ShortcutRepositoryTest.java
+++ b/tests/src/com/android/quicksearchbox/ShortcutRepositoryTest.java
@@ -27,6 +27,7 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
@@ -803,7 +804,7 @@
         }
     }
 
-    void assertShortcuts(String message, String query, List<Corpus> allowedCorpora,
+    void assertShortcuts(String message, String query, Collection<Corpus> allowedCorpora,
             SuggestionCursor expected) {
         SuggestionCursor cursor = mRepo.getShortcutsForQuery(query, allowedCorpora,
                 mConfig.getMaxShortcutsReturned(), NOW);
@@ -814,7 +815,7 @@
         }
     }
 
-    void assertShortcuts(String message, String query, List<Corpus> allowedCorpora,
+    void assertShortcuts(String message, String query, Collection<Corpus> allowedCorpora,
             SuggestionData... expected) {
         assertShortcuts(message, query, allowedCorpora, new DataSuggestionCursor(query, expected));
     }