summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRyan O'Leary <ryanaoleary@google.com>2022-09-08 18:58:11 +0000
committerGerrit Code Review <noreply-gerritcodereview@google.com>2022-09-08 18:58:11 +0000
commit176b988ec55cc6206053e6fbd6c5d8d68a16efa9 (patch)
tree81121a827ed4174c2edfa572ccb342ad0132362d
parentbc62ad4f2cc43e3b28553f849e2181e1d64688df (diff)
parent5ed44ae31836c21fa36d568d94e6cc96d1b8403b (diff)
downloadQuickSearchBox-176b988ec55cc6206053e6fbd6c5d8d68a16efa9.tar.gz
Merge "Delete .java files"
-rw-r--r--src/com/android/quicksearchbox/AbstractInternalSource.java77
-rw-r--r--src/com/android/quicksearchbox/AbstractSource.java133
-rw-r--r--src/com/android/quicksearchbox/AbstractSuggestionCursorWrapper.java33
-rw-r--r--src/com/android/quicksearchbox/AbstractSuggestionExtras.java59
-rw-r--r--src/com/android/quicksearchbox/AbstractSuggestionWrapper.java106
-rw-r--r--src/com/android/quicksearchbox/CachingIconLoader.java140
-rw-r--r--src/com/android/quicksearchbox/Config.java299
-rw-r--r--src/com/android/quicksearchbox/CursorBackedSourceResult.java77
-rw-r--r--src/com/android/quicksearchbox/CursorBackedSuggestionCursor.java301
-rw-r--r--src/com/android/quicksearchbox/CursorBackedSuggestionExtras.java111
-rw-r--r--src/com/android/quicksearchbox/DialogActivity.java69
-rw-r--r--src/com/android/quicksearchbox/EventLogLogger.java111
-rw-r--r--src/com/android/quicksearchbox/Help.java61
-rw-r--r--src/com/android/quicksearchbox/IconLoader.java56
-rw-r--r--src/com/android/quicksearchbox/JsonBackedSuggestionExtras.java80
-rw-r--r--src/com/android/quicksearchbox/LatencyTracker.java55
-rw-r--r--src/com/android/quicksearchbox/LevenshteinSuggestionFormatter.java127
-rw-r--r--src/com/android/quicksearchbox/ListSuggestionCursor.java180
-rw-r--r--src/com/android/quicksearchbox/ListSuggestionCursorNoDuplicates.java50
-rw-r--r--src/com/android/quicksearchbox/Logger.java78
-rw-r--r--src/com/android/quicksearchbox/PackageIconLoader.java261
-rw-r--r--src/com/android/quicksearchbox/QsbApplication.java364
-rw-r--r--src/com/android/quicksearchbox/QsbApplicationWrapper.java46
-rw-r--r--src/com/android/quicksearchbox/QueryTask.java86
-rw-r--r--src/com/android/quicksearchbox/ResultFilter.java30
-rw-r--r--src/com/android/quicksearchbox/SearchActivity.java510
-rw-r--r--src/com/android/quicksearchbox/SearchSettings.java55
-rw-r--r--src/com/android/quicksearchbox/SearchSettingsImpl.java212
-rw-r--r--src/com/android/quicksearchbox/SearchWidgetProvider.java187
-rw-r--r--src/com/android/quicksearchbox/Source.java149
-rw-r--r--src/com/android/quicksearchbox/SourceResult.java26
-rw-r--r--src/com/android/quicksearchbox/Suggestion.java129
-rw-r--r--src/com/android/quicksearchbox/SuggestionCursor.java86
-rw-r--r--src/com/android/quicksearchbox/SuggestionCursorBackedCursor.java200
-rw-r--r--src/com/android/quicksearchbox/SuggestionCursorProvider.java39
-rw-r--r--src/com/android/quicksearchbox/SuggestionCursorWrapper.java84
-rw-r--r--src/com/android/quicksearchbox/SuggestionData.java346
-rw-r--r--src/com/android/quicksearchbox/SuggestionExtras.java42
-rw-r--r--src/com/android/quicksearchbox/SuggestionFilter.java29
-rw-r--r--src/com/android/quicksearchbox/SuggestionFormatter.java58
-rw-r--r--src/com/android/quicksearchbox/SuggestionNonFormatter.java34
-rw-r--r--src/com/android/quicksearchbox/SuggestionPosition.java61
-rw-r--r--src/com/android/quicksearchbox/SuggestionUtils.java122
-rw-r--r--src/com/android/quicksearchbox/Suggestions.java193
-rw-r--r--src/com/android/quicksearchbox/SuggestionsProvider.java34
-rw-r--r--src/com/android/quicksearchbox/SuggestionsProviderImpl.java115
-rw-r--r--src/com/android/quicksearchbox/TextAppearanceFactory.java44
-rw-r--r--src/com/android/quicksearchbox/VoiceSearch.java106
-rw-r--r--src/com/android/quicksearchbox/google/AbstractGoogleSource.java124
-rw-r--r--src/com/android/quicksearchbox/google/AbstractGoogleSourceResult.java153
-rw-r--r--src/com/android/quicksearchbox/google/GoogleSearch.java169
-rw-r--r--src/com/android/quicksearchbox/google/GoogleSource.java39
-rw-r--r--src/com/android/quicksearchbox/google/GoogleSuggestClient.java218
-rw-r--r--src/com/android/quicksearchbox/google/GoogleSuggestionProvider.java136
-rw-r--r--src/com/android/quicksearchbox/google/SearchBaseUrlHelper.java176
-rw-r--r--src/com/android/quicksearchbox/ui/BaseSuggestionView.java116
-rw-r--r--src/com/android/quicksearchbox/ui/ClusteredSuggestionsView.java70
-rw-r--r--src/com/android/quicksearchbox/ui/ContactBadge.java56
-rw-r--r--src/com/android/quicksearchbox/ui/CorpusView.java95
-rw-r--r--src/com/android/quicksearchbox/ui/DefaultSuggestionView.java254
-rw-r--r--src/com/android/quicksearchbox/ui/DefaultSuggestionViewFactory.java89
-rw-r--r--src/com/android/quicksearchbox/ui/DelayingSuggestionsAdapter.java172
-rw-r--r--src/com/android/quicksearchbox/ui/QueryTextView.java104
-rw-r--r--src/com/android/quicksearchbox/ui/SearchActivityView.java563
-rw-r--r--src/com/android/quicksearchbox/ui/SearchActivityViewSinglePane.java59
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionClickListener.java41
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionView.java38
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionViewFactory.java63
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionViewInflater.java83
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionsAdapter.java86
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionsAdapterBase.java250
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionsListAdapter.java101
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionsListView.java61
-rw-r--r--src/com/android/quicksearchbox/ui/SuggestionsView.java76
-rw-r--r--src/com/android/quicksearchbox/ui/WebSearchSuggestionView.java102
-rw-r--r--src/com/android/quicksearchbox/util/AsyncDataSetObservable.java66
-rw-r--r--src/com/android/quicksearchbox/util/BarrierConsumer.java94
-rw-r--r--src/com/android/quicksearchbox/util/BatchingNamedTaskExecutor.java93
-rw-r--r--src/com/android/quicksearchbox/util/CachedLater.java139
-rw-r--r--src/com/android/quicksearchbox/util/Consumer.java34
-rw-r--r--src/com/android/quicksearchbox/util/Consumers.java84
-rw-r--r--src/com/android/quicksearchbox/util/Factory.java23
-rw-r--r--src/com/android/quicksearchbox/util/HttpHelper.java152
-rw-r--r--src/com/android/quicksearchbox/util/JavaNetHttpHelper.java187
-rw-r--r--src/com/android/quicksearchbox/util/LevenshteinDistance.java194
-rw-r--r--src/com/android/quicksearchbox/util/NamedTask.java26
-rw-r--r--src/com/android/quicksearchbox/util/NamedTaskExecutor.java44
-rw-r--r--src/com/android/quicksearchbox/util/NoOpConsumer.java30
-rw-r--r--src/com/android/quicksearchbox/util/Now.java41
-rw-r--r--src/com/android/quicksearchbox/util/NowOrLater.java43
-rw-r--r--src/com/android/quicksearchbox/util/NowOrLaterWrapper.java51
-rw-r--r--src/com/android/quicksearchbox/util/PerNameExecutor.java64
-rw-r--r--src/com/android/quicksearchbox/util/PriorityThreadFactory.java50
-rw-r--r--src/com/android/quicksearchbox/util/QuietlyCloseable.java28
-rw-r--r--src/com/android/quicksearchbox/util/SQLiteAsyncQuery.java43
-rw-r--r--src/com/android/quicksearchbox/util/SQLiteTransaction.java48
-rw-r--r--src/com/android/quicksearchbox/util/SingleThreadNamedTaskExecutor.java102
-rw-r--r--src/com/android/quicksearchbox/util/Util.java90
98 files changed, 0 insertions, 11071 deletions
diff --git a/src/com/android/quicksearchbox/AbstractInternalSource.java b/src/com/android/quicksearchbox/AbstractInternalSource.java
deleted file mode 100644
index 5567452..0000000
--- a/src/com/android/quicksearchbox/AbstractInternalSource.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 com.android.quicksearchbox.util.NamedTaskExecutor;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Handler;
-
-/**
- * Abstract implementation of a source that is not backed by a searchable activity.
- */
-public abstract class AbstractInternalSource extends AbstractSource {
-
- public AbstractInternalSource(Context context, Handler uiThread, NamedTaskExecutor iconLoader) {
- super(context, uiThread, iconLoader);
- }
-
- @Override
- public String getSuggestUri() {
- return null;
- }
-
- @Override
- public boolean canRead() {
- return true;
- }
-
- @Override
- public String getDefaultIntentData() {
- return null;
- }
-
- @Override
- protected String getIconPackage() {
- return getContext().getPackageName();
- }
-
- @Override
- public int getQueryThreshold() {
- return 0;
- }
-
- @Override
- public Drawable getSourceIcon() {
- return getContext().getResources().getDrawable(getSourceIconResource());
- }
-
- @Override
- public Uri getSourceIconUri() {
- return Uri.parse("android.resource://" + getContext().getPackageName()
- + "/" + getSourceIconResource());
- }
-
- protected abstract int getSourceIconResource();
-
- @Override
- public boolean queryAfterZeroResults() {
- return true;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/AbstractSource.java b/src/com/android/quicksearchbox/AbstractSource.java
deleted file mode 100644
index f8c6d0c..0000000
--- a/src/com/android/quicksearchbox/AbstractSource.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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 com.android.quicksearchbox.util.NamedTaskExecutor;
-import com.android.quicksearchbox.util.NowOrLater;
-
-import android.app.SearchManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Handler;
-import android.util.Log;
-
-/**
- * Abstract suggestion source implementation.
- */
-public abstract class AbstractSource implements Source {
-
- private static final String TAG = "QSB.AbstractSource";
-
- private final Context mContext;
- private final Handler mUiThread;
-
- private IconLoader mIconLoader;
-
- private final NamedTaskExecutor mIconLoaderExecutor;
-
- public AbstractSource(Context context, Handler uiThread, NamedTaskExecutor iconLoader) {
- mContext = context;
- mUiThread = uiThread;
- mIconLoaderExecutor = iconLoader;
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- protected IconLoader getIconLoader() {
- if (mIconLoader == null) {
- String iconPackage = getIconPackage();
- mIconLoader = new CachingIconLoader(
- new PackageIconLoader(mContext, iconPackage, mUiThread, mIconLoaderExecutor));
- }
- return mIconLoader;
- }
-
- protected abstract String getIconPackage();
-
- @Override
- public NowOrLater<Drawable> getIcon(String drawableId) {
- return getIconLoader().getIcon(drawableId);
- }
-
- @Override
- public Uri getIconUri(String drawableId) {
- return getIconLoader().getIconUri(drawableId);
- }
-
- @Override
- public Intent createSearchIntent(String query, Bundle appData) {
- return createSourceSearchIntent(getIntentComponent(), query, appData);
- }
-
- public static Intent createSourceSearchIntent(ComponentName activity, String query,
- Bundle appData) {
- if (activity == null) {
- Log.w(TAG, "Tried to create search intent with no target activity");
- return null;
- }
- Intent intent = new Intent(Intent.ACTION_SEARCH);
- intent.setComponent(activity);
- 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);
- intent.putExtra(SearchManager.USER_QUERY, query);
- intent.putExtra(SearchManager.QUERY, query);
- if (appData != null) {
- intent.putExtra(SearchManager.APP_DATA, appData);
- }
- return intent;
- }
-
- protected Intent createVoiceWebSearchIntent(Bundle appData) {
- return QsbApplication.get(mContext).getVoiceSearch()
- .createVoiceWebSearchIntent(appData);
- }
-
- @Override
- public Source getRoot() {
- return this;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o != null && o instanceof Source) {
- Source s = ((Source) o).getRoot();
- if (s.getClass().equals(this.getClass())) {
- return s.getName().equals(getName());
- }
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- return getName().hashCode();
- }
-
- @Override
- public String toString() {
- return "Source{name=" + getName() + "}";
- }
-
-}
diff --git a/src/com/android/quicksearchbox/AbstractSuggestionCursorWrapper.java b/src/com/android/quicksearchbox/AbstractSuggestionCursorWrapper.java
deleted file mode 100644
index 78fc1c2..0000000
--- a/src/com/android/quicksearchbox/AbstractSuggestionCursorWrapper.java
+++ /dev/null
@@ -1,33 +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;
-
-/**
- * A SuggestionCursor that delegates all calls to other suggestions.
- */
-public abstract class AbstractSuggestionCursorWrapper extends AbstractSuggestionWrapper
- implements SuggestionCursor {
-
- private final String mUserQuery;
-
- public AbstractSuggestionCursorWrapper(String userQuery) {
- mUserQuery = userQuery;
- }
-
- public String getUserQuery() {
- return mUserQuery;
- }
-}
diff --git a/src/com/android/quicksearchbox/AbstractSuggestionExtras.java b/src/com/android/quicksearchbox/AbstractSuggestionExtras.java
deleted file mode 100644
index f2c5690..0000000
--- a/src/com/android/quicksearchbox/AbstractSuggestionExtras.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 org.json.JSONException;
-
-import java.util.Collection;
-import java.util.HashSet;
-
-/**
- * Abstract SuggestionExtras supporting flattening to JSON.
- */
-public abstract class AbstractSuggestionExtras implements SuggestionExtras {
-
- private final SuggestionExtras mMore;
-
- protected AbstractSuggestionExtras(SuggestionExtras more) {
- mMore = more;
- }
-
- public Collection<String> getExtraColumnNames() {
- HashSet<String> columns = new HashSet<String>();
- columns.addAll(doGetExtraColumnNames());
- if (mMore != null) {
- columns.addAll(mMore.getExtraColumnNames());
- }
- return columns;
- }
-
- protected abstract Collection<String> doGetExtraColumnNames();
-
- public String getExtra(String columnName) {
- String extra = doGetExtra(columnName);
- if (extra == null && mMore != null) {
- extra = mMore.getExtra(columnName);
- }
- return extra;
- }
-
- protected abstract String doGetExtra(String columnName);
-
- public String toJsonString() throws JSONException {
- return new JsonBackedSuggestionExtras(this).toString();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/AbstractSuggestionWrapper.java b/src/com/android/quicksearchbox/AbstractSuggestionWrapper.java
deleted file mode 100644
index a8e4f2b..0000000
--- a/src/com/android/quicksearchbox/AbstractSuggestionWrapper.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.content.ComponentName;
-
-/**
- * A Suggestion that delegates all calls to other suggestions.
- */
-public abstract class AbstractSuggestionWrapper implements Suggestion {
-
- /**
- * Gets the current suggestion.
- */
- protected abstract Suggestion current();
-
- public String getShortcutId() {
- return current().getShortcutId();
- }
-
- public String getSuggestionFormat() {
- return current().getSuggestionFormat();
- }
-
- public String getSuggestionIcon1() {
- return current().getSuggestionIcon1();
- }
-
- public String getSuggestionIcon2() {
- return current().getSuggestionIcon2();
- }
-
- public String getSuggestionIntentAction() {
- return current().getSuggestionIntentAction();
- }
-
- public ComponentName getSuggestionIntentComponent() {
- return current().getSuggestionIntentComponent();
- }
-
- public String getSuggestionIntentDataString() {
- return current().getSuggestionIntentDataString();
- }
-
- public String getSuggestionIntentExtraData() {
- return current().getSuggestionIntentExtraData();
- }
-
- public String getSuggestionLogType() {
- return current().getSuggestionLogType();
- }
-
- public String getSuggestionQuery() {
- return current().getSuggestionQuery();
- }
-
- public Source getSuggestionSource() {
- return current().getSuggestionSource();
- }
-
- public String getSuggestionText1() {
- return current().getSuggestionText1();
- }
-
- public String getSuggestionText2() {
- return current().getSuggestionText2();
- }
-
- public String getSuggestionText2Url() {
- return current().getSuggestionText2Url();
- }
-
- public boolean isSpinnerWhileRefreshing() {
- return current().isSpinnerWhileRefreshing();
- }
-
- public boolean isSuggestionShortcut() {
- return current().isSuggestionShortcut();
- }
-
- public boolean isWebSearchSuggestion() {
- return current().isWebSearchSuggestion();
- }
-
- public boolean isHistorySuggestion() {
- return current().isHistorySuggestion();
- }
-
- public SuggestionExtras getExtras() {
- return current().getExtras();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/CachingIconLoader.java b/src/com/android/quicksearchbox/CachingIconLoader.java
deleted file mode 100644
index ea45b40..0000000
--- a/src/com/android/quicksearchbox/CachingIconLoader.java
+++ /dev/null
@@ -1,140 +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 com.android.quicksearchbox.util.CachedLater;
-import com.android.quicksearchbox.util.Consumer;
-import com.android.quicksearchbox.util.Now;
-import com.android.quicksearchbox.util.NowOrLater;
-import com.android.quicksearchbox.util.NowOrLaterWrapper;
-
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.util.WeakHashMap;
-
-/**
- * Icon loader that caches the results of another icon loader.
- *
- */
-public class CachingIconLoader implements IconLoader {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.CachingIconLoader";
-
- private final IconLoader mWrapped;
-
- private final WeakHashMap<String, Entry> mIconCache;
-
- /**
- * Creates a new caching icon loader.
- *
- * @param wrapped IconLoader whose results will be cached.
- */
- public CachingIconLoader(IconLoader wrapped) {
- mWrapped = wrapped;
- mIconCache = new WeakHashMap<String, Entry>();
- }
-
- public NowOrLater<Drawable> getIcon(String drawableId) {
- if (DBG) Log.d(TAG, "getIcon(" + drawableId + ")");
- if (TextUtils.isEmpty(drawableId) || "0".equals(drawableId)) {
- return new Now<Drawable>(null);
- }
- Entry newEntry = null;
- NowOrLater<Drawable.ConstantState> drawableState;
- synchronized (this) {
- drawableState = queryCache(drawableId);
- if (drawableState == null) {
- newEntry = new Entry();
- storeInIconCache(drawableId, newEntry);
- }
- }
- if (drawableState != null) {
- return new NowOrLaterWrapper<Drawable.ConstantState, Drawable>(drawableState){
- @Override
- public Drawable get(Drawable.ConstantState value) {
- return value == null ? null : value.newDrawable();
- }};
- }
- NowOrLater<Drawable> drawable = mWrapped.getIcon(drawableId);
- newEntry.set(drawable);
- storeInIconCache(drawableId, newEntry);
- return drawable;
- }
-
- public Uri getIconUri(String drawableId) {
- return mWrapped.getIconUri(drawableId);
- }
-
- private synchronized NowOrLater<Drawable.ConstantState> queryCache(String drawableId) {
- NowOrLater<Drawable.ConstantState> cached = mIconCache.get(drawableId);
- if (DBG) {
- if (cached != null) Log.d(TAG, "Found icon in cache: " + drawableId);
- }
- return cached;
- }
-
- private synchronized void storeInIconCache(String resourceUri, Entry drawable) {
- if (drawable != null) {
- mIconCache.put(resourceUri, drawable);
- }
- }
-
- private static class Entry extends CachedLater<Drawable.ConstantState>
- implements Consumer<Drawable>{
- private NowOrLater<Drawable> mDrawable;
- private boolean mGotDrawable;
- private boolean mCreateRequested;
-
- public Entry() {
- }
-
- public synchronized void set(NowOrLater<Drawable> drawable) {
- if (mGotDrawable) throw new IllegalStateException("set() may only be called once.");
- mGotDrawable = true;
- mDrawable = drawable;
- if (mCreateRequested) {
- getLater();
- }
- }
-
- @Override
- protected synchronized void create() {
- if (!mCreateRequested) {
- mCreateRequested = true;
- if (mGotDrawable) {
- getLater();
- }
- }
- }
-
- private void getLater() {
- NowOrLater<Drawable> drawable = mDrawable;
- mDrawable = null;
- drawable.getLater(this);
- }
-
- public boolean consume(Drawable value) {
- store(value == null ? null : value.getConstantState());
- return true;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/Config.java b/src/com/android/quicksearchbox/Config.java
deleted file mode 100644
index 678d411..0000000
--- a/src/com/android/quicksearchbox/Config.java
+++ /dev/null
@@ -1,299 +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.AlarmManager;
-import android.content.Context;
-import android.net.Uri;
-import android.os.Process;
-import android.util.Log;
-
-import java.util.HashSet;
-
-/**
- * Provides values for configurable parameters in all of QSB.
- *
- * All the methods in this class return fixed default values. Subclasses may
- * make these values server-side settable.
- *
- */
-public class Config {
-
- private static final String TAG = "QSB.Config";
- private static final boolean DBG = false;
-
- protected static final long SECOND_MILLIS = 1000L;
- protected static final long MINUTE_MILLIS = 60L * SECOND_MILLIS;
- protected static final long DAY_MILLIS = 86400000L;
-
- private static final int NUM_PROMOTED_SOURCES = 3;
- private static final int MAX_RESULTS_PER_SOURCE = 50;
- private static final long SOURCE_TIMEOUT_MILLIS = 10000;
-
- private static final int QUERY_THREAD_PRIORITY =
- Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE;
-
- private static final long MAX_STAT_AGE_MILLIS = 30 * DAY_MILLIS;
- private static final int MIN_CLICKS_FOR_SOURCE_RANKING = 3;
-
- private static final int NUM_WEB_CORPUS_THREADS = 2;
-
- private static final int LATENCY_LOG_FREQUENCY = 1000;
-
- private static final long TYPING_SUGGESTIONS_UPDATE_DELAY_MILLIS = 100;
- private static final long PUBLISH_RESULT_DELAY_MILLIS = 200;
-
- private static final long VOICE_SEARCH_HINT_ACTIVE_PERIOD = 7L * DAY_MILLIS;
-
- private static final long VOICE_SEARCH_HINT_UPDATE_INTERVAL
- = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
-
- private static final long VOICE_SEARCH_HINT_SHOW_PERIOD_MILLIS
- = AlarmManager.INTERVAL_HOUR * 2;
-
- private static final long VOICE_SEARCH_HINT_CHANGE_PERIOD = 2L * MINUTE_MILLIS;
-
- private static final long VOICE_SEARCH_HINT_VISIBLE_PERIOD = 6L * MINUTE_MILLIS;
-
- private static final int HTTP_CONNECT_TIMEOUT_MILLIS = 4000;
- private static final int HTTP_READ_TIMEOUT_MILLIS = 4000;
-
- private static final String USER_AGENT = "Android/1.0";
-
- private final Context mContext;
- private HashSet<String> mDefaultCorpora;
- private HashSet<String> mHiddenCorpora;
- private HashSet<String> mDefaultCorporaSuggestUris;
-
- /**
- * Creates a new config that uses hard-coded default values.
- */
- public Config(Context context) {
- mContext = context;
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- /**
- * Releases any resources used by the configuration object.
- *
- * Default implementation does nothing.
- */
- public void close() {
- }
-
- private HashSet<String> loadResourceStringSet(int res) {
- HashSet<String> set = new HashSet<String>();
- String[] items = mContext.getResources().getStringArray(res);
- for (String item : items) {
- set.add(item);
- }
- return set;
- }
-
- /**
- * The number of promoted sources.
- */
- public int getNumPromotedSources() {
- return NUM_PROMOTED_SOURCES;
- }
-
- /**
- * The number of suggestions visible above the onscreen keyboard.
- */
- public int getNumSuggestionsAboveKeyboard() {
- // Get the list of default corpora from a resource, which allows vendor overlays.
- return mContext.getResources().getInteger(R.integer.num_suggestions_above_keyboard);
- }
-
- /**
- * The maximum number of suggestions to promote.
- */
- public int getMaxPromotedSuggestions() {
- return mContext.getResources().getInteger(R.integer.max_promoted_suggestions);
- }
-
- public int getMaxPromotedResults() {
- return mContext.getResources().getInteger(R.integer.max_promoted_results);
- }
-
- /**
- * The number of results to ask each source for.
- */
- public int getMaxResultsPerSource() {
- return MAX_RESULTS_PER_SOURCE;
- }
-
- /**
- * The maximum number of shortcuts to show for the web source in All mode.
- */
- public int getMaxShortcutsPerWebSource() {
- return mContext.getResources().getInteger(R.integer.max_shortcuts_per_web_source);
- }
-
- /**
- * The maximum number of shortcuts to show for each non-web source in All mode.
- */
- public int getMaxShortcutsPerNonWebSource() {
- return mContext.getResources().getInteger(R.integer.max_shortcuts_per_non_web_source);
- }
-
- /**
- * Gets the maximum number of shortcuts that will be shown from the given source.
- */
- public int getMaxShortcuts(String sourceName) {
- return getMaxShortcutsPerNonWebSource();
- }
-
- /**
- * The timeout for querying each source, in milliseconds.
- */
- public long getSourceTimeoutMillis() {
- return SOURCE_TIMEOUT_MILLIS;
- }
-
- /**
- * The priority of query threads.
- *
- * @return A thread priority, as defined in {@link Process}.
- */
- public int getQueryThreadPriority() {
- return QUERY_THREAD_PRIORITY;
- }
-
- /**
- * The maximum age of log data used for shortcuts.
- */
- public long getMaxStatAgeMillis(){
- return MAX_STAT_AGE_MILLIS;
- }
-
- /**
- * The minimum number of clicks needed to rank a source.
- */
- public int getMinClicksForSourceRanking(){
- return MIN_CLICKS_FOR_SOURCE_RANKING;
- }
-
- public int getNumWebCorpusThreads() {
- return NUM_WEB_CORPUS_THREADS;
- }
-
- /**
- * How often query latency should be logged.
- *
- * @return An integer in the range 0-1000. 0 means that no latency events
- * should be logged. 1000 means that all latency events should be logged.
- */
- public int getLatencyLogFrequency() {
- return LATENCY_LOG_FREQUENCY;
- }
-
- /**
- * The delay in milliseconds before suggestions are updated while typing.
- * If a new character is typed before this timeout expires, the timeout is reset.
- */
- public long getTypingUpdateSuggestionsDelayMillis() {
- return TYPING_SUGGESTIONS_UPDATE_DELAY_MILLIS;
- }
-
- public boolean allowVoiceSearchHints() {
- return true;
- }
-
- /**
- * The period of time for which after installing voice search we should consider showing voice
- * search hints.
- *
- * @return The period in milliseconds.
- */
- public long getVoiceSearchHintActivePeriod() {
- return VOICE_SEARCH_HINT_ACTIVE_PERIOD;
- }
-
- /**
- * The time interval at which we should consider whether or not to show some voice search hints.
- *
- * @return The period in milliseconds.
- */
- public long getVoiceSearchHintUpdatePeriod() {
- return VOICE_SEARCH_HINT_UPDATE_INTERVAL;
- }
-
- /**
- * The time interval at which, on average, voice search hints are displayed.
- *
- * @return The period in milliseconds.
- */
- public long getVoiceSearchHintShowPeriod() {
- return VOICE_SEARCH_HINT_SHOW_PERIOD_MILLIS;
- }
-
- /**
- * The amount of time for which voice search hints are displayed in one go.
- *
- * @return The period in milliseconds.
- */
- public long getVoiceSearchHintVisibleTime() {
- return VOICE_SEARCH_HINT_VISIBLE_PERIOD;
- }
-
- /**
- * The period that we change voice search hints at while they're being displayed.
- *
- * @return The period in milliseconds.
- */
- public long getVoiceSearchHintChangePeriod() {
- return VOICE_SEARCH_HINT_CHANGE_PERIOD;
- }
-
- public boolean showSuggestionsForZeroQuery() {
- // Get the list of default corpora from a resource, which allows vendor overlays.
- return mContext.getResources().getBoolean(R.bool.show_zero_query_suggestions);
- }
-
- public boolean showShortcutsForZeroQuery() {
- // Get the list of default corpora from a resource, which allows vendor overlays.
- return mContext.getResources().getBoolean(R.bool.show_zero_query_shortcuts);
- }
-
- public boolean showScrollingSuggestions() {
- return mContext.getResources().getBoolean(R.bool.show_scrolling_suggestions);
- }
-
- public boolean showScrollingResults() {
- return mContext.getResources().getBoolean(R.bool.show_scrolling_results);
- }
-
- public Uri getHelpUrl(String activity) {
- return null;
- }
-
- public int getHttpConnectTimeout() {
- return HTTP_CONNECT_TIMEOUT_MILLIS;
- }
-
- public int getHttpReadTimeout() {
- return HTTP_READ_TIMEOUT_MILLIS;
- }
-
- public String getUserAgent() {
- return USER_AGENT;
- }
-}
diff --git a/src/com/android/quicksearchbox/CursorBackedSourceResult.java b/src/com/android/quicksearchbox/CursorBackedSourceResult.java
deleted file mode 100644
index 7c2fe9f..0000000
--- a/src/com/android/quicksearchbox/CursorBackedSourceResult.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.content.ComponentName;
-import android.database.Cursor;
-
-import com.android.quicksearchbox.google.GoogleSource;
-
-import java.util.Collection;
-
-public class CursorBackedSourceResult extends CursorBackedSuggestionCursor
- implements SourceResult {
-
- private final GoogleSource mSource;
-
- public CursorBackedSourceResult(GoogleSource source, String userQuery) {
- this(source, userQuery, null);
- }
-
- public CursorBackedSourceResult(GoogleSource source, String userQuery, Cursor cursor) {
- super(userQuery, cursor);
- mSource = source;
- }
-
- public GoogleSource getSource() {
- return mSource;
- }
-
- @Override
- public GoogleSource getSuggestionSource() {
- return mSource;
- }
-
- @Override
- public ComponentName getSuggestionIntentComponent() {
- return mSource.getIntentComponent();
- }
-
- public boolean isSuggestionShortcut() {
- return false;
- }
-
- public boolean isHistorySuggestion() {
- return false;
- }
-
- @Override
- public String toString() {
- return mSource + "[" + getUserQuery() + "]";
- }
-
- @Override
- public SuggestionExtras getExtras() {
- if (mCursor == null) return null;
- return CursorBackedSuggestionExtras.createExtrasIfNecessary(mCursor, getPosition());
- }
-
- public Collection<String> getExtraColumns() {
- if (mCursor == null) return null;
- return CursorBackedSuggestionExtras.getExtraColumns(mCursor);
- }
-
-} \ No newline at end of file
diff --git a/src/com/android/quicksearchbox/CursorBackedSuggestionCursor.java b/src/com/android/quicksearchbox/CursorBackedSuggestionCursor.java
deleted file mode 100644
index aa35164..0000000
--- a/src/com/android/quicksearchbox/CursorBackedSuggestionCursor.java
+++ /dev/null
@@ -1,301 +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.ComponentName;
-import android.content.Intent;
-import android.database.Cursor;
-import android.database.DataSetObserver;
-import android.net.Uri;
-import android.util.Log;
-
-public abstract class CursorBackedSuggestionCursor implements SuggestionCursor {
-
- private static final boolean DBG = false;
- protected static final String TAG = "QSB.CursorBackedSuggestionCursor";
-
- public static final String SUGGEST_COLUMN_LOG_TYPE = "suggest_log_type";
-
- private final String mUserQuery;
-
- /** The suggestions, or {@code null} if the suggestions query failed. */
- protected final Cursor mCursor;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_FORMAT} in @{link mCursor}. */
- private final int mFormatCol;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_TEXT_1} in @{link mCursor}. */
- private final int mText1Col;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_TEXT_2} in @{link mCursor}. */
- private final int mText2Col;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_TEXT_2_URL} in @{link mCursor}. */
- private final int mText2UrlCol;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_ICON_1} in @{link mCursor}. */
- private final int mIcon1Col;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_ICON_1} in @{link mCursor}. */
- private final int mIcon2Col;
-
- /** Column index of {@link SearchManager#SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING}
- * in @{link mCursor}.
- **/
- private final int mRefreshSpinnerCol;
-
- /** True if this result has been closed. */
- private boolean mClosed = false;
-
- public CursorBackedSuggestionCursor(String userQuery, Cursor cursor) {
- mUserQuery = userQuery;
- mCursor = cursor;
- mFormatCol = getColumnIndex(SearchManager.SUGGEST_COLUMN_FORMAT);
- mText1Col = getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
- mText2Col = getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2);
- mText2UrlCol = getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2_URL);
- mIcon1Col = getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_1);
- mIcon2Col = getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_2);
- mRefreshSpinnerCol = getColumnIndex(SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING);
- }
-
- public String getUserQuery() {
- return mUserQuery;
- }
-
- public abstract Source getSuggestionSource();
-
- public String getSuggestionLogType() {
- return getStringOrNull(SUGGEST_COLUMN_LOG_TYPE);
- }
-
- public void close() {
- if (DBG) Log.d(TAG, "close()");
- if (mClosed) {
- throw new IllegalStateException("Double close()");
- }
- mClosed = true;
- if (mCursor != null) {
- try {
- mCursor.close();
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "close() failed, ", ex);
- }
- }
- }
-
- @Override
- protected void finalize() {
- if (!mClosed) {
- Log.e(TAG, "LEAK! Finalized without being closed: " + toString());
- }
- }
-
- public int getCount() {
- if (mClosed) {
- throw new IllegalStateException("getCount() after close()");
- }
- if (mCursor == null) return 0;
- try {
- return mCursor.getCount();
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getCount() failed, ", ex);
- return 0;
- }
- }
-
- public void moveTo(int pos) {
- if (mClosed) {
- throw new IllegalStateException("moveTo(" + pos + ") after close()");
- }
- try {
- if (!mCursor.moveToPosition(pos)) {
- Log.e(TAG, "moveToPosition(" + pos + ") failed, count=" + getCount());
- }
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "moveToPosition() failed, ", ex);
- }
- }
-
- public boolean moveToNext() {
- if (mClosed) {
- throw new IllegalStateException("moveToNext() after close()");
- }
- try {
- return mCursor.moveToNext();
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "moveToNext() failed, ", ex);
- return false;
- }
- }
-
- public int getPosition() {
- if (mClosed) {
- throw new IllegalStateException("getPosition after close()");
- }
- try {
- return mCursor.getPosition();
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getPosition() failed, ", ex);
- return -1;
- }
- }
-
- public String getShortcutId() {
- return getStringOrNull(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
- }
-
- public String getSuggestionFormat() {
- return getStringOrNull(mFormatCol);
- }
-
- public String getSuggestionText1() {
- return getStringOrNull(mText1Col);
- }
-
- public String getSuggestionText2() {
- return getStringOrNull(mText2Col);
- }
-
- public String getSuggestionText2Url() {
- return getStringOrNull(mText2UrlCol);
- }
-
- public String getSuggestionIcon1() {
- return getStringOrNull(mIcon1Col);
- }
-
- public String getSuggestionIcon2() {
- return getStringOrNull(mIcon2Col);
- }
-
- public boolean isSpinnerWhileRefreshing() {
- return "true".equals(getStringOrNull(mRefreshSpinnerCol));
- }
-
- /**
- * Gets the intent action for the current suggestion.
- */
- public String getSuggestionIntentAction() {
- String action = getStringOrNull(SearchManager.SUGGEST_COLUMN_INTENT_ACTION);
- if (action != null) return action;
- return getSuggestionSource().getDefaultIntentAction();
- }
-
- public abstract ComponentName getSuggestionIntentComponent();
-
- /**
- * Gets the query for the current suggestion.
- */
- public String getSuggestionQuery() {
- return getStringOrNull(SearchManager.SUGGEST_COLUMN_QUERY);
- }
-
- public String getSuggestionIntentDataString() {
- // use specific data if supplied, or default data if supplied
- String data = getStringOrNull(SearchManager.SUGGEST_COLUMN_INTENT_DATA);
- if (data == null) {
- data = getSuggestionSource().getDefaultIntentData();
- }
- // then, if an ID was provided, append it.
- if (data != null) {
- String id = getStringOrNull(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
- if (id != null) {
- data = data + "/" + Uri.encode(id);
- }
- }
- return data;
- }
-
- /**
- * Gets the intent extra data for the current suggestion.
- */
- public String getSuggestionIntentExtraData() {
- return getStringOrNull(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
- }
-
- public boolean isWebSearchSuggestion() {
- return Intent.ACTION_WEB_SEARCH.equals(getSuggestionIntentAction());
- }
-
- /**
- * Gets the index of a column in {@link #mCursor} by name.
- *
- * @return The index, or {@code -1} if the column was not found.
- */
- protected int getColumnIndex(String colName) {
- if (mCursor == null) return -1;
- try {
- return mCursor.getColumnIndex(colName);
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getColumnIndex() failed, ", ex);
- return -1;
- }
- }
-
- /**
- * Gets the string value of a column in {@link #mCursor} by column index.
- *
- * @param col Column index.
- * @return The string value, or {@code null}.
- */
- protected String getStringOrNull(int col) {
- if (mCursor == null) return null;
- if (col == -1) {
- return null;
- }
- try {
- return mCursor.getString(col);
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getString() failed, ", ex);
- return null;
- }
- }
-
- /**
- * Gets the string value of a column in {@link #mCursor} by column name.
- *
- * @param colName Column name.
- * @return The string value, or {@code null}.
- */
- protected String getStringOrNull(String colName) {
- int col = getColumnIndex(colName);
- return getStringOrNull(col);
- }
-
- public void registerDataSetObserver(DataSetObserver observer) {
- // We don't watch Cursor-backed SuggestionCursors for changes
- }
-
- public void unregisterDataSetObserver(DataSetObserver observer) {
- // We don't watch Cursor-backed SuggestionCursors for changes
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "[" + mUserQuery + "]";
- }
-
-}
diff --git a/src/com/android/quicksearchbox/CursorBackedSuggestionExtras.java b/src/com/android/quicksearchbox/CursorBackedSuggestionExtras.java
deleted file mode 100644
index b6d85ff..0000000
--- a/src/com/android/quicksearchbox/CursorBackedSuggestionExtras.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * 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.database.Cursor;
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-
-/**
- * SuggestionExtras taking values from the extra columns in a suggestion cursor.
- */
-public class CursorBackedSuggestionExtras extends AbstractSuggestionExtras {
- private static final String TAG = "QSB.CursorBackedSuggestionExtras";
-
- private static final HashSet<String> DEFAULT_COLUMNS = new HashSet<String>();
- static {
- DEFAULT_COLUMNS.addAll(Arrays.asList(SuggestionCursorBackedCursor.COLUMNS));
- }
-
- private final Cursor mCursor;
- private final int mCursorPosition;
- private final List<String> mExtraColumns;
-
- static CursorBackedSuggestionExtras createExtrasIfNecessary(Cursor cursor, int position) {
- List<String> extraColumns = getExtraColumns(cursor);
- if (extraColumns != null) {
- return new CursorBackedSuggestionExtras(cursor, position, extraColumns);
- } else {
- return null;
- }
- }
-
- static String[] getCursorColumns(Cursor cursor) {
- try {
- return cursor.getColumnNames();
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getColumnNames() failed, ", ex);
- return null;
- }
- }
-
- static boolean cursorContainsExtras(Cursor cursor) {
- String[] columns = getCursorColumns(cursor);
- for (String cursorColumn : columns) {
- if (!DEFAULT_COLUMNS.contains(cursorColumn)) {
- return true;
- }
- }
- return false;
- }
-
- static List<String> getExtraColumns(Cursor cursor) {
- String[] columns = getCursorColumns(cursor);
- if (columns == null) return null;
- List<String> extraColumns = null;
- for (String cursorColumn : columns) {
- if (!DEFAULT_COLUMNS.contains(cursorColumn)) {
- if (extraColumns == null) {
- extraColumns = new ArrayList<String>();
- }
- extraColumns.add(cursorColumn);
- }
- }
- return extraColumns;
- }
-
- private CursorBackedSuggestionExtras(Cursor cursor, int position, List<String> extraColumns) {
- super(null);
- mCursor = cursor;
- mCursorPosition = position;
- mExtraColumns = extraColumns;
- }
-
- @Override
- public String doGetExtra(String columnName) {
- try {
- mCursor.moveToPosition(mCursorPosition);
- int columnIdx = mCursor.getColumnIndex(columnName);
- if (columnIdx < 0) return null;
- return mCursor.getString(columnIdx);
- } catch (RuntimeException ex) {
- // all operations on cross-process cursors can throw random exceptions
- Log.e(TAG, "getExtra(" + columnName + ") failed, ", ex);
- return null;
- }
- }
-
- @Override
- public List<String> doGetExtraColumnNames() {
- return mExtraColumns;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/DialogActivity.java b/src/com/android/quicksearchbox/DialogActivity.java
deleted file mode 100644
index 276b688..0000000
--- a/src/com/android/quicksearchbox/DialogActivity.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.Activity;
-import android.os.Bundle;
-import android.view.View;
-import android.view.Window;
-import android.widget.FrameLayout;
-import android.widget.TextView;
-
-/**
- * Activity that looks like a dialog window.
- */
-public abstract class DialogActivity extends Activity {
-
- protected TextView mTitleView;
- protected FrameLayout mContentFrame;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getWindow().requestFeature(Window.FEATURE_NO_TITLE);
- setContentView(R.layout.dialog_activity);
- mTitleView = (TextView) findViewById(R.id.alertTitle);
- mContentFrame = (FrameLayout) findViewById(R.id.content);
- }
-
- public void setHeading(int titleRes) {
- mTitleView.setText(titleRes);
- }
-
- public void setHeading(CharSequence title) {
- mTitleView.setText(title);
- }
-
- public void setDialogContent(int layoutRes) {
- mContentFrame.removeAllViews();
- getLayoutInflater().inflate(layoutRes, mContentFrame);
- }
-
- public void setDialogContent(View content) {
- mContentFrame.removeAllViews();
- mContentFrame.addView(content);
- }
-
- public View getDialogContent() {
- if (mContentFrame.getChildCount() > 0) {
- return mContentFrame.getChildAt(0);
- } else {
- return null;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/EventLogLogger.java b/src/com/android/quicksearchbox/EventLogLogger.java
deleted file mode 100644
index 17ec0d1..0000000
--- a/src/com/android/quicksearchbox/EventLogLogger.java
+++ /dev/null
@@ -1,111 +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.content.Context;
-import android.util.EventLog;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Random;
-
-/**
- * Logs events to {@link EventLog}.
- */
-public class EventLogLogger implements Logger {
-
- private static final char LIST_SEPARATOR = '|';
-
- private final Context mContext;
-
- private final Config mConfig;
-
- private final String mPackageName;
-
- private final Random mRandom;
-
- public EventLogLogger(Context context, Config config) {
- mContext = context;
- mConfig = config;
- mPackageName = mContext.getPackageName();
- mRandom = new Random();
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- protected int getVersionCode() {
- return QsbApplication.get(getContext()).getVersionCode();
- }
-
- protected Config getConfig() {
- return mConfig;
- }
-
- @Override
- public void logStart(int onCreateLatency, int latency, String intentSource) {
- // TODO: Add more info to startMethod
- String startMethod = intentSource;
- EventLogTags.writeQsbStart(mPackageName, getVersionCode(), startMethod,
- latency, null, null, onCreateLatency);
- }
-
- @Override
- public void logSuggestionClick(long id, SuggestionCursor suggestionCursor, int clickType) {
- String suggestions = getSuggestions(suggestionCursor);
- int numChars = suggestionCursor.getUserQuery().length();
- EventLogTags.writeQsbClick(id, suggestions, null, numChars,
- clickType);
- }
-
- @Override
- public void logSearch(int startMethod, int numChars) {
- EventLogTags.writeQsbSearch(null, startMethod, numChars);
- }
-
- @Override
- public void logVoiceSearch() {
- EventLogTags.writeQsbVoiceSearch(null);
- }
-
- @Override
- public void logExit(SuggestionCursor suggestionCursor, int numChars) {
- String suggestions = getSuggestions(suggestionCursor);
- EventLogTags.writeQsbExit(suggestions, numChars);
- }
-
- @Override
- public void logLatency(SourceResult result) {
- }
-
- private String getSuggestions(SuggestionCursor cursor) {
- StringBuilder sb = new StringBuilder();
- final int count = cursor == null ? 0 : cursor.getCount();
- for (int i = 0; i < count; i++) {
- if (i > 0) sb.append(LIST_SEPARATOR);
- cursor.moveTo(i);
- String source = cursor.getSuggestionSource().getName();
- String type = cursor.getSuggestionLogType();
- if (type == null) type = "";
- String shortcut = cursor.isSuggestionShortcut() ? "shortcut" : "";
- sb.append(source).append(':').append(type).append(':').append(shortcut);
- }
- return sb.toString();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/Help.java b/src/com/android/quicksearchbox/Help.java
deleted file mode 100644
index 9c86811..0000000
--- a/src/com/android/quicksearchbox/Help.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2011 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.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-
-/**
- * Handles app help.
- */
-public class Help {
-
- private final Context mContext;
- private final Config mConfig;
-
- public Help(Context context, Config config) {
- mContext = context;
- mConfig = config;
- }
-
- public void addHelpMenuItem(Menu menu, String activityName) {
- addHelpMenuItem(menu, activityName, false);
- }
-
- public void addHelpMenuItem(Menu menu, String activityName, boolean showAsAction) {
- Intent helpIntent = getHelpIntent(activityName);
- if (helpIntent != null) {
- MenuInflater inflater = new MenuInflater(mContext);
- inflater.inflate(R.menu.help, menu);
- MenuItem item = menu.findItem(R.id.menu_help);
- item.setIntent(helpIntent);
- if (showAsAction) {
- item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
- }
- }
- }
-
- private Intent getHelpIntent(String activityName) {
- Uri helpUrl = mConfig.getHelpUrl(activityName);
- if (helpUrl == null) return null;
- return new Intent(Intent.ACTION_VIEW, helpUrl);
- }
-
-}
diff --git a/src/com/android/quicksearchbox/IconLoader.java b/src/com/android/quicksearchbox/IconLoader.java
deleted file mode 100644
index 191ca33..0000000
--- a/src/com/android/quicksearchbox/IconLoader.java
+++ /dev/null
@@ -1,56 +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 com.android.quicksearchbox.util.NowOrLater;
-
-import android.content.ContentResolver;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-
-/**
- * Interface for icon loaders.
- *
- */
-public interface IconLoader {
-
- /**
- * Gets a drawable given an ID.
- *
- * The ID could be just the string value of a resource id
- * (e.g., "2130837524"), in which case we will try to retrieve a drawable from
- * the provider's resources. If the ID is not an integer, it is
- * treated as a Uri and opened with
- * {@link ContentResolver#openOutputStream(android.net.Uri, String)}.
- *
- * All resources and URIs are read using the suggestion provider's context.
- *
- * @return a {@link NowOrLater} for retrieving the icon. If the ID is not formatted as expected,
- * or no drawable can be found for the provided value, the value from this will be null.
- *
- * @param drawableId a string like "2130837524",
- * "android.resource://com.android.alarmclock/2130837524",
- * or "content://contacts/photos/253".
- */
- NowOrLater<Drawable> getIcon(String drawableId);
-
- /**
- * Converts a drawable ID to a Uri that can be used from other packages.
- */
- Uri getIconUri(String drawableId);
-
-}
diff --git a/src/com/android/quicksearchbox/JsonBackedSuggestionExtras.java b/src/com/android/quicksearchbox/JsonBackedSuggestionExtras.java
deleted file mode 100644
index 418a0b0..0000000
--- a/src/com/android/quicksearchbox/JsonBackedSuggestionExtras.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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 org.json.JSONException;
-import org.json.JSONObject;
-
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-
-/**
- * SuggestionExtras taking values from a {@link JSONObject}.
- */
-public class JsonBackedSuggestionExtras implements SuggestionExtras {
- private static final String TAG = "QSB.JsonBackedSuggestionExtras";
-
- private final JSONObject mExtras;
- private final Collection<String> mColumns;
-
- public JsonBackedSuggestionExtras(String json) throws JSONException {
- mExtras = new JSONObject(json);
- mColumns = new ArrayList<String>(mExtras.length());
- Iterator<String> it = mExtras.keys();
- while (it.hasNext()) {
- mColumns.add(it.next());
- }
- }
-
- public JsonBackedSuggestionExtras(SuggestionExtras extras) throws JSONException {
- mExtras = new JSONObject();
- mColumns = extras.getExtraColumnNames();
- for (String column : extras.getExtraColumnNames()) {
- String value = extras.getExtra(column);
- mExtras.put(column, value == null ? JSONObject.NULL : value);
- }
- }
-
- public String getExtra(String columnName) {
- try {
- if (mExtras.isNull(columnName)) {
- return null;
- } else {
- return mExtras.getString(columnName);
- }
- } catch (JSONException e) {
- Log.w(TAG, "Could not extract JSON extra", e);
- return null;
- }
- }
-
- public Collection<String> getExtraColumnNames() {
- return mColumns;
- }
-
- @Override
- public String toString() {
- return mExtras.toString();
- }
-
- public String toJsonString() {
- return toString();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/LatencyTracker.java b/src/com/android/quicksearchbox/LatencyTracker.java
deleted file mode 100644
index 6c9472c..0000000
--- a/src/com/android/quicksearchbox/LatencyTracker.java
+++ /dev/null
@@ -1,55 +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.os.SystemClock;
-
-/**
- * Tracks latency in wall-clock time. Since {@link #getLatency} returns an {@code int},
- * latencies over 2^31 ms (~ 25 days) cannot be measured.
- * This class uses {@link SystemClock#uptimeMillis} which does not advance during deep sleep.
- */
-public class LatencyTracker {
-
- /**
- * Start time, in milliseconds as returned by {@link SystemClock#uptimeMillis}.
- */
- private long mStartTime;
-
- /**
- * Creates a new latency tracker and sets the start time.
- */
- public LatencyTracker() {
- mStartTime = SystemClock.uptimeMillis();
- }
-
- /**
- * Resets the start time.
- */
- public void reset() {
- mStartTime = SystemClock.uptimeMillis();
- }
-
- /**
- * Gets the number of milliseconds since the object was created, or {@link #reset} was called.
- */
- public int getLatency() {
- long now = SystemClock.uptimeMillis();
- return (int) (now - mStartTime);
- }
-
-}
diff --git a/src/com/android/quicksearchbox/LevenshteinSuggestionFormatter.java b/src/com/android/quicksearchbox/LevenshteinSuggestionFormatter.java
deleted file mode 100644
index 6961447..0000000
--- a/src/com/android/quicksearchbox/LevenshteinSuggestionFormatter.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * 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 com.android.quicksearchbox.util.LevenshteinDistance;
-import com.android.quicksearchbox.util.LevenshteinDistance.Token;
-import com.google.common.annotations.VisibleForTesting;
-
-import android.text.SpannableString;
-import android.text.Spanned;
-import android.util.Log;
-
-import java.util.Arrays;
-
-/**
- * Suggestion formatter using the Levenshtein distance (minumum edit distance) to calculate the
- * formatting.
- */
-public class LevenshteinSuggestionFormatter extends SuggestionFormatter {
- private static final boolean DBG = false;
- private static final String TAG = "QSB.LevenshteinSuggestionFormatter";
-
- public LevenshteinSuggestionFormatter(TextAppearanceFactory spanFactory) {
- super(spanFactory);
- }
-
- @Override
- public Spanned formatSuggestion(String query, String suggestion) {
- if (DBG) Log.d(TAG, "formatSuggestion('" + query + "', '" + suggestion + "')");
- query = normalizeQuery(query);
- final Token[] queryTokens = tokenize(query);
- final Token[] suggestionTokens = tokenize(suggestion);
- final int[] matches = findMatches(queryTokens, suggestionTokens);
- if (DBG){
- Log.d(TAG, "source = " + Arrays.toString(queryTokens));
- Log.d(TAG, "target = " + Arrays.toString(suggestionTokens));
- Log.d(TAG, "matches = " + Arrays.toString(matches));
- }
- final SpannableString str = new SpannableString(suggestion);
-
- final int matchesLen = matches.length;
- for (int i = 0; i < matchesLen; ++i) {
- final Token t = suggestionTokens[i];
- int sourceLen = 0;
- int thisMatch = matches[i];
- if (thisMatch >= 0) {
- sourceLen = queryTokens[thisMatch].length();
- }
- applySuggestedTextStyle(str, t.mStart + sourceLen, t.mEnd);
- applyQueryTextStyle(str, t.mStart, t.mStart + sourceLen);
- }
-
- return str;
- }
-
- private String normalizeQuery(String query) {
- return query.toLowerCase();
- }
-
- /**
- * Finds which tokens in the target match tokens in the source.
- *
- * @param source List of source tokens (i.e. user query)
- * @param target List of target tokens (i.e. suggestion)
- * @return The indices into source which target tokens correspond to. A non-negative value n at
- * position i means that target token i matches source token n. A negative value means that
- * the target token i does not match any source token.
- */
- @VisibleForTesting
- int[] findMatches(Token[] source, Token[] target) {
- final LevenshteinDistance table = new LevenshteinDistance(source, target);
- table.calculate();
- final int targetLen = target.length;
- final int[] result = new int[targetLen];
- LevenshteinDistance.EditOperation[] ops = table.getTargetOperations();
- for (int i = 0; i < targetLen; ++i) {
- if (ops[i].getType() == LevenshteinDistance.EDIT_UNCHANGED) {
- result[i] = ops[i].getPosition();
- } else {
- result[i] = -1;
- }
- }
- return result;
- }
-
- @VisibleForTesting
- Token[] tokenize(final String seq) {
- int pos = 0;
- final int len = seq.length();
- final char[] chars = seq.toCharArray();
- // There can't be more tokens than characters, make an array that is large enough
- Token[] tokens = new Token[len];
- int tokenCount = 0;
- while (pos < len) {
- while (pos < len && (chars[pos] == ' ' || chars[pos] == '\t')) {
- pos++;
- }
- int start = pos;
- while (pos < len && !(chars[pos] == ' ' || chars[pos] == '\t')) {
- pos++;
- }
- int end = pos;
- if (start != end) {
- tokens[tokenCount++] = new Token(chars, start, end);
- }
- }
- // Create a token array of the right size and return
- Token[] ret = new Token[tokenCount];
- System.arraycopy(tokens, 0, ret, 0, tokenCount);
- return ret;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ListSuggestionCursor.java b/src/com/android/quicksearchbox/ListSuggestionCursor.java
deleted file mode 100644
index 863be31..0000000
--- a/src/com/android/quicksearchbox/ListSuggestionCursor.java
+++ /dev/null
@@ -1,180 +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 com.google.common.annotations.VisibleForTesting;
-
-import android.database.DataSetObservable;
-import android.database.DataSetObserver;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-
-/**
- * A SuggestionCursor that is backed by a list of Suggestions.
- */
-public class ListSuggestionCursor extends AbstractSuggestionCursorWrapper {
-
- private static final int DEFAULT_CAPACITY = 16;
-
- private final DataSetObservable mDataSetObservable = new DataSetObservable();
-
- private final ArrayList<Entry> mSuggestions;
-
- private HashSet<String> mExtraColumns;
-
- private int mPos = 0;
-
- public ListSuggestionCursor(String userQuery) {
- this(userQuery, DEFAULT_CAPACITY);
- }
-
- @VisibleForTesting
- public ListSuggestionCursor(String userQuery, Suggestion...suggestions) {
- this(userQuery, suggestions.length);
- for (Suggestion suggestion : suggestions) {
- add(suggestion);
- }
- }
-
- public ListSuggestionCursor(String userQuery, int capacity) {
- super(userQuery);
- mSuggestions = new ArrayList<Entry>(capacity);
- }
-
- /**
- * Adds a suggestion from another suggestion cursor.
- *
- * @return {@code true} if the suggestion was added.
- */
- public boolean add(Suggestion suggestion) {
- mSuggestions.add(new Entry(suggestion));
- return true;
- }
-
- public void close() {
- mSuggestions.clear();
- }
-
- public int getPosition() {
- return mPos;
- }
-
- public void moveTo(int pos) {
- mPos = pos;
- }
-
- public boolean moveToNext() {
- int size = mSuggestions.size();
- if (mPos >= size) {
- // Already past the end
- return false;
- }
- mPos++;
- return mPos < size;
- }
-
- public void removeRow() {
- mSuggestions.remove(mPos);
- }
-
- public void replaceRow(Suggestion suggestion) {
- mSuggestions.set(mPos, new Entry(suggestion));
- }
-
- public int getCount() {
- return mSuggestions.size();
- }
-
- @Override
- protected Suggestion current() {
- return mSuggestions.get(mPos).get();
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{[" + getUserQuery() + "] " + mSuggestions + "}";
- }
-
- /**
- * Register an observer that is called when changes happen to this data set.
- *
- * @param observer gets notified when the data set changes.
- */
- public void registerDataSetObserver(DataSetObserver observer) {
- mDataSetObservable.registerObserver(observer);
- }
-
- /**
- * Unregister an observer that has previously been registered with
- * {@link #registerDataSetObserver(DataSetObserver)}
- *
- * @param observer the observer to unregister.
- */
- public void unregisterDataSetObserver(DataSetObserver observer) {
- mDataSetObservable.unregisterObserver(observer);
- }
-
- protected void notifyDataSetChanged() {
- mDataSetObservable.notifyChanged();
- }
-
- @Override
- public SuggestionExtras getExtras() {
- // override with caching to avoid re-parsing the extras
- return mSuggestions.get(mPos).getExtras();
- }
-
- public Collection<String> getExtraColumns() {
- if (mExtraColumns == null) {
- mExtraColumns = new HashSet<String>();
- for (Entry e : mSuggestions) {
- SuggestionExtras extras = e.getExtras();
- Collection<String> extraColumns = extras == null ? null
- : extras.getExtraColumnNames();
- if (extraColumns != null) {
- for (String column : extras.getExtraColumnNames()) {
- mExtraColumns.add(column);
- }
- }
- }
- }
- return mExtraColumns.isEmpty() ? null : mExtraColumns;
- }
-
- /**
- * This class exists purely to cache the suggestion extras.
- */
- private static class Entry {
- private final Suggestion mSuggestion;
- private SuggestionExtras mExtras;
- public Entry(Suggestion s) {
- mSuggestion = s;
- }
- public Suggestion get() {
- return mSuggestion;
- }
- public SuggestionExtras getExtras() {
- if (mExtras == null) {
- mExtras = mSuggestion.getExtras();
- }
- return mExtras;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ListSuggestionCursorNoDuplicates.java b/src/com/android/quicksearchbox/ListSuggestionCursorNoDuplicates.java
deleted file mode 100644
index 48c302c..0000000
--- a/src/com/android/quicksearchbox/ListSuggestionCursorNoDuplicates.java
+++ /dev/null
@@ -1,50 +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.util.Log;
-
-import java.util.HashSet;
-
-/**
- * A SuggestionCursor that is backed by a list of SuggestionPosition objects
- * and doesn't allow duplicate suggestions.
- */
-public class ListSuggestionCursorNoDuplicates extends ListSuggestionCursor {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.ListSuggestionCursorNoDuplicates";
-
- private final HashSet<String> mSuggestionKeys;
-
- public ListSuggestionCursorNoDuplicates(String userQuery) {
- super(userQuery);
- mSuggestionKeys = new HashSet<String>();
- }
-
- @Override
- public boolean add(Suggestion suggestion) {
- String key = SuggestionUtils.getSuggestionKey(suggestion);
- if (mSuggestionKeys.add(key)) {
- return super.add(suggestion);
- } else {
- if (DBG) Log.d(TAG, "Rejecting duplicate " + key);
- return false;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/Logger.java b/src/com/android/quicksearchbox/Logger.java
deleted file mode 100644
index 40ff606..0000000
--- a/src/com/android/quicksearchbox/Logger.java
+++ /dev/null
@@ -1,78 +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;
-
-
-
-/**
- * Interface for logging implementations.
- */
-public interface Logger {
-
- public static final int SEARCH_METHOD_BUTTON = 0;
- public static final int SEARCH_METHOD_KEYBOARD = 1;
-
- public static final int SUGGESTION_CLICK_TYPE_LAUNCH = 0;
- public static final int SUGGESTION_CLICK_TYPE_REFINE = 1;
- public static final int SUGGESTION_CLICK_TYPE_QUICK_CONTACT = 2;
-
- /**
- * Called when QSB has started.
- *
- * @param latency User-visible start-up latency in milliseconds.
- */
- void logStart(int onCreateLatency, int latency, String intentSource);
-
- /**
- * Called when a suggestion is clicked.
- *
- * @param suggestionId Suggestion ID; 0-based position of the suggestion in the UI if the list
- * is flat.
- * @param suggestionCursor all the suggestions shown in the UI.
- * @param clickType One of the SUGGESTION_CLICK_TYPE constants.
- */
- void logSuggestionClick(long suggestionId, SuggestionCursor suggestionCursor, int clickType);
-
- /**
- * The user launched a search.
- *
- * @param startMethod One of {@link #SEARCH_METHOD_BUTTON} or {@link #SEARCH_METHOD_KEYBOARD}.
- * @param numChars The number of characters in the query.
- */
- void logSearch(int startMethod, int numChars);
-
- /**
- * The user launched a voice search.
- */
- void logVoiceSearch();
-
- /**
- * The user left QSB without performing any action (click suggestions, search or voice search).
- *
- * @param suggestionCursor all the suggestions shown in the UI when the user left
- * @param numChars The number of characters in the query typed when the user left.
- */
- void logExit(SuggestionCursor suggestionCursor, int numChars);
-
- /**
- * Logs the latency of a suggestion query to a specific source.
- *
- * @param result The result of the query.
- */
- void logLatency(SourceResult result);
-
-}
diff --git a/src/com/android/quicksearchbox/PackageIconLoader.java b/src/com/android/quicksearchbox/PackageIconLoader.java
deleted file mode 100644
index a572d3c..0000000
--- a/src/com/android/quicksearchbox/PackageIconLoader.java
+++ /dev/null
@@ -1,261 +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 com.android.quicksearchbox.util.CachedLater;
-import com.android.quicksearchbox.util.NamedTask;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-import com.android.quicksearchbox.util.Now;
-import com.android.quicksearchbox.util.NowOrLater;
-import com.android.quicksearchbox.util.Util;
-
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.res.Resources;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Handler;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-/**
- * Loads icons from other packages.
- *
- * Code partly stolen from {@link ContentResolver} and android.app.SuggestionsAdapter.
- */
-public class PackageIconLoader implements IconLoader {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.PackageIconLoader";
-
- private final Context mContext;
-
- private final String mPackageName;
-
- private Context mPackageContext;
-
- private final Handler mUiThread;
-
- private final NamedTaskExecutor mIconLoaderExecutor;
-
- /**
- * Creates a new icon loader.
- *
- * @param context The QSB application context.
- * @param packageName The name of the package from which the icons will be loaded.
- * Resource IDs without an explicit package will be resolved against the package
- * of this context.
- */
- public PackageIconLoader(Context context, String packageName, Handler uiThread,
- NamedTaskExecutor iconLoaderExecutor) {
- mContext = context;
- mPackageName = packageName;
- mUiThread = uiThread;
- mIconLoaderExecutor = iconLoaderExecutor;
- }
-
- private boolean ensurePackageContext() {
- if (mPackageContext == null) {
- try {
- mPackageContext = mContext.createPackageContext(mPackageName,
- Context.CONTEXT_RESTRICTED);
- } catch (PackageManager.NameNotFoundException ex) {
- // This should only happen if the app has just be uninstalled
- Log.e(TAG, "Application not found " + mPackageName);
- return false;
- }
- }
- return true;
- }
-
- public NowOrLater<Drawable> getIcon(final String drawableId) {
- if (DBG) Log.d(TAG, "getIcon(" + drawableId + ")");
- if (TextUtils.isEmpty(drawableId) || "0".equals(drawableId)) {
- return new Now<Drawable>(null);
- }
- if (!ensurePackageContext()) {
- return new Now<Drawable>(null);
- }
- NowOrLater<Drawable> drawable;
- try {
- // First, see if it's just an integer
- int resourceId = Integer.parseInt(drawableId);
- // If so, find it by resource ID
- Drawable icon = mPackageContext.getResources().getDrawable(resourceId);
- drawable = new Now<Drawable>(icon);
- } catch (NumberFormatException nfe) {
- // It's not an integer, use it as a URI
- Uri uri = Uri.parse(drawableId);
- if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(uri.getScheme())) {
- // load all resources synchronously, to reduce UI flickering
- drawable = new Now<Drawable>(getDrawable(uri));
- } else {
- drawable = new IconLaterTask(uri);
- }
- } catch (Resources.NotFoundException nfe) {
- // It was an integer, but it couldn't be found, bail out
- Log.w(TAG, "Icon resource not found: " + drawableId);
- drawable = new Now<Drawable>(null);
- }
- return drawable;
- }
-
- public Uri getIconUri(String drawableId) {
- if (TextUtils.isEmpty(drawableId) || "0".equals(drawableId)) {
- return null;
- }
- if (!ensurePackageContext()) return null;
- try {
- int resourceId = Integer.parseInt(drawableId);
- return Util.getResourceUri(mPackageContext, resourceId);
- } catch (NumberFormatException nfe) {
- return Uri.parse(drawableId);
- }
- }
-
- /**
- * Gets a drawable by URI.
- *
- * @return A drawable, or {@code null} if the drawable could not be loaded.
- */
- private Drawable getDrawable(Uri uri) {
- try {
- String scheme = uri.getScheme();
- if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
- // Load drawables through Resources, to get the source density information
- OpenResourceIdResult r = getResourceId(uri);
- try {
- return r.r.getDrawable(r.id);
- } catch (Resources.NotFoundException ex) {
- throw new FileNotFoundException("Resource does not exist: " + uri);
- }
- } else {
- // Let the ContentResolver handle content and file URIs.
- InputStream stream = mPackageContext.getContentResolver().openInputStream(uri);
- if (stream == null) {
- throw new FileNotFoundException("Failed to open " + uri);
- }
- try {
- return Drawable.createFromStream(stream, null);
- } finally {
- try {
- stream.close();
- } catch (IOException ex) {
- Log.e(TAG, "Error closing icon stream for " + uri, ex);
- }
- }
- }
- } catch (FileNotFoundException fnfe) {
- Log.w(TAG, "Icon not found: " + uri + ", " + fnfe.getMessage());
- return null;
- }
- }
-
- /**
- * A resource identified by the {@link Resources} that contains it, and a resource id.
- */
- private class OpenResourceIdResult {
- public Resources r;
- public int id;
- }
-
- /**
- * Resolves an android.resource URI to a {@link Resources} and a resource id.
- */
- private OpenResourceIdResult getResourceId(Uri uri) throws FileNotFoundException {
- String authority = uri.getAuthority();
- Resources r;
- if (TextUtils.isEmpty(authority)) {
- throw new FileNotFoundException("No authority: " + uri);
- } else {
- try {
- r = mPackageContext.getPackageManager().getResourcesForApplication(authority);
- } catch (NameNotFoundException ex) {
- throw new FileNotFoundException("Failed to get resources: " + ex);
- }
- }
- List<String> path = uri.getPathSegments();
- if (path == null) {
- throw new FileNotFoundException("No path: " + uri);
- }
- int len = path.size();
- int id;
- if (len == 1) {
- try {
- id = Integer.parseInt(path.get(0));
- } catch (NumberFormatException e) {
- throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
- }
- } else if (len == 2) {
- id = r.getIdentifier(path.get(1), path.get(0), authority);
- } else {
- throw new FileNotFoundException("More than two path segments: " + uri);
- }
- if (id == 0) {
- throw new FileNotFoundException("No resource found for: " + uri);
- }
- OpenResourceIdResult res = new OpenResourceIdResult();
- res.r = r;
- res.id = id;
- return res;
- }
-
- private class IconLaterTask extends CachedLater<Drawable> implements NamedTask {
- private final Uri mUri;
-
- public IconLaterTask(Uri iconUri) {
- mUri = iconUri;
- }
-
- @Override
- protected void create() {
- mIconLoaderExecutor.execute(this);
- }
-
- @Override
- public void run() {
- final Drawable icon = getIcon();
- mUiThread.post(new Runnable(){
- public void run() {
- store(icon);
- }});
- }
-
- @Override
- public String getName() {
- return mPackageName;
- }
-
- private Drawable getIcon() {
- try {
- return getDrawable(mUri);
- } catch (Throwable t) {
- // we're making a call into another package, which could throw any exception.
- // Make sure it doesn't crash QSB
- Log.e(TAG, "Failed to load icon " + mUri, t);
- return null;
- }
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/QsbApplication.java b/src/com/android/quicksearchbox/QsbApplication.java
deleted file mode 100644
index b3bccd3..0000000
--- a/src/com/android/quicksearchbox/QsbApplication.java
+++ /dev/null
@@ -1,364 +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.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.os.Build;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Process;
-import android.view.ContextThemeWrapper;
-
-import com.android.quicksearchbox.google.GoogleSource;
-import com.android.quicksearchbox.google.GoogleSuggestClient;
-import com.android.quicksearchbox.google.SearchBaseUrlHelper;
-import com.android.quicksearchbox.ui.DefaultSuggestionViewFactory;
-import com.android.quicksearchbox.ui.SuggestionViewFactory;
-import com.android.quicksearchbox.util.Factory;
-import com.android.quicksearchbox.util.HttpHelper;
-import com.android.quicksearchbox.util.JavaNetHttpHelper;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-import com.android.quicksearchbox.util.PerNameExecutor;
-import com.android.quicksearchbox.util.PriorityThreadFactory;
-import com.android.quicksearchbox.util.SingleThreadNamedTaskExecutor;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-
-public class QsbApplication {
- private final Context mContext;
-
- private int mVersionCode;
- private Handler mUiThreadHandler;
- private Config mConfig;
- private SearchSettings mSettings;
- private NamedTaskExecutor mSourceTaskExecutor;
- private ThreadFactory mQueryThreadFactory;
- private SuggestionsProvider mSuggestionsProvider;
- private SuggestionViewFactory mSuggestionViewFactory;
- private GoogleSource mGoogleSource;
- private VoiceSearch mVoiceSearch;
- private Logger mLogger;
- private SuggestionFormatter mSuggestionFormatter;
- private TextAppearanceFactory mTextAppearanceFactory;
- private NamedTaskExecutor mIconLoaderExecutor;
- private HttpHelper mHttpHelper;
- private SearchBaseUrlHelper mSearchBaseUrlHelper;
-
- public QsbApplication(Context context) {
- // the application context does not use the theme from the <application> tag
- mContext = new ContextThemeWrapper(context, R.style.Theme_QuickSearchBox);
- }
-
- public static boolean isFroyoOrLater() {
- return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
- }
-
- public static boolean isHoneycombOrLater() {
- return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
- }
-
- public static QsbApplication get(Context context) {
- return ((QsbApplicationWrapper) context.getApplicationContext()).getApp();
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- public int getVersionCode() {
- if (mVersionCode == 0) {
- try {
- PackageManager pm = getContext().getPackageManager();
- PackageInfo pkgInfo = pm.getPackageInfo(getContext().getPackageName(), 0);
- mVersionCode = pkgInfo.versionCode;
- } catch (PackageManager.NameNotFoundException ex) {
- // The current package should always exist, how else could we
- // run code from it?
- throw new RuntimeException(ex);
- }
- }
- return mVersionCode;
- }
-
- protected void checkThread() {
- if (Looper.myLooper() != Looper.getMainLooper()) {
- throw new IllegalStateException("Accessed Application object from thread "
- + Thread.currentThread().getName());
- }
- }
-
- protected void close() {
- checkThread();
- if (mConfig != null) {
- mConfig.close();
- mConfig = null;
- }
- if (mSuggestionsProvider != null) {
- mSuggestionsProvider.close();
- mSuggestionsProvider = null;
- }
- }
-
- public synchronized Handler getMainThreadHandler() {
- if (mUiThreadHandler == null) {
- mUiThreadHandler = new Handler(Looper.getMainLooper());
- }
- return mUiThreadHandler;
- }
-
- public void runOnUiThread(Runnable action) {
- getMainThreadHandler().post(action);
- }
-
- public synchronized NamedTaskExecutor getIconLoaderExecutor() {
- if (mIconLoaderExecutor == null) {
- mIconLoaderExecutor = createIconLoaderExecutor();
- }
- return mIconLoaderExecutor;
- }
-
- protected NamedTaskExecutor createIconLoaderExecutor() {
- ThreadFactory iconThreadFactory = new PriorityThreadFactory(
- Process.THREAD_PRIORITY_BACKGROUND);
- return new PerNameExecutor(SingleThreadNamedTaskExecutor.factory(iconThreadFactory));
- }
-
- /**
- * Indicates that construction of the QSB UI is now complete.
- */
- public void onStartupComplete() {
- }
-
- /**
- * Gets the QSB configuration object.
- * May be called from any thread.
- */
- public synchronized Config getConfig() {
- if (mConfig == null) {
- mConfig = createConfig();
- }
- return mConfig;
- }
-
- protected Config createConfig() {
- return new Config(getContext());
- }
-
- public synchronized SearchSettings getSettings() {
- if (mSettings == null) {
- mSettings = createSettings();
- mSettings.upgradeSettingsIfNeeded();
- }
- return mSettings;
- }
-
- protected SearchSettings createSettings() {
- return new SearchSettingsImpl(getContext(), getConfig());
- }
-
- protected Factory<Executor> createExecutorFactory(final int numThreads) {
- final ThreadFactory threadFactory = getQueryThreadFactory();
- return new Factory<Executor>() {
- @Override
- public Executor create() {
- return Executors.newFixedThreadPool(numThreads, threadFactory);
- }
- };
- }
-
- /**
- /**
- * Gets the source task executor.
- * May only be called from the main thread.
- */
- public NamedTaskExecutor getSourceTaskExecutor() {
- checkThread();
- if (mSourceTaskExecutor == null) {
- mSourceTaskExecutor = createSourceTaskExecutor();
- }
- return mSourceTaskExecutor;
- }
-
- protected NamedTaskExecutor createSourceTaskExecutor() {
- ThreadFactory queryThreadFactory = getQueryThreadFactory();
- return new PerNameExecutor(SingleThreadNamedTaskExecutor.factory(queryThreadFactory));
- }
-
- /**
- * Gets the query thread factory.
- * May only be called from the main thread.
- */
- protected ThreadFactory getQueryThreadFactory() {
- checkThread();
- if (mQueryThreadFactory == null) {
- mQueryThreadFactory = createQueryThreadFactory();
- }
- return mQueryThreadFactory;
- }
-
- protected ThreadFactory createQueryThreadFactory() {
- String nameFormat = "QSB #%d";
- int priority = getConfig().getQueryThreadPriority();
- return new ThreadFactoryBuilder()
- .setNameFormat(nameFormat)
- .setThreadFactory(new PriorityThreadFactory(priority))
- .build();
- }
-
- /**
- * Gets the suggestion provider.
- *
- * May only be called from the main thread.
- */
- protected SuggestionsProvider getSuggestionsProvider() {
- checkThread();
- if (mSuggestionsProvider == null) {
- mSuggestionsProvider = createSuggestionsProvider();
- }
- return mSuggestionsProvider;
- }
-
- protected SuggestionsProvider createSuggestionsProvider() {
- return new SuggestionsProviderImpl(getConfig(),
- getSourceTaskExecutor(),
- getMainThreadHandler(),
- getLogger());
- }
-
- /**
- * Gets the default suggestion view factory.
- * May only be called from the main thread.
- */
- public SuggestionViewFactory getSuggestionViewFactory() {
- checkThread();
- if (mSuggestionViewFactory == null) {
- mSuggestionViewFactory = createSuggestionViewFactory();
- }
- return mSuggestionViewFactory;
- }
-
- protected SuggestionViewFactory createSuggestionViewFactory() {
- return new DefaultSuggestionViewFactory(getContext());
- }
-
- /**
- * Gets the Google source.
- * May only be called from the main thread.
- */
- public GoogleSource getGoogleSource() {
- checkThread();
- if (mGoogleSource == null) {
- mGoogleSource = createGoogleSource();
- }
- return mGoogleSource;
- }
-
- protected GoogleSource createGoogleSource() {
- return new GoogleSuggestClient(getContext(), getMainThreadHandler(),
- getIconLoaderExecutor(), getConfig());
- }
-
- /**
- * Gets Voice Search utilities.
- */
- public VoiceSearch getVoiceSearch() {
- checkThread();
- if (mVoiceSearch == null) {
- mVoiceSearch = createVoiceSearch();
- }
- return mVoiceSearch;
- }
-
- protected VoiceSearch createVoiceSearch() {
- return new VoiceSearch(getContext());
- }
-
- /**
- * Gets the event logger.
- * May only be called from the main thread.
- */
- public Logger getLogger() {
- checkThread();
- if (mLogger == null) {
- mLogger = createLogger();
- }
- return mLogger;
- }
-
- protected Logger createLogger() {
- return new EventLogLogger(getContext(), getConfig());
- }
-
- public SuggestionFormatter getSuggestionFormatter() {
- if (mSuggestionFormatter == null) {
- mSuggestionFormatter = createSuggestionFormatter();
- }
- return mSuggestionFormatter;
- }
-
- protected SuggestionFormatter createSuggestionFormatter() {
- return new LevenshteinSuggestionFormatter(getTextAppearanceFactory());
- }
-
- public TextAppearanceFactory getTextAppearanceFactory() {
- if (mTextAppearanceFactory == null) {
- mTextAppearanceFactory = createTextAppearanceFactory();
- }
- return mTextAppearanceFactory;
- }
-
- protected TextAppearanceFactory createTextAppearanceFactory() {
- return new TextAppearanceFactory(getContext());
- }
-
- public synchronized HttpHelper getHttpHelper() {
- if (mHttpHelper == null) {
- mHttpHelper = createHttpHelper();
- }
- return mHttpHelper;
- }
-
- protected HttpHelper createHttpHelper() {
- return new JavaNetHttpHelper(
- new JavaNetHttpHelper.PassThroughRewriter(),
- getConfig().getUserAgent());
- }
-
- public synchronized SearchBaseUrlHelper getSearchBaseUrlHelper() {
- if (mSearchBaseUrlHelper == null) {
- mSearchBaseUrlHelper = createSearchBaseUrlHelper();
- }
-
- return mSearchBaseUrlHelper;
- }
-
- protected SearchBaseUrlHelper createSearchBaseUrlHelper() {
- // This cast to "SearchSettingsImpl" is somewhat ugly.
- return new SearchBaseUrlHelper(getContext(), getHttpHelper(),
- getSettings(), ((SearchSettingsImpl)getSettings()).getSearchPreferences());
- }
-
- public Help getHelp() {
- // No point caching this, it's super cheap.
- return new Help(getContext(), getConfig());
- }
-}
diff --git a/src/com/android/quicksearchbox/QsbApplicationWrapper.java b/src/com/android/quicksearchbox/QsbApplicationWrapper.java
deleted file mode 100644
index 7329cdf..0000000
--- a/src/com/android/quicksearchbox/QsbApplicationWrapper.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.Application;
-
-public class QsbApplicationWrapper extends Application {
-
- private QsbApplication mApp;
-
- @Override
- public void onTerminate() {
- synchronized (this) {
- if (mApp != null) {
- mApp.close();
- }
- }
- super.onTerminate();
- }
-
- public synchronized QsbApplication getApp() {
- if (mApp == null) {
- mApp = createQsbApplication();
- }
- return mApp;
- }
-
- protected QsbApplication createQsbApplication() {
- return new QsbApplication(this);
- }
-
-}
diff --git a/src/com/android/quicksearchbox/QueryTask.java b/src/com/android/quicksearchbox/QueryTask.java
deleted file mode 100644
index 8ea5be9..0000000
--- a/src/com/android/quicksearchbox/QueryTask.java
+++ /dev/null
@@ -1,86 +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 com.android.quicksearchbox.util.Consumer;
-import com.android.quicksearchbox.util.Consumers;
-import com.android.quicksearchbox.util.NamedTask;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-
-import android.os.Handler;
-import android.util.Log;
-
-/**
- * A task that gets suggestions from a corpus.
- */
-public class QueryTask<C extends SuggestionCursor> implements NamedTask {
- private static final String TAG = "QSB.QueryTask";
- private static final boolean DBG = false;
-
- private final String mQuery;
- private final int mQueryLimit;
- private final SuggestionCursorProvider<C> mProvider;
- private final Handler mHandler;
- private final Consumer<C> mConsumer;
-
- /**
- * Creates a new query task.
- *
- * @param query Query to run.
- * @param queryLimit The number of suggestions to ask each provider for.
- * @param provider The provider to ask for suggestions.
- * @param handler Handler that {@link Consumer#consume} will
- * get called on. If null, the method is called on the query thread.
- * @param consumer Consumer to notify when the suggestions have been returned.
- */
- public QueryTask(String query, int queryLimit, SuggestionCursorProvider<C> provider,
- Handler handler, Consumer<C> consumer) {
- mQuery = query;
- mQueryLimit = queryLimit;
- mProvider = provider;
- mHandler = handler;
- mConsumer = consumer;
- }
-
- @Override
- public String getName() {
- return mProvider.getName();
- }
-
- @Override
- public void run() {
- final C cursor = mProvider.getSuggestions(mQuery, mQueryLimit);
- if (DBG) Log.d(TAG, "Suggestions from " + mProvider + " = " + cursor);
- Consumers.consumeCloseableAsync(mHandler, mConsumer, cursor);
- }
-
- @Override
- public String toString() {
- return mProvider + "[" + mQuery + "]";
- }
-
- public static <C extends SuggestionCursor> void startQuery(String query,
- int maxResults,
- SuggestionCursorProvider<C> provider,
- NamedTaskExecutor executor, Handler handler,
- Consumer<C> consumer) {
-
- QueryTask<C> task = new QueryTask<C>(query, maxResults, provider, handler,
- consumer);
- executor.execute(task);
- }
-}
diff --git a/src/com/android/quicksearchbox/ResultFilter.java b/src/com/android/quicksearchbox/ResultFilter.java
deleted file mode 100644
index 76d88b6..0000000
--- a/src/com/android/quicksearchbox/ResultFilter.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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;
-
-/**
- * {@link SuggestionFilter} that accepts only results (not web suggestions).
- */
-public class ResultFilter implements SuggestionFilter {
-
- public ResultFilter() {
- }
-
- public boolean accept(Suggestion s) {
- return !s.isWebSearchSuggestion();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SearchActivity.java b/src/com/android/quicksearchbox/SearchActivity.java
deleted file mode 100644
index ff21a17..0000000
--- a/src/com/android/quicksearchbox/SearchActivity.java
+++ /dev/null
@@ -1,510 +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.Activity;
-import android.app.SearchManager;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Debug;
-import android.os.Handler;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.Menu;
-import android.view.View;
-
-import com.android.common.Search;
-import com.android.quicksearchbox.ui.SearchActivityView;
-import com.android.quicksearchbox.ui.SuggestionClickListener;
-import com.android.quicksearchbox.ui.SuggestionsAdapter;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.CharMatcher;
-
-import java.io.File;
-
-/**
- * The main activity for Quick Search Box. Shows the search UI.
- *
- */
-public class SearchActivity extends Activity {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SearchActivity";
-
- private static final String SCHEME_CORPUS = "qsb.corpus";
-
- private static final String INTENT_EXTRA_TRACE_START_UP = "trace_start_up";
-
- // Keys for the saved instance state.
- private static final String INSTANCE_KEY_QUERY = "query";
-
- private static final String ACTIVITY_HELP_CONTEXT = "search";
-
- private boolean mTraceStartUp;
- // Measures time from for last onCreate()/onNewIntent() call.
- private LatencyTracker mStartLatencyTracker;
- // Measures time spent inside onCreate()
- private LatencyTracker mOnCreateTracker;
- private int mOnCreateLatency;
- // Whether QSB is starting. True between the calls to onCreate()/onNewIntent() and onResume().
- private boolean mStarting;
- // True if the user has taken some action, e.g. launching a search, voice search,
- // or suggestions, since QSB was last started.
- private boolean mTookAction;
-
- private SearchActivityView mSearchActivityView;
-
- private Source mSource;
-
- private Bundle mAppSearchData;
-
- private final Handler mHandler = new Handler();
- private final Runnable mUpdateSuggestionsTask = new Runnable() {
- @Override
- public void run() {
- updateSuggestions();
- }
- };
-
- private final Runnable mShowInputMethodTask = new Runnable() {
- @Override
- public void run() {
- mSearchActivityView.showInputMethodForQuery();
- }
- };
-
- private OnDestroyListener mDestroyListener;
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- mTraceStartUp = getIntent().hasExtra(INTENT_EXTRA_TRACE_START_UP);
- if (mTraceStartUp) {
- String traceFile = new File(getDir("traces", 0), "qsb-start.trace").getAbsolutePath();
- Log.i(TAG, "Writing start-up trace to " + traceFile);
- Debug.startMethodTracing(traceFile);
- }
- recordStartTime();
- if (DBG) Log.d(TAG, "onCreate()");
- super.onCreate(savedInstanceState);
-
- // This forces the HTTP request to check the users domain to be
- // sent as early as possible.
- QsbApplication.get(this).getSearchBaseUrlHelper();
-
- mSource = QsbApplication.get(this).getGoogleSource();
-
- mSearchActivityView = setupContentView();
-
- if (getConfig().showScrollingResults()) {
- mSearchActivityView.setMaxPromotedResults(getConfig().getMaxPromotedResults());
- } else {
- mSearchActivityView.limitResultsToViewHeight();
- }
-
- mSearchActivityView.setSearchClickListener(new SearchActivityView.SearchClickListener() {
- @Override
- public boolean onSearchClicked(int method) {
- return SearchActivity.this.onSearchClicked(method);
- }
- });
-
- mSearchActivityView.setQueryListener(new SearchActivityView.QueryListener() {
- @Override
- public void onQueryChanged() {
- updateSuggestionsBuffered();
- }
- });
-
- mSearchActivityView.setSuggestionClickListener(new ClickHandler());
-
- mSearchActivityView.setVoiceSearchButtonClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onVoiceSearchClicked();
- }
- });
-
- View.OnClickListener finishOnClick = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- finish();
- }
- };
- mSearchActivityView.setExitClickListener(finishOnClick);
-
- // First get setup from intent
- Intent intent = getIntent();
- setupFromIntent(intent);
- // Then restore any saved instance state
- restoreInstanceState(savedInstanceState);
-
- // Do this at the end, to avoid updating the list view when setSource()
- // is called.
- mSearchActivityView.start();
-
- recordOnCreateDone();
- }
-
- protected SearchActivityView setupContentView() {
- setContentView(R.layout.search_activity);
- return (SearchActivityView) findViewById(R.id.search_activity_view);
- }
-
- protected SearchActivityView getSearchActivityView() {
- return mSearchActivityView;
- }
-
- @Override
- protected void onNewIntent(Intent intent) {
- if (DBG) Log.d(TAG, "onNewIntent()");
- recordStartTime();
- setIntent(intent);
- setupFromIntent(intent);
- }
-
- private void recordStartTime() {
- mStartLatencyTracker = new LatencyTracker();
- mOnCreateTracker = new LatencyTracker();
- mStarting = true;
- mTookAction = false;
- }
-
- private void recordOnCreateDone() {
- mOnCreateLatency = mOnCreateTracker.getLatency();
- }
-
- protected void restoreInstanceState(Bundle savedInstanceState) {
- if (savedInstanceState == null) return;
- String query = savedInstanceState.getString(INSTANCE_KEY_QUERY);
- setQuery(query, false);
- }
-
- @Override
- protected void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- // We don't save appSearchData, since we always get the value
- // from the intent and the user can't change it.
-
- outState.putString(INSTANCE_KEY_QUERY, getQuery());
- }
-
- private void setupFromIntent(Intent intent) {
- if (DBG) Log.d(TAG, "setupFromIntent(" + intent.toUri(0) + ")");
- String corpusName = getCorpusNameFromUri(intent.getData());
- String query = intent.getStringExtra(SearchManager.QUERY);
- Bundle appSearchData = intent.getBundleExtra(SearchManager.APP_DATA);
- boolean selectAll = intent.getBooleanExtra(SearchManager.EXTRA_SELECT_QUERY, false);
-
- setQuery(query, selectAll);
- mAppSearchData = appSearchData;
-
- }
-
- private String getCorpusNameFromUri(Uri uri) {
- if (uri == null) return null;
- if (!SCHEME_CORPUS.equals(uri.getScheme())) return null;
- return uri.getAuthority();
- }
-
- private QsbApplication getQsbApplication() {
- return QsbApplication.get(this);
- }
-
- private Config getConfig() {
- return getQsbApplication().getConfig();
- }
-
- protected SearchSettings getSettings() {
- return getQsbApplication().getSettings();
- }
-
- private SuggestionsProvider getSuggestionsProvider() {
- return getQsbApplication().getSuggestionsProvider();
- }
-
- private Logger getLogger() {
- return getQsbApplication().getLogger();
- }
-
- @VisibleForTesting
- public void setOnDestroyListener(OnDestroyListener l) {
- mDestroyListener = l;
- }
-
- @Override
- protected void onDestroy() {
- if (DBG) Log.d(TAG, "onDestroy()");
- mSearchActivityView.destroy();
- super.onDestroy();
- if (mDestroyListener != null) {
- mDestroyListener.onDestroyed();
- }
- }
-
- @Override
- protected void onStop() {
- if (DBG) Log.d(TAG, "onStop()");
- if (!mTookAction) {
- // TODO: This gets logged when starting other activities, e.g. by opening the search
- // settings, or clicking a notification in the status bar.
- // TODO we should log both sets of suggestions in 2-pane mode
- getLogger().logExit(getCurrentSuggestions(), getQuery().length());
- }
- // Close all open suggestion cursors. The query will be redone in onResume()
- // if we come back to this activity.
- mSearchActivityView.clearSuggestions();
- mSearchActivityView.onStop();
- super.onStop();
- }
-
- @Override
- protected void onPause() {
- if (DBG) Log.d(TAG, "onPause()");
- mSearchActivityView.onPause();
- super.onPause();
- }
-
- @Override
- protected void onRestart() {
- if (DBG) Log.d(TAG, "onRestart()");
- super.onRestart();
- }
-
- @Override
- protected void onResume() {
- if (DBG) Log.d(TAG, "onResume()");
- super.onResume();
- updateSuggestionsBuffered();
- mSearchActivityView.onResume();
- if (mTraceStartUp) Debug.stopMethodTracing();
- }
-
- @Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- // Since the menu items are dynamic, we recreate the menu every time.
- menu.clear();
- createMenuItems(menu, true);
- return true;
- }
-
- public void createMenuItems(Menu menu, boolean showDisabled) {
- getQsbApplication().getHelp().addHelpMenuItem(menu, ACTIVITY_HELP_CONTEXT);
- }
-
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- super.onWindowFocusChanged(hasFocus);
- if (hasFocus) {
- // Launch the IME after a bit
- mHandler.postDelayed(mShowInputMethodTask, 0);
- }
- }
-
- protected String getQuery() {
- return mSearchActivityView.getQuery();
- }
-
- protected void setQuery(String query, boolean selectAll) {
- mSearchActivityView.setQuery(query, selectAll);
- }
-
- /**
- * @return true if a search was performed as a result of this click, false otherwise.
- */
- protected boolean onSearchClicked(int method) {
- String query = CharMatcher.whitespace().trimAndCollapseFrom(getQuery(), ' ');
- if (DBG) Log.d(TAG, "Search clicked, query=" + query);
-
- // Don't do empty queries
- if (TextUtils.getTrimmedLength(query) == 0) return false;
-
- mTookAction = true;
-
- // Log search start
- getLogger().logSearch(method, query.length());
-
- // Start search
- startSearch(mSource, query);
- return true;
- }
-
- protected void startSearch(Source searchSource, String query) {
- Intent intent = searchSource.createSearchIntent(query, mAppSearchData);
- launchIntent(intent);
- }
-
- protected void onVoiceSearchClicked() {
- if (DBG) Log.d(TAG, "Voice Search clicked");
-
- mTookAction = true;
-
- // Log voice search start
- getLogger().logVoiceSearch();
-
- // Start voice search
- Intent intent = mSource.createVoiceSearchIntent(mAppSearchData);
- launchIntent(intent);
- }
-
- protected Source getSearchSource() {
- return mSource;
- }
-
- protected SuggestionCursor getCurrentSuggestions() {
- Suggestions suggestions = mSearchActivityView.getSuggestions();
- if (suggestions == null) {
- return null;
- }
- return suggestions.getResult();
- }
-
- protected SuggestionPosition getCurrentSuggestions(SuggestionsAdapter<?> adapter, long id) {
- SuggestionPosition pos = adapter.getSuggestion(id);
- if (pos == null) {
- return null;
- }
- SuggestionCursor suggestions = pos.getCursor();
- int position = pos.getPosition();
- if (suggestions == null) {
- return null;
- }
- int count = suggestions.getCount();
- if (position < 0 || position >= count) {
- Log.w(TAG, "Invalid suggestion position " + position + ", count = " + count);
- return null;
- }
- suggestions.moveTo(position);
- return pos;
- }
-
- protected void launchIntent(Intent intent) {
- if (DBG) Log.d(TAG, "launchIntent " + 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);
- }
- }
-
- private boolean launchSuggestion(SuggestionsAdapter<?> adapter, long id) {
- SuggestionPosition suggestion = getCurrentSuggestions(adapter, id);
- if (suggestion == null) return false;
-
- if (DBG) Log.d(TAG, "Launching suggestion " + id);
- mTookAction = true;
-
- // Log suggestion click
- getLogger().logSuggestionClick(id, suggestion.getCursor(),
- Logger.SUGGESTION_CLICK_TYPE_LAUNCH);
-
- // Launch intent
- launchSuggestion(suggestion.getCursor(), suggestion.getPosition());
-
- return true;
- }
-
- protected void launchSuggestion(SuggestionCursor suggestions, int position) {
- suggestions.moveTo(position);
- Intent intent = SuggestionUtils.getSuggestionIntent(suggestions, mAppSearchData);
- launchIntent(intent);
- }
-
- protected void refineSuggestion(SuggestionsAdapter<?> adapter, long id) {
- if (DBG) Log.d(TAG, "query refine clicked, pos " + id);
- SuggestionPosition suggestion = getCurrentSuggestions(adapter, id);
- if (suggestion == null) {
- return;
- }
- String query = suggestion.getSuggestionQuery();
- if (TextUtils.isEmpty(query)) {
- return;
- }
-
- // Log refine click
- getLogger().logSuggestionClick(id, suggestion.getCursor(),
- Logger.SUGGESTION_CLICK_TYPE_REFINE);
-
- // Put query + space in query text view
- String queryWithSpace = query + ' ';
- setQuery(queryWithSpace, false);
- updateSuggestions();
- mSearchActivityView.focusQueryTextView();
- }
-
- private void updateSuggestionsBuffered() {
- if (DBG) Log.d(TAG, "updateSuggestionsBuffered()");
- mHandler.removeCallbacks(mUpdateSuggestionsTask);
- long delay = getConfig().getTypingUpdateSuggestionsDelayMillis();
- mHandler.postDelayed(mUpdateSuggestionsTask, delay);
- }
-
- private void gotSuggestions(Suggestions suggestions) {
- if (mStarting) {
- mStarting = false;
- String source = getIntent().getStringExtra(Search.SOURCE);
- int latency = mStartLatencyTracker.getLatency();
- getLogger().logStart(mOnCreateLatency, latency, source);
- getQsbApplication().onStartupComplete();
- }
- }
-
- public void updateSuggestions() {
- if (DBG) Log.d(TAG, "updateSuggestions()");
- final String query = CharMatcher.whitespace().trimLeadingFrom(getQuery());
- updateSuggestions(query, mSource);
- }
-
- protected void updateSuggestions(String query, Source source) {
- if (DBG) Log.d(TAG, "updateSuggestions(\"" + query+"\"," + source + ")");
- Suggestions suggestions = getSuggestionsProvider().getSuggestions(
- query, source);
-
- // Log start latency if this is the first suggestions update
- gotSuggestions(suggestions);
-
- showSuggestions(suggestions);
- }
-
- protected void showSuggestions(Suggestions suggestions) {
- mSearchActivityView.setSuggestions(suggestions);
- }
-
- private class ClickHandler implements SuggestionClickListener {
-
- @Override
- public void onSuggestionClicked(SuggestionsAdapter<?> adapter, long id) {
- launchSuggestion(adapter, id);
- }
-
- @Override
- public void onSuggestionQueryRefineClicked(SuggestionsAdapter<?> adapter, long id) {
- refineSuggestion(adapter, id);
- }
- }
-
- public interface OnDestroyListener {
- void onDestroyed();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SearchSettings.java b/src/com/android/quicksearchbox/SearchSettings.java
deleted file mode 100644
index 7b1a8a9..0000000
--- a/src/com/android/quicksearchbox/SearchSettings.java
+++ /dev/null
@@ -1,55 +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;
-
-
-/**
- * Interface for search settings.
- *
- * NOTE: Currently, this is not used very widely, in most instances
- * implementers of this interface are passed around by class name.
- * Should this be deprecated ?
- */
-public interface SearchSettings {
-
- public void upgradeSettingsIfNeeded();
-
- /**
- * Informs our listeners about the updated settings data.
- */
- public void broadcastSettingsChanged();
-
- public int getNextVoiceSearchHintIndex(int size);
-
- public void resetVoiceSearchHintFirstSeenTime();
-
- public boolean haveVoiceSearchHintsExpired(int currentVoiceSearchVersion);
-
- /**
- * Determines whether google.com should be used as the base path
- * for all searches (as opposed to using its country specific variants).
- */
- public boolean shouldUseGoogleCom();
-
- public void setUseGoogleCom(boolean useGoogleCom);
-
- public long getSearchBaseDomainApplyTime();
-
- public String getSearchBaseDomain();
-
- public void setSearchBaseDomain(String searchBaseUrl);
-}
diff --git a/src/com/android/quicksearchbox/SearchSettingsImpl.java b/src/com/android/quicksearchbox/SearchSettingsImpl.java
deleted file mode 100644
index 1fc74ea..0000000
--- a/src/com/android/quicksearchbox/SearchSettingsImpl.java
+++ /dev/null
@@ -1,212 +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.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.util.Log;
-
-import com.android.common.SharedPreferencesCompat;
-
-/**
- * Manages user settings.
- */
-public class SearchSettingsImpl implements SearchSettings {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SearchSettingsImpl";
-
- // Name of the preferences file used to store search preference
- public static final String PREFERENCES_NAME = "SearchSettings";
-
- /**
- * Preference key used for storing the index of the next voice search hint to show.
- */
- private static final String NEXT_VOICE_SEARCH_HINT_INDEX_PREF = "next_voice_search_hint";
-
- /**
- * Preference key used to store the time at which the first voice search hint was displayed.
- */
- private static final String FIRST_VOICE_HINT_DISPLAY_TIME = "first_voice_search_hint_time";
-
- /**
- * Preference key for the version of voice search we last got hints from.
- */
- private static final String LAST_SEEN_VOICE_SEARCH_VERSION = "voice_search_version";
-
- /**
- * Preference key for storing whether searches always go to google.com. Public
- * so that it can be used by PreferenceControllers.
- */
- public static final String USE_GOOGLE_COM_PREF = "use_google_com";
-
- /**
- * Preference key for the base search URL. This value is normally set by
- * a SearchBaseUrlHelper instance. Public so classes can listen to changes
- * on this key.
- */
- public static final String SEARCH_BASE_DOMAIN_PREF = "search_base_domain";
-
- /**
- * This is the time at which the base URL was stored, and is set using
- * @link{System.currentTimeMillis()}.
- */
- private static final String SEARCH_BASE_DOMAIN_APPLY_TIME = "search_base_domain_apply_time";
-
- private final Context mContext;
-
- private final Config mConfig;
-
- public SearchSettingsImpl(Context context, Config config) {
- mContext = context;
- mConfig = config;
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- protected Config getConfig() {
- return mConfig;
- }
-
- @Override
- public void upgradeSettingsIfNeeded() {
- }
-
- public SharedPreferences getSearchPreferences() {
- return getContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
- }
-
- protected void storeBoolean(String name, boolean value) {
- SharedPreferencesCompat.apply(getSearchPreferences().edit().putBoolean(name, value));
- }
-
- protected void storeInt(String name, int value) {
- SharedPreferencesCompat.apply(getSearchPreferences().edit().putInt(name, value));
- }
-
- protected void storeLong(String name, long value) {
- SharedPreferencesCompat.apply(getSearchPreferences().edit().putLong(name, value));
- }
-
- protected void storeString(String name, String value) {
- SharedPreferencesCompat.apply(getSearchPreferences().edit().putString(name, value));
- }
-
- protected void removePref(String name) {
- SharedPreferencesCompat.apply(getSearchPreferences().edit().remove(name));
- }
-
- /**
- * Informs our listeners about the updated settings data.
- */
- @Override
- public void broadcastSettingsChanged() {
- // We use a message broadcast since the listeners could be in multiple processes.
- Intent intent = new Intent(SearchManager.INTENT_ACTION_SEARCH_SETTINGS_CHANGED);
- Log.i(TAG, "Broadcasting: " + intent);
- getContext().sendBroadcast(intent);
- }
-
- @Override
- public int getNextVoiceSearchHintIndex(int size) {
- int i = getAndIncrementIntPreference(getSearchPreferences(),
- NEXT_VOICE_SEARCH_HINT_INDEX_PREF);
- return i % size;
- }
-
- // TODO: Could this be made atomic to avoid races?
- private int getAndIncrementIntPreference(SharedPreferences prefs, String name) {
- int i = prefs.getInt(name, 0);
- storeInt(name, i + 1);
- return i;
- }
-
- @Override
- public void resetVoiceSearchHintFirstSeenTime() {
- storeLong(FIRST_VOICE_HINT_DISPLAY_TIME, System.currentTimeMillis());
- }
-
- @Override
- public boolean haveVoiceSearchHintsExpired(int currentVoiceSearchVersion) {
- SharedPreferences prefs = getSearchPreferences();
-
- if (currentVoiceSearchVersion != 0) {
- long currentTime = System.currentTimeMillis();
- int lastVoiceSearchVersion = prefs.getInt(LAST_SEEN_VOICE_SEARCH_VERSION, 0);
- long firstHintTime = prefs.getLong(FIRST_VOICE_HINT_DISPLAY_TIME, 0);
- if (firstHintTime == 0 || currentVoiceSearchVersion != lastVoiceSearchVersion) {
- SharedPreferencesCompat.apply(prefs.edit()
- .putInt(LAST_SEEN_VOICE_SEARCH_VERSION, currentVoiceSearchVersion)
- .putLong(FIRST_VOICE_HINT_DISPLAY_TIME, currentTime));
- firstHintTime = currentTime;
- }
- if (currentTime - firstHintTime > getConfig().getVoiceSearchHintActivePeriod()) {
- if (DBG) Log.d(TAG, "Voice seach hint period expired; not showing hints.");
- return true;
- } else {
- return false;
- }
- } else {
- if (DBG) Log.d(TAG, "Could not determine voice search version; not showing hints.");
- return true;
- }
- }
-
- /**
- * @return true if user searches should always be based at google.com, false
- * otherwise.
- */
- @Override
- public boolean shouldUseGoogleCom() {
- // Note that this preserves the old behaviour of using google.com
- // for searches, with the gl= parameter set.
- return getSearchPreferences().getBoolean(USE_GOOGLE_COM_PREF, true);
- }
-
- @Override
- public void setUseGoogleCom(boolean useGoogleCom) {
- storeBoolean(USE_GOOGLE_COM_PREF, useGoogleCom);
- }
-
- @Override
- public long getSearchBaseDomainApplyTime() {
- return getSearchPreferences().getLong(SEARCH_BASE_DOMAIN_APPLY_TIME, -1);
- }
-
- @Override
- public String getSearchBaseDomain() {
- // Note that the only time this will return null is on the first run
- // of the app, or when settings have been cleared. Callers should
- // ideally check that getSearchBaseDomainApplyTime() is not -1 before
- // calling this function.
- return getSearchPreferences().getString(SEARCH_BASE_DOMAIN_PREF, null);
- }
-
- @Override
- public void setSearchBaseDomain(String searchBaseUrl) {
- Editor sharedPrefEditor = getSearchPreferences().edit();
- sharedPrefEditor.putString(SEARCH_BASE_DOMAIN_PREF, searchBaseUrl);
- sharedPrefEditor.putLong(SEARCH_BASE_DOMAIN_APPLY_TIME, System.currentTimeMillis());
-
- SharedPreferencesCompat.apply(sharedPrefEditor);
- }
-}
diff --git a/src/com/android/quicksearchbox/SearchWidgetProvider.java b/src/com/android/quicksearchbox/SearchWidgetProvider.java
deleted file mode 100644
index fdd8cf3..0000000
--- a/src/com/android/quicksearchbox/SearchWidgetProvider.java
+++ /dev/null
@@ -1,187 +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 com.android.common.Search;
-import com.android.common.speech.Recognition;
-import com.android.quicksearchbox.util.Util;
-
-import android.app.Activity;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.app.SearchManager;
-import android.appwidget.AppWidgetManager;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.Typeface;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.speech.RecognizerIntent;
-import android.text.Annotation;
-import android.text.SpannableStringBuilder;
-import android.text.TextUtils;
-import android.text.style.StyleSpan;
-import android.util.Log;
-import android.view.View;
-import android.widget.RemoteViews;
-
-import java.util.ArrayList;
-import java.util.Random;
-
-/**
- * Search widget provider.
- *
- */
-public class SearchWidgetProvider extends BroadcastReceiver {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SearchWidgetProvider";
-
- /**
- * The {@link Search#SOURCE} value used when starting searches from the search widget.
- */
- private static final String WIDGET_SEARCH_SOURCE = "launcher-widget";
-
- @Override
- public void onReceive(Context context, Intent intent) {
- if (DBG) Log.d(TAG, "onReceive(" + intent.toUri(0) + ")");
- String action = intent.getAction();
- if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) {
- // nothing needs doing
- } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
- updateSearchWidgets(context);
- } else {
- if (DBG) Log.d(TAG, "Unhandled intent action=" + action);
- }
- }
-
- private static SearchWidgetState[] getSearchWidgetStates(Context context) {
- AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
- int[] appWidgetIds = appWidgetManager.getAppWidgetIds(myComponentName(context));
- SearchWidgetState[] states = new SearchWidgetState[appWidgetIds.length];
- for (int i = 0; i<appWidgetIds.length; ++i) {
- states[i] = getSearchWidgetState(context, appWidgetIds[i]);
- }
- return states;
- }
-
-
- /**
- * Updates all search widgets.
- */
- public static void updateSearchWidgets(Context context) {
- if (DBG) Log.d(TAG, "updateSearchWidgets");
- SearchWidgetState[] states = getSearchWidgetStates(context);
-
- for (SearchWidgetState state : states) {
- state.updateWidget(context, AppWidgetManager.getInstance(context));
- }
- }
-
- /**
- * Gets the component name of this search widget provider.
- */
- private static ComponentName myComponentName(Context context) {
- String pkg = context.getPackageName();
- String cls = pkg + ".SearchWidgetProvider";
- return new ComponentName(pkg, cls);
- }
-
- private static Intent createQsbActivityIntent(Context context, String action,
- Bundle widgetAppData) {
- Intent qsbIntent = new Intent(action);
- qsbIntent.setPackage(context.getPackageName());
- qsbIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
- | Intent.FLAG_ACTIVITY_CLEAR_TOP
- | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
- qsbIntent.putExtra(SearchManager.APP_DATA, widgetAppData);
- return qsbIntent;
- }
-
- private static SearchWidgetState getSearchWidgetState(Context context, int appWidgetId) {
- if (DBG) Log.d(TAG, "Creating appwidget state " + appWidgetId);
- SearchWidgetState state = new SearchWidgetState(appWidgetId);
-
- Bundle widgetAppData = new Bundle();
- widgetAppData.putString(Search.SOURCE, WIDGET_SEARCH_SOURCE);
-
- // Text field click
- Intent qsbIntent = createQsbActivityIntent(
- context,
- SearchManager.INTENT_ACTION_GLOBAL_SEARCH,
- widgetAppData);
- state.setQueryTextViewIntent(qsbIntent);
-
- // Voice search button
- Intent voiceSearchIntent = getVoiceSearchIntent(context, widgetAppData);
- state.setVoiceSearchIntent(voiceSearchIntent);
-
- return state;
- }
-
- private static Intent getVoiceSearchIntent(Context context, Bundle widgetAppData) {
- VoiceSearch voiceSearch = QsbApplication.get(context).getVoiceSearch();
- return voiceSearch.createVoiceWebSearchIntent(widgetAppData);
- }
-
- private static class SearchWidgetState {
- private final int mAppWidgetId;
- private Intent mQueryTextViewIntent;
- private Intent mVoiceSearchIntent;
-
- public SearchWidgetState(int appWidgetId) {
- mAppWidgetId = appWidgetId;
- }
-
- public void setQueryTextViewIntent(Intent queryTextViewIntent) {
- mQueryTextViewIntent = queryTextViewIntent;
- }
-
- public void setVoiceSearchIntent(Intent voiceSearchIntent) {
- mVoiceSearchIntent = voiceSearchIntent;
- }
-
- public void updateWidget(Context context,AppWidgetManager appWidgetMgr) {
- if (DBG) Log.d(TAG, "Updating appwidget " + mAppWidgetId);
- RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.search_widget);
-
- setOnClickActivityIntent(context, views, R.id.search_widget_text,
- mQueryTextViewIntent);
- // Voice Search button
- if (mVoiceSearchIntent != null) {
- setOnClickActivityIntent(context, views, R.id.search_widget_voice_btn,
- mVoiceSearchIntent);
- views.setViewVisibility(R.id.search_widget_voice_btn, View.VISIBLE);
- } else {
- views.setViewVisibility(R.id.search_widget_voice_btn, View.GONE);
- }
-
- appWidgetMgr.updateAppWidget(mAppWidgetId, views);
- }
-
- private void setOnClickActivityIntent(Context context, RemoteViews views, int viewId,
- Intent intent) {
- intent.setPackage(context.getPackageName());
- PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
- views.setOnClickPendingIntent(viewId, pendingIntent);
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/Source.java b/src/com/android/quicksearchbox/Source.java
deleted file mode 100644
index 680f415..0000000
--- a/src/com/android/quicksearchbox/Source.java
+++ /dev/null
@@ -1,149 +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 com.android.quicksearchbox.util.NowOrLater;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Bundle;
-
-/**
- * Interface for suggestion sources.
- *
- */
-public interface Source extends SuggestionCursorProvider<SourceResult> {
-
- /**
- * Gets the name activity that intents from this source are sent to.
- */
- ComponentName getIntentComponent();
-
- /**
- * Gets the suggestion URI for getting suggestions from this Source.
- */
- String getSuggestUri();
-
- /**
- * Gets the localized, human-readable label for this source.
- */
- CharSequence getLabel();
-
- /**
- * Gets the icon for this suggestion source.
- */
- Drawable getSourceIcon();
-
- /**
- * Gets the icon URI for this suggestion source.
- */
- Uri getSourceIconUri();
-
- /**
- * Gets an icon from this suggestion source.
- *
- * @param drawableId Resource ID or URI.
- */
- NowOrLater<Drawable> getIcon(String drawableId);
-
- /**
- * Gets the URI for an icon form this suggestion source.
- *
- * @param drawableId Resource ID or URI.
- */
- Uri getIconUri(String drawableId);
-
- /**
- * Gets the search hint text for this suggestion source.
- */
- CharSequence getHint();
-
- /**
- * Gets the description to use for this source in system search settings.
- */
- CharSequence getSettingsDescription();
-
- /**
- *
- * Note: this does not guarantee that this source will be queried for queries of
- * this length or longer, only that it will not be queried for anything shorter.
- *
- * @return The minimum number of characters needed to trigger this source.
- */
- int getQueryThreshold();
-
- /**
- * Indicates whether a source should be invoked for supersets of queries it has returned zero
- * results for in the past. For example, if a source returned zero results for "bo", it would
- * be ignored for "bob".
- *
- * If set to <code>false</code>, this source will only be ignored for a single session; the next
- * time the search dialog is brought up, all sources will be queried.
- *
- * @return <code>true</code> if this source should be queried after returning no results.
- */
- boolean queryAfterZeroResults();
-
- boolean voiceSearchEnabled();
-
- /**
- * Whether this source should be included in the blended All mode. The source must
- * also be enabled to be included in All.
- */
- boolean includeInAll();
-
- Intent createSearchIntent(String query, Bundle appData);
-
- 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.
- * @return The suggestion results.
- */
- @Override
- SourceResult getSuggestions(String query, int queryLimit);
-
- /**
- * Gets the default intent action for suggestions from this source.
- *
- * @return The default intent action, or {@code null}.
- */
- String getDefaultIntentAction();
-
- /**
- * Gets the default intent data for suggestions from this source.
- *
- * @return The default intent data, or {@code null}.
- */
- String getDefaultIntentData();
-
- /**
- * Gets the root source, if this source is a wrapper around another. Otherwise, returns this
- * source.
- */
- Source getRoot();
-
-}
diff --git a/src/com/android/quicksearchbox/SourceResult.java b/src/com/android/quicksearchbox/SourceResult.java
deleted file mode 100644
index 20ea48f..0000000
--- a/src/com/android/quicksearchbox/SourceResult.java
+++ /dev/null
@@ -1,26 +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;
-
-/**
- * The result of getting suggestions from a single source.
- */
-public interface SourceResult extends SuggestionCursor {
-
- Source getSource();
-
-}
diff --git a/src/com/android/quicksearchbox/Suggestion.java b/src/com/android/quicksearchbox/Suggestion.java
deleted file mode 100644
index 81f5578..0000000
--- a/src/com/android/quicksearchbox/Suggestion.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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.content.ComponentName;
-
-/**
- * Interface for individual suggestions.
- */
-public interface Suggestion {
-
- /**
- * Gets the source that produced the current suggestion.
- */
- Source getSuggestionSource();
-
- /**
- * Gets the shortcut ID of the current suggestion.
- */
- String getShortcutId();
-
- /**
- * Whether to show a spinner while refreshing this shortcut.
- */
- boolean isSpinnerWhileRefreshing();
-
- /**
- * Gets the format of the text returned by {@link #getSuggestionText1()}
- * and {@link #getSuggestionText2()}.
- *
- * @return {@code null} or "html"
- */
- String getSuggestionFormat();
-
- /**
- * Gets the first text line for the current suggestion.
- */
- String getSuggestionText1();
-
- /**
- * Gets the second text line for the current suggestion.
- */
- String getSuggestionText2();
-
- /**
- * Gets the second text line URL for the current suggestion.
- */
- String getSuggestionText2Url();
-
- /**
- * Gets the left-hand-side icon for the current suggestion.
- *
- * @return A string that can be passed to {@link Source#getIcon(String)}.
- */
- String getSuggestionIcon1();
-
- /**
- * Gets the right-hand-side icon for the current suggestion.
- *
- * @return A string that can be passed to {@link Source#getIcon(String)}.
- */
- String getSuggestionIcon2();
-
- /**
- * Gets the intent action for the current suggestion.
- */
- String getSuggestionIntentAction();
-
- /**
- * Gets the name of the activity that the intent for the current suggestion will be sent to.
- */
- ComponentName getSuggestionIntentComponent();
-
- /**
- * Gets the extra data associated with this suggestion's intent.
- */
- String getSuggestionIntentExtraData();
-
- /**
- * Gets the data associated with this suggestion's intent.
- */
- String getSuggestionIntentDataString();
-
- /**
- * Gets the query associated with this suggestion's intent.
- */
- String getSuggestionQuery();
-
- /**
- * Gets the suggestion log type for the current suggestion. This is logged together
- * with the value returned from {@link Source#getName()}.
- * The value is source-specific. Most sources return {@code null}.
- */
- String getSuggestionLogType();
-
- /**
- * Checks if this suggestion is a shortcut.
- */
- boolean isSuggestionShortcut();
-
- /**
- * Checks if this is a web search suggestion.
- */
- boolean isWebSearchSuggestion();
-
- /**
- * Checks whether this suggestion comes from the user's search history.
- */
- boolean isHistorySuggestion();
-
- /**
- * Returns any extras associated with this suggestion, or {@code null} if there are none.
- */
- SuggestionExtras getExtras();
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionCursor.java b/src/com/android/quicksearchbox/SuggestionCursor.java
deleted file mode 100644
index 04d53c8..0000000
--- a/src/com/android/quicksearchbox/SuggestionCursor.java
+++ /dev/null
@@ -1,86 +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 com.android.quicksearchbox.util.QuietlyCloseable;
-
-import android.database.DataSetObserver;
-
-import java.util.Collection;
-
-/**
- * A sequence of suggestions, with a current position.
- */
-public interface SuggestionCursor extends Suggestion, QuietlyCloseable {
-
- /**
- * Gets the query that the user typed to get this suggestion.
- */
- String getUserQuery();
-
- /**
- * Gets the number of suggestions in this result.
- *
- * @return The number of suggestions, or {@code 0} if this result represents a failed query.
- */
- int getCount();
-
- /**
- * Moves to a given suggestion.
- *
- * @param pos The position to move to.
- * @throws IndexOutOfBoundsException if {@code pos < 0} or {@code pos >= getCount()}.
- */
- void moveTo(int pos);
-
- /**
- * Moves to the next suggestion, if there is one.
- *
- * @return {@code false} if there is no next suggestion.
- */
- boolean moveToNext();
-
- /**
- * Gets the current position within the cursor.
- */
- int getPosition();
-
- /**
- * Frees any resources used by this cursor.
- */
- @Override
- void close();
-
- /**
- * Register an observer that is called when changes happen to this data set.
- *
- * @param observer gets notified when the data set changes.
- */
- void registerDataSetObserver(DataSetObserver observer);
-
- /**
- * Unregister an observer that has previously been registered with
- * {@link #registerDataSetObserver(DataSetObserver)}
- *
- * @param observer the observer to unregister.
- */
- void unregisterDataSetObserver(DataSetObserver observer);
-
- /**
- * Return the extra columns present in this cursor, or null if none exist.
- */
- Collection<String> getExtraColumns();
-}
diff --git a/src/com/android/quicksearchbox/SuggestionCursorBackedCursor.java b/src/com/android/quicksearchbox/SuggestionCursorBackedCursor.java
deleted file mode 100644
index 7e929c5..0000000
--- a/src/com/android/quicksearchbox/SuggestionCursorBackedCursor.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * 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.database.AbstractCursor;
-import android.database.CursorIndexOutOfBoundsException;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-
-public class SuggestionCursorBackedCursor extends AbstractCursor {
-
- // This array also used in CursorBackedSuggestionExtras to avoid duplication.
- public static final String[] COLUMNS = {
- "_id", // 0, This will contain the row number. CursorAdapter, used by SuggestionsAdapter,
- // used by SearchDialog, expects an _id column.
- SearchManager.SUGGEST_COLUMN_TEXT_1, // 1
- SearchManager.SUGGEST_COLUMN_TEXT_2, // 2
- SearchManager.SUGGEST_COLUMN_TEXT_2_URL, // 3
- SearchManager.SUGGEST_COLUMN_ICON_1, // 4
- SearchManager.SUGGEST_COLUMN_ICON_2, // 5
- SearchManager.SUGGEST_COLUMN_INTENT_ACTION, // 6
- SearchManager.SUGGEST_COLUMN_INTENT_DATA, // 7
- SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, // 8
- SearchManager.SUGGEST_COLUMN_QUERY, // 9
- SearchManager.SUGGEST_COLUMN_FORMAT, // 10
- SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, // 11
- SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING, // 12
- };
-
- private static final int COLUMN_INDEX_ID = 0;
- private static final int COLUMN_INDEX_TEXT1 = 1;
- private static final int COLUMN_INDEX_TEXT2 = 2;
- private static final int COLUMN_INDEX_TEXT2_URL = 3;
- private static final int COLUMN_INDEX_ICON1 = 4;
- private static final int COLUMN_INDEX_ICON2 = 5;
- private static final int COLUMN_INDEX_INTENT_ACTION = 6;
- private static final int COLUMN_INDEX_INTENT_DATA = 7;
- private static final int COLUMN_INDEX_INTENT_EXTRA_DATA = 8;
- private static final int COLUMN_INDEX_QUERY = 9;
- private static final int COLUMN_INDEX_FORMAT = 10;
- private static final int COLUMN_INDEX_SHORTCUT_ID = 11;
- private static final int COLUMN_INDEX_SPINNER_WHILE_REFRESHING = 12;
-
- private final SuggestionCursor mCursor;
- private ArrayList<String> mExtraColumns;
-
- public SuggestionCursorBackedCursor(SuggestionCursor cursor) {
- mCursor = cursor;
- }
-
- @Override
- public void close() {
- super.close();
- mCursor.close();
- }
-
- @Override
- public String[] getColumnNames() {
- Collection<String> extraColumns = mCursor.getExtraColumns();
- if (extraColumns != null) {
- ArrayList<String> allColumns = new ArrayList<String>(COLUMNS.length +
- extraColumns.size());
- mExtraColumns = new ArrayList<String>(extraColumns);
- allColumns.addAll(Arrays.asList(COLUMNS));
- allColumns.addAll(mExtraColumns);
- return allColumns.toArray(new String[allColumns.size()]);
- } else {
- return COLUMNS;
- }
- }
-
- @Override
- public int getCount() {
- return mCursor.getCount();
- }
-
- private Suggestion get() {
- mCursor.moveTo(getPosition());
- return mCursor;
- }
-
- private String getExtra(int columnIdx) {
- int extraColumn = columnIdx - COLUMNS.length;
- SuggestionExtras extras = get().getExtras();
- if (extras != null) {
- return extras.getExtra(mExtraColumns.get(extraColumn));
- } else {
- return null;
- }
- }
-
- @Override
- public int getInt(int column) {
- if (column == COLUMN_INDEX_ID) {
- return getPosition();
- } else {
- try {
- return Integer.valueOf(getString(column));
- } catch (NumberFormatException e) {
- return 0;
- }
- }
- }
-
- @Override
- public String getString(int column) {
- if (column < COLUMNS.length) {
- switch (column) {
- case COLUMN_INDEX_ID:
- return String.valueOf(getPosition());
- case COLUMN_INDEX_TEXT1:
- return get().getSuggestionText1();
- case COLUMN_INDEX_TEXT2:
- return get().getSuggestionText2();
- case COLUMN_INDEX_TEXT2_URL:
- return get().getSuggestionText2Url();
- case COLUMN_INDEX_ICON1:
- return get().getSuggestionIcon1();
- case COLUMN_INDEX_ICON2:
- return get().getSuggestionIcon2();
- case COLUMN_INDEX_INTENT_ACTION:
- return get().getSuggestionIntentAction();
- case COLUMN_INDEX_INTENT_DATA:
- return get().getSuggestionIntentDataString();
- case COLUMN_INDEX_INTENT_EXTRA_DATA:
- return get().getSuggestionIntentExtraData();
- case COLUMN_INDEX_QUERY:
- return get().getSuggestionQuery();
- case COLUMN_INDEX_FORMAT:
- return get().getSuggestionFormat();
- case COLUMN_INDEX_SHORTCUT_ID:
- return get().getShortcutId();
- case COLUMN_INDEX_SPINNER_WHILE_REFRESHING:
- return String.valueOf(get().isSpinnerWhileRefreshing());
- default:
- throw new CursorIndexOutOfBoundsException("Requested column " + column
- + " of " + COLUMNS.length);
- }
- } else {
- return getExtra(column);
- }
- }
-
- @Override
- public long getLong(int column) {
- try {
- return Long.valueOf(getString(column));
- } catch (NumberFormatException e) {
- return 0;
- }
- }
-
- @Override
- public boolean isNull(int column) {
- return getString(column) == null;
- }
-
- @Override
- public short getShort(int column) {
- try {
- return Short.valueOf(getString(column));
- } catch (NumberFormatException e) {
- return 0;
- }
- }
-
- @Override
- public double getDouble(int column) {
- try {
- return Double.valueOf(getString(column));
- } catch (NumberFormatException e) {
- return 0;
- }
- }
-
- @Override
- public float getFloat(int column) {
- try {
- return Float.valueOf(getString(column));
- } catch (NumberFormatException e) {
- return 0;
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/SuggestionCursorProvider.java b/src/com/android/quicksearchbox/SuggestionCursorProvider.java
deleted file mode 100644
index 23109cd..0000000
--- a/src/com/android/quicksearchbox/SuggestionCursorProvider.java
+++ /dev/null
@@ -1,39 +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;
-
-
-/**
- * Interface for objects that can produce a SuggestionCursor given a query.
- */
-public interface SuggestionCursorProvider<C extends SuggestionCursor> {
-
- /**
- * Gets the name of the provider. This is used for logging and
- * to execute tasks on the queue for the provider.
- */
- String getName();
-
- /**
- * Gets suggestions from the provider.
- *
- * @param query The user query.
- * @param queryLimit An advisory maximum number of results that the source should return.
- * @return The suggestion results. Must not be {@code null}.
- */
- C getSuggestions(String query, int queryLimit);
-}
diff --git a/src/com/android/quicksearchbox/SuggestionCursorWrapper.java b/src/com/android/quicksearchbox/SuggestionCursorWrapper.java
deleted file mode 100644
index 83e74f4..0000000
--- a/src/com/android/quicksearchbox/SuggestionCursorWrapper.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.database.DataSetObserver;
-
-import java.util.Collection;
-
-/**
- * A suggestion cursor that delegates all methods to another SuggestionCursor.
- */
-public class SuggestionCursorWrapper extends AbstractSuggestionCursorWrapper {
-
- private final SuggestionCursor mCursor;
-
- public SuggestionCursorWrapper(String userQuery, SuggestionCursor cursor) {
- super(userQuery);
- mCursor = cursor;
- }
-
- public void close() {
- if (mCursor != null) {
- mCursor.close();
- }
- }
-
- public int getCount() {
- return mCursor == null ? 0 : mCursor.getCount();
- }
-
- public int getPosition() {
- return mCursor == null ? 0 : mCursor.getPosition();
- }
-
- public void moveTo(int pos) {
- if (mCursor != null) {
- mCursor.moveTo(pos);
- }
- }
-
- public boolean moveToNext() {
- if (mCursor != null) {
- return mCursor.moveToNext();
- } else {
- return false;
- }
- }
-
- public void registerDataSetObserver(DataSetObserver observer) {
- if (mCursor != null) {
- mCursor.registerDataSetObserver(observer);
- }
- }
-
- public void unregisterDataSetObserver(DataSetObserver observer) {
- if (mCursor != null) {
- mCursor.unregisterDataSetObserver(observer);
- }
- }
-
- @Override
- protected SuggestionCursor current() {
- return mCursor;
- }
-
- public Collection<String> getExtraColumns() {
- return mCursor.getExtraColumns();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionData.java b/src/com/android/quicksearchbox/SuggestionData.java
deleted file mode 100644
index 3cc835d..0000000
--- a/src/com/android/quicksearchbox/SuggestionData.java
+++ /dev/null
@@ -1,346 +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 com.google.common.annotations.VisibleForTesting;
-
-import android.content.ComponentName;
-import android.content.Intent;
-
-
-/**
- * Holds data for each suggest item including the display data and how to launch the result.
- * Used for passing from the provider to the suggest cursor.
- */
-public class SuggestionData implements Suggestion {
-
- private final Source mSource;
- private String mFormat;
- private String mText1;
- private String mText2;
- private String mText2Url;
- private String mIcon1;
- private String mIcon2;
- private String mShortcutId;
- private boolean mSpinnerWhileRefreshing;
- private String mIntentAction;
- private String mIntentData;
- private String mIntentExtraData;
- private String mSuggestionQuery;
- private String mLogType;
- private boolean mIsShortcut;
- private boolean mIsHistory;
- private SuggestionExtras mExtras;
-
- public SuggestionData(Source source) {
- mSource = source;
- }
-
- public Source getSuggestionSource() {
- return mSource;
- }
-
- public String getSuggestionFormat() {
- return mFormat;
- }
-
- public String getSuggestionText1() {
- return mText1;
- }
-
- public String getSuggestionText2() {
- return mText2;
- }
-
- public String getSuggestionText2Url() {
- return mText2Url;
- }
-
- public String getSuggestionIcon1() {
- return mIcon1;
- }
-
- public String getSuggestionIcon2() {
- return mIcon2;
- }
-
- public boolean isSpinnerWhileRefreshing() {
- return mSpinnerWhileRefreshing;
- }
-
- public String getIntentExtraData() {
- return mIntentExtraData;
- }
-
- public String getShortcutId() {
- return mShortcutId;
- }
-
- public String getSuggestionIntentAction() {
- if (mIntentAction != null) return mIntentAction;
- return mSource.getDefaultIntentAction();
- }
-
- public ComponentName getSuggestionIntentComponent() {
- return mSource.getIntentComponent();
- }
-
- public String getSuggestionIntentDataString() {
- return mIntentData;
- }
-
- public String getSuggestionIntentExtraData() {
- return mIntentExtraData;
- }
-
- public String getSuggestionQuery() {
- return mSuggestionQuery;
- }
-
- public String getSuggestionLogType() {
- return mLogType;
- }
-
- public boolean isSuggestionShortcut() {
- return mIsShortcut;
- }
-
- public boolean isWebSearchSuggestion() {
- return Intent.ACTION_WEB_SEARCH.equals(getSuggestionIntentAction());
- }
-
- public boolean isHistorySuggestion() {
- return mIsHistory;
- }
-
- @VisibleForTesting
- public SuggestionData setFormat(String format) {
- mFormat = format;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setText1(String text1) {
- mText1 = text1;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setText2(String text2) {
- mText2 = text2;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setText2Url(String text2Url) {
- mText2Url = text2Url;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIcon1(String icon1) {
- mIcon1 = icon1;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIcon2(String icon2) {
- mIcon2 = icon2;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIntentAction(String intentAction) {
- mIntentAction = intentAction;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIntentData(String intentData) {
- mIntentData = intentData;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIntentExtraData(String intentExtraData) {
- mIntentExtraData = intentExtraData;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setSuggestionQuery(String suggestionQuery) {
- mSuggestionQuery = suggestionQuery;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setShortcutId(String shortcutId) {
- mShortcutId = shortcutId;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setSpinnerWhileRefreshing(boolean spinnerWhileRefreshing) {
- mSpinnerWhileRefreshing = spinnerWhileRefreshing;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setSuggestionLogType(String logType) {
- mLogType = logType;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIsShortcut(boolean isShortcut) {
- mIsShortcut = isShortcut;
- return this;
- }
-
- @VisibleForTesting
- public SuggestionData setIsHistory(boolean isHistory) {
- mIsHistory = isHistory;
- return this;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((mFormat == null) ? 0 : mFormat.hashCode());
- result = prime * result + ((mIcon1 == null) ? 0 : mIcon1.hashCode());
- result = prime * result + ((mIcon2 == null) ? 0 : mIcon2.hashCode());
- result = prime * result + ((mIntentAction == null) ? 0 : mIntentAction.hashCode());
- result = prime * result + ((mIntentData == null) ? 0 : mIntentData.hashCode());
- result = prime * result + ((mIntentExtraData == null) ? 0 : mIntentExtraData.hashCode());
- result = prime * result + ((mLogType == null) ? 0 : mLogType.hashCode());
- result = prime * result + ((mShortcutId == null) ? 0 : mShortcutId.hashCode());
- result = prime * result + ((mSource == null) ? 0 : mSource.hashCode());
- result = prime * result + (mSpinnerWhileRefreshing ? 1231 : 1237);
- result = prime * result + ((mSuggestionQuery == null) ? 0 : mSuggestionQuery.hashCode());
- result = prime * result + ((mText1 == null) ? 0 : mText1.hashCode());
- result = prime * result + ((mText2 == null) ? 0 : mText2.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- SuggestionData other = (SuggestionData)obj;
- if (mFormat == null) {
- if (other.mFormat != null)
- return false;
- } else if (!mFormat.equals(other.mFormat))
- return false;
- if (mIcon1 == null) {
- if (other.mIcon1 != null)
- return false;
- } else if (!mIcon1.equals(other.mIcon1))
- return false;
- if (mIcon2 == null) {
- if (other.mIcon2 != null)
- return false;
- } else if (!mIcon2.equals(other.mIcon2))
- return false;
- if (mIntentAction == null) {
- if (other.mIntentAction != null)
- return false;
- } else if (!mIntentAction.equals(other.mIntentAction))
- return false;
- if (mIntentData == null) {
- if (other.mIntentData != null)
- return false;
- } else if (!mIntentData.equals(other.mIntentData))
- return false;
- if (mIntentExtraData == null) {
- if (other.mIntentExtraData != null)
- return false;
- } else if (!mIntentExtraData.equals(other.mIntentExtraData))
- return false;
- if (mLogType == null) {
- if (other.mLogType != null)
- return false;
- } else if (!mLogType.equals(other.mLogType))
- return false;
- if (mShortcutId == null) {
- if (other.mShortcutId != null)
- return false;
- } else if (!mShortcutId.equals(other.mShortcutId))
- return false;
- if (mSource == null) {
- if (other.mSource != null)
- return false;
- } else if (!mSource.equals(other.mSource))
- return false;
- if (mSpinnerWhileRefreshing != other.mSpinnerWhileRefreshing)
- return false;
- if (mSuggestionQuery == null) {
- if (other.mSuggestionQuery != null)
- return false;
- } else if (!mSuggestionQuery.equals(other.mSuggestionQuery))
- return false;
- if (mText1 == null) {
- if (other.mText1 != null)
- return false;
- } else if (!mText1.equals(other.mText1))
- return false;
- if (mText2 == null) {
- if (other.mText2 != null)
- return false;
- } else if (!mText2.equals(other.mText2))
- return false;
- return true;
- }
-
- /**
- * Returns a string representation of the contents of this SuggestionData,
- * for debugging purposes.
- */
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder("SuggestionData(");
- appendField(builder, "source", mSource.getName());
- appendField(builder, "text1", mText1);
- appendField(builder, "intentAction", mIntentAction);
- appendField(builder, "intentData", mIntentData);
- appendField(builder, "query", mSuggestionQuery);
- appendField(builder, "shortcutid", mShortcutId);
- appendField(builder, "logtype", mLogType);
- return builder.toString();
- }
-
- private void appendField(StringBuilder builder, String name, String value) {
- if (value != null) {
- builder.append(",").append(name).append("=").append(value);
- }
- }
-
- @VisibleForTesting
- public void setExtras(SuggestionExtras extras) {
- mExtras = extras;
- }
-
- public SuggestionExtras getExtras() {
- return mExtras;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionExtras.java b/src/com/android/quicksearchbox/SuggestionExtras.java
deleted file mode 100644
index 263c808..0000000
--- a/src/com/android/quicksearchbox/SuggestionExtras.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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 org.json.JSONException;
-
-import java.util.Collection;
-
-/**
- * Extra data that can be attached to a suggestion.
- */
-public interface SuggestionExtras {
-
- /**
- * Return the names of custom columns present in these extras.
- */
- Collection<String> getExtraColumnNames();
-
- /**
- * @param columnName The column to get a value from.
- */
- String getExtra(String columnName);
-
- /**
- * Flatten these extras as a JSON object.
- */
- String toJsonString() throws JSONException;
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionFilter.java b/src/com/android/quicksearchbox/SuggestionFilter.java
deleted file mode 100644
index aaf0c70..0000000
--- a/src/com/android/quicksearchbox/SuggestionFilter.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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;
-
-/**
- * Interface for choosing which suggestions to include in a promoted list.
- */
-public interface SuggestionFilter {
- /**
- * Determines if a suggestion should be added to the promoted suggestion list.
- *
- * @param s The suggestion in question
- * @return true to include it in the results
- */
- boolean accept(Suggestion s);
-}
diff --git a/src/com/android/quicksearchbox/SuggestionFormatter.java b/src/com/android/quicksearchbox/SuggestionFormatter.java
deleted file mode 100644
index a6eab9a..0000000
--- a/src/com/android/quicksearchbox/SuggestionFormatter.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.text.Spannable;
-
-/**
- * Suggestion formatter interface. This is used to bold (or otherwise highlight) portions of a
- * suggestion which were not a part of the query.
- */
-public abstract class SuggestionFormatter {
-
- private final TextAppearanceFactory mSpanFactory;
-
- protected SuggestionFormatter(TextAppearanceFactory spanFactory) {
- mSpanFactory = spanFactory;
- }
-
- /**
- * Formats a suggestion for display in the UI.
- *
- * @param query the query as entered by the user
- * @param suggestion the suggestion
- * @return Formatted suggestion text.
- */
- public abstract CharSequence formatSuggestion(String query, String suggestion);
-
- protected void applyQueryTextStyle(Spannable text, int start, int end) {
- if (start == end) return;
- setSpans(text, start, end, mSpanFactory.createSuggestionQueryTextAppearance());
- }
-
- protected void applySuggestedTextStyle(Spannable text, int start, int end) {
- if (start == end) return;
- setSpans(text, start, end, mSpanFactory.createSuggestionSuggestedTextAppearance());
- }
-
- private void setSpans(Spannable text, int start, int end, Object[] spans) {
- for (Object span : spans) {
- text.setSpan(span, start, end, 0);
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionNonFormatter.java b/src/com/android/quicksearchbox/SuggestionNonFormatter.java
deleted file mode 100644
index d7dc0bd..0000000
--- a/src/com/android/quicksearchbox/SuggestionNonFormatter.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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;
-
-
-/**
- * Basic SuggestionFormatter that does no formatting.
- */
-public class SuggestionNonFormatter extends SuggestionFormatter {
-
- public SuggestionNonFormatter(TextAppearanceFactory spanFactory) {
- super(spanFactory);
- }
-
- @Override
- public CharSequence formatSuggestion(String query, String suggestion) {
- return suggestion;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionPosition.java b/src/com/android/quicksearchbox/SuggestionPosition.java
deleted file mode 100644
index 8311978..0000000
--- a/src/com/android/quicksearchbox/SuggestionPosition.java
+++ /dev/null
@@ -1,61 +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;
-
-
-/**
- * A pointer to a suggestion in a {@link SuggestionCursor}.
- *
- */
-public class SuggestionPosition extends AbstractSuggestionWrapper {
-
- private final SuggestionCursor mCursor;
-
- private final int mPosition;
-
- public SuggestionPosition(SuggestionCursor cursor) {
- this(cursor, cursor.getPosition());
- }
-
- public SuggestionPosition(SuggestionCursor cursor, int suggestionPos) {
- mCursor = cursor;
- mPosition = suggestionPos;
- }
-
- public SuggestionCursor getCursor() {
- return mCursor;
- }
-
- /**
- * Gets the suggestion cursor, moved to point to the right suggestion.
- */
- @Override
- protected Suggestion current() {
- mCursor.moveTo(mPosition);
- return mCursor;
- }
-
- public int getPosition() {
- return mPosition;
- }
-
- @Override
- public String toString() {
- return mCursor + ":" + mPosition;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionUtils.java b/src/com/android/quicksearchbox/SuggestionUtils.java
deleted file mode 100644
index bf15053..0000000
--- a/src/com/android/quicksearchbox/SuggestionUtils.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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 com.google.common.annotations.VisibleForTesting;
-
-import android.app.SearchManager;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-
-/**
- * Some utilities for suggestions.
- */
-public class SuggestionUtils {
-
- private SuggestionUtils() {
- }
-
- public static Intent getSuggestionIntent(SuggestionCursor suggestion, Bundle appSearchData) {
- String action = suggestion.getSuggestionIntentAction();
-
- String data = suggestion.getSuggestionIntentDataString();
- String query = suggestion.getSuggestionQuery();
- String userQuery = suggestion.getUserQuery();
- String extraData = suggestion.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(suggestion.getSuggestionIntentComponent());
- return intent;
- }
-
- /**
- * Gets a unique key that identifies a suggestion. This is used to avoid
- * duplicate suggestions.
- */
- public static String getSuggestionKey(Suggestion suggestion) {
- String action = makeKeyComponent(suggestion.getSuggestionIntentAction());
- String data = makeKeyComponent(normalizeUrl(suggestion.getSuggestionIntentDataString()));
- String query = makeKeyComponent(normalizeUrl(suggestion.getSuggestionQuery()));
- // calculating accurate size of string builder avoids an allocation vs starting with
- // the default size and having to expand.
- int size = action.length() + 2 + data.length() + query.length();
- return new StringBuilder(size)
- .append(action)
- .append('#')
- .append(data)
- .append('#')
- .append(query)
- .toString();
- }
-
- private static String makeKeyComponent(String str) {
- return str == null ? "" : str;
- }
-
- private static final String SCHEME_SEPARATOR = "://";
- private static final String DEFAULT_SCHEME = "http";
-
- /**
- * Simple url normalization that adds http:// if no scheme exists, and
- * strips empty paths, e.g.,
- * www.google.com/ -> http://www.google.com. Used to prevent obvious
- * duplication of nav suggestions, bookmarks and urls entered by the user.
- */
- @VisibleForTesting
- static String normalizeUrl(String url) {
- String normalized;
- if (url != null) {
- int start;
- int schemePos = url.indexOf(SCHEME_SEPARATOR);
- if (schemePos == -1) {
- // no scheme - add the default
- normalized = DEFAULT_SCHEME + SCHEME_SEPARATOR + url;
- start = DEFAULT_SCHEME.length() + SCHEME_SEPARATOR.length();
- } else {
- normalized = url;
- start = schemePos + SCHEME_SEPARATOR.length();
- }
- int end = normalized.length();
- if (normalized.indexOf('/', start) == end - 1) {
- end--;
- }
- return normalized.substring(0, end);
- }
- return url;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/Suggestions.java b/src/com/android/quicksearchbox/Suggestions.java
deleted file mode 100644
index aca2a67..0000000
--- a/src/com/android/quicksearchbox/Suggestions.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * 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.database.DataSetObservable;
-import android.database.DataSetObserver;
-import android.util.Log;
-
-/**
- * Collects all corpus results for a single query.
- */
-public class Suggestions {
- private static final boolean DBG = false;
- private static final String TAG = "QSB.Suggestions";
-
- /** True if {@link Suggestions#close} has been called. */
- private boolean mClosed = false;
- protected final String mQuery;
-
- /**
- * The observers that want notifications of changes to the published suggestions.
- * This object may be accessed on any thread.
- */
- private final DataSetObservable mDataSetObservable = new DataSetObservable();
-
- private Source mSource;
-
- private SourceResult mResult;
-
- private int mRefCount = 0;
-
- private boolean mDone = false;
-
- public Suggestions(String query, Source source) {
- mQuery = query;
- mSource = source;
- }
-
- public void acquire() {
- mRefCount++;
- }
-
- public void release() {
- mRefCount--;
- if (mRefCount <= 0) {
- close();
- }
- }
-
- public Source getSource() {
- return mSource;
- }
-
- /**
- * Marks the suggestions set as complete, regardless of whether all corpora have
- * returned.
- */
- public void done() {
- mDone = true;
- }
-
- /**
- * Checks whether all sources have reported.
- * Must be called on the UI thread, or before this object is seen by the UI thread.
- */
- public boolean isDone() {
- return mDone || mResult != null;
- }
-
- /**
- * Adds a list of corpus results. Must be called on the UI thread, or before this
- * object is seen by the UI thread.
- */
- public void addResults(SourceResult result) {
- if (isClosed()) {
- result.close();
- return;
- }
-
- if (DBG) {
- Log.d(TAG, "addResults["+ hashCode() + "] source:" +
- result.getSource().getName() + " results:" + result.getCount());
- }
- if (!mQuery.equals(result.getUserQuery())) {
- throw new IllegalArgumentException("Got result for wrong query: "
- + mQuery + " != " + result.getUserQuery());
- }
- mResult = result;
- notifyDataSetChanged();
- }
-
- /**
- * Registers an observer that will be notified when the reported results or
- * the done status changes.
- */
- public void registerDataSetObserver(DataSetObserver observer) {
- if (mClosed) {
- throw new IllegalStateException("registerDataSetObserver() when closed");
- }
- mDataSetObservable.registerObserver(observer);
- }
-
-
- /**
- * Unregisters an observer.
- */
- public void unregisterDataSetObserver(DataSetObserver observer) {
- mDataSetObservable.unregisterObserver(observer);
- }
-
- /**
- * Calls {@link DataSetObserver#onChanged()} on all observers.
- */
- protected void notifyDataSetChanged() {
- if (DBG) Log.d(TAG, "notifyDataSetChanged()");
- mDataSetObservable.notifyChanged();
- }
-
- /**
- * Closes all the source results and unregisters all observers.
- */
- private void close() {
- if (DBG) Log.d(TAG, "close() [" + hashCode() + "]");
- if (mClosed) {
- throw new IllegalStateException("Double close()");
- }
- mClosed = true;
- mDataSetObservable.unregisterAll();
- if (mResult != null) {
- mResult.close();
- }
- mResult = null;
- }
-
- public boolean isClosed() {
- return mClosed;
- }
-
- @Override
- protected void finalize() {
- if (!mClosed) {
- Log.e(TAG, "LEAK! Finalized without being closed: Suggestions[" + getQuery() + "]");
- }
- }
-
- public String getQuery() {
- return mQuery;
- }
-
- /**
- * Gets the list of corpus results reported so far. Do not modify or hang on to
- * the returned iterator.
- */
- public SourceResult getResult() {
- return mResult;
- }
-
- public SourceResult getWebResult() {
- return mResult;
- }
-
- /**
- * Gets the number of source results.
- * Must be called on the UI thread, or before this object is seen by the UI thread.
- */
- public int getResultCount() {
- if (isClosed()) {
- throw new IllegalStateException("Called getSourceCount() when closed.");
- }
- return mResult == null ? 0 : mResult.getCount();
- }
-
- @Override
- public String toString() {
- return "Suggestions@" + hashCode() + "{source=" + mSource
- + ",getResultCount()=" + getResultCount() + "}";
- }
-
-}
diff --git a/src/com/android/quicksearchbox/SuggestionsProvider.java b/src/com/android/quicksearchbox/SuggestionsProvider.java
deleted file mode 100644
index 9196018..0000000
--- a/src/com/android/quicksearchbox/SuggestionsProvider.java
+++ /dev/null
@@ -1,34 +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;
-
-/**
- * Provides a set of suggestion results for a query..
- *
- */
-public interface SuggestionsProvider {
-
- /**
- * Gets suggestions for a query.
- *
- * @param query The query.
- * @param source The source to query. Must be non-null.
- */
- Suggestions getSuggestions(String query, Source source);
-
- void close();
-}
diff --git a/src/com/android/quicksearchbox/SuggestionsProviderImpl.java b/src/com/android/quicksearchbox/SuggestionsProviderImpl.java
deleted file mode 100644
index 76a9071..0000000
--- a/src/com/android/quicksearchbox/SuggestionsProviderImpl.java
+++ /dev/null
@@ -1,115 +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.os.Handler;
-import android.util.Log;
-
-import com.android.quicksearchbox.util.BatchingNamedTaskExecutor;
-import com.android.quicksearchbox.util.Consumer;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-import com.android.quicksearchbox.util.NoOpConsumer;
-
-/**
- * Suggestions provider implementation.
- *
- * The provider will only handle a single query at a time. If a new query comes
- * in, the old one is cancelled.
- */
-public class SuggestionsProviderImpl implements SuggestionsProvider {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SuggestionsProviderImpl";
-
- private final Config mConfig;
-
- private final NamedTaskExecutor mQueryExecutor;
-
- private final Handler mPublishThread;
-
- private final Logger mLogger;
-
- public SuggestionsProviderImpl(Config config,
- NamedTaskExecutor queryExecutor,
- Handler publishThread,
- Logger logger) {
- mConfig = config;
- mQueryExecutor = queryExecutor;
- mPublishThread = publishThread;
- mLogger = logger;
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public Suggestions getSuggestions(String query, Source sourceToQuery) {
- if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
- final Suggestions suggestions = new Suggestions(query, sourceToQuery);
- Log.i(TAG, "chars:" + query.length() + ",source:" + sourceToQuery);
-
- Consumer<SourceResult> receiver;
- if (shouldDisplayResults(query)) {
- receiver = new SuggestionCursorReceiver(suggestions);
- } else {
- receiver = new NoOpConsumer<SourceResult>();
- suggestions.done();
- }
-
- int maxResults = mConfig.getMaxResultsPerSource();
- QueryTask.startQuery(query, maxResults, sourceToQuery, mQueryExecutor,
- mPublishThread, receiver);
-
- return suggestions;
- }
-
- private boolean shouldDisplayResults(String query) {
- if (query.length() == 0 && !mConfig.showSuggestionsForZeroQuery()) {
- // Note that even though we don't display such results, it's
- // useful to run the query itself because it warms up the network
- // connection.
- return false;
- }
- return true;
- }
-
-
- private class SuggestionCursorReceiver implements Consumer<SourceResult> {
- private final Suggestions mSuggestions;
-
- public SuggestionCursorReceiver(Suggestions suggestions) {
- mSuggestions = suggestions;
- }
-
- @Override
- public boolean consume(SourceResult cursor) {
- if (DBG) {
- Log.d(TAG, "SuggestionCursorReceiver.consume(" + cursor + ") corpus=" +
- cursor.getSource() + " count = " + cursor.getCount());
- }
- // publish immediately
- if (DBG) Log.d(TAG, "Publishing results");
- mSuggestions.addResults(cursor);
- if (cursor != null && mLogger != null) {
- mLogger.logLatency(cursor);
- }
- return true;
- }
-
- }
-}
diff --git a/src/com/android/quicksearchbox/TextAppearanceFactory.java b/src/com/android/quicksearchbox/TextAppearanceFactory.java
deleted file mode 100644
index af950d9..0000000
--- a/src/com/android/quicksearchbox/TextAppearanceFactory.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.content.Context;
-import android.text.style.TextAppearanceSpan;
-
-/**
- * Factory class for text appearances.
- */
-public class TextAppearanceFactory {
- private final Context mContext;
-
- public TextAppearanceFactory(Context context) {
- mContext = context;
- }
-
- public Object[] createSuggestionQueryTextAppearance() {
- return new Object[]{
- new TextAppearanceSpan(mContext, R.style.SuggestionText1_Query)
- };
- }
-
- public Object[] createSuggestionSuggestedTextAppearance() {
- return new Object[]{
- new TextAppearanceSpan(mContext, R.style.SuggestionText1_Suggested)
- };
- }
-
-}
diff --git a/src/com/android/quicksearchbox/VoiceSearch.java b/src/com/android/quicksearchbox/VoiceSearch.java
deleted file mode 100644
index 674db96..0000000
--- a/src/com/android/quicksearchbox/VoiceSearch.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ComponentInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ResolveInfo;
-import android.os.Bundle;
-import android.speech.RecognizerIntent;
-import android.util.Log;
-
-/**
- * Voice Search integration.
- */
-public class VoiceSearch {
-
- private static final String TAG = "QSB.VoiceSearch";
-
- private final Context mContext;
-
- public VoiceSearch(Context context) {
- mContext = context;
- }
-
- protected Context getContext() {
- return mContext;
- }
-
- public boolean shouldShowVoiceSearch() {
- return isVoiceSearchAvailable();
- }
-
- protected Intent createVoiceSearchIntent() {
- return new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
- }
-
- private ResolveInfo getResolveInfo() {
- Intent intent = createVoiceSearchIntent();
- ResolveInfo ri = mContext.getPackageManager().
- resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
- return ri;
- }
-
- public boolean isVoiceSearchAvailable() {
- return getResolveInfo() != null;
- }
-
- public Intent createVoiceWebSearchIntent(Bundle appData) {
- if (!isVoiceSearchAvailable()) return null;
- Intent intent = createVoiceSearchIntent();
- 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;
- }
-
- /**
- * Create an intent to launch the voice search help screen, if any exists.
- * @return The intent, or null.
- */
- public Intent createVoiceSearchHelpIntent() {
- return null;
- }
-
- /**
- * Gets the {@code versionCode} of the currently installed voice search package.
- *
- * @return The {@code versionCode} of voiceSearch, or 0 if none is installed.
- */
- public int getVersion() {
- ResolveInfo ri = getResolveInfo();
- if (ri == null) return 0;
- ComponentInfo ci = ri.activityInfo != null ? ri.activityInfo : ri.serviceInfo;
- try {
- return getContext().getPackageManager().getPackageInfo(ci.packageName, 0).versionCode;
- } catch (NameNotFoundException e) {
- Log.e(TAG, "Cannot find voice search package " + ci.packageName, e);
- return 0;
- }
- }
-
- public ComponentName getComponent() {
- return createVoiceSearchIntent().resolveActivity(getContext().getPackageManager());
- }
-}
diff --git a/src/com/android/quicksearchbox/google/AbstractGoogleSource.java b/src/com/android/quicksearchbox/google/AbstractGoogleSource.java
deleted file mode 100644
index 2077777..0000000
--- a/src/com/android/quicksearchbox/google/AbstractGoogleSource.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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.google;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-
-import com.android.quicksearchbox.AbstractInternalSource;
-import com.android.quicksearchbox.CursorBackedSourceResult;
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-
-/**
- * Special source implementation for Google suggestions.
- */
-public abstract class AbstractGoogleSource extends AbstractInternalSource implements GoogleSource {
-
- /*
- * This name corresponds to what was used in previous version of quick search box. We use the
- * same name so that shortcuts continue to work after an upgrade. (It also makes logging more
- * consistent).
- */
- private static final String GOOGLE_SOURCE_NAME =
- "com.android.quicksearchbox/.google.GoogleSearch";
-
- public AbstractGoogleSource(Context context, Handler uiThread, NamedTaskExecutor iconLoader) {
- super(context, uiThread, iconLoader);
- }
-
- @Override
- public abstract ComponentName getIntentComponent();
-
- @Override
- public abstract SuggestionCursor refreshShortcut(String shortcutId, String extraData);
-
- /**
- * Called by QSB to get web suggestions for a query.
- */
- @Override
- public abstract SourceResult queryInternal(String query);
-
- /**
- * Called by external apps to get web suggestions for a query.
- */
- @Override
- public abstract SourceResult queryExternal(String query);
-
- @Override
- public Intent createVoiceSearchIntent(Bundle appData) {
- return createVoiceWebSearchIntent(appData);
- }
-
- @Override
- public String getDefaultIntentAction() {
- return Intent.ACTION_WEB_SEARCH;
- }
-
- @Override
- public CharSequence getHint() {
- return getContext().getString(R.string.google_search_hint);
- }
-
- @Override
- public CharSequence getLabel() {
- return getContext().getString(R.string.google_search_label);
- }
-
- @Override
- public String getName() {
- return GOOGLE_SOURCE_NAME;
- }
-
- @Override
- public CharSequence getSettingsDescription() {
- return getContext().getString(R.string.google_search_description);
- }
-
- @Override
- protected int getSourceIconResource() {
- return R.mipmap.google_icon;
- }
-
- @Override
- public SourceResult getSuggestions(String query, int queryLimit) {
- return emptyIfNull(queryInternal(query), query);
- }
-
- public SourceResult getSuggestionsExternal(String query) {
- return emptyIfNull(queryExternal(query), query);
- }
-
- private SourceResult emptyIfNull(SourceResult result, String query) {
- return result == null ? new CursorBackedSourceResult(this, query) : result;
- }
-
- @Override
- public boolean voiceSearchEnabled() {
- return true;
- }
-
- @Override
- public boolean includeInAll() {
- return true;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/google/AbstractGoogleSourceResult.java b/src/com/android/quicksearchbox/google/AbstractGoogleSourceResult.java
deleted file mode 100644
index 6eb8f9d..0000000
--- a/src/com/android/quicksearchbox/google/AbstractGoogleSourceResult.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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.google;
-
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Source;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionExtras;
-
-import android.content.ComponentName;
-import android.database.DataSetObserver;
-
-import java.util.Collection;
-
-public abstract class AbstractGoogleSourceResult implements SourceResult {
-
- private final Source mSource;
- private final String mUserQuery;
- private int mPos = 0;
-
- public AbstractGoogleSourceResult(Source source, String userQuery) {
- mSource = source;
- mUserQuery = userQuery;
- }
-
- public abstract int getCount();
-
- public abstract String getSuggestionQuery();
-
- public Source getSource() {
- return mSource;
- }
-
- public void close() {
- }
-
- public int getPosition() {
- return mPos;
- }
-
- public String getUserQuery() {
- return mUserQuery;
- }
-
- public void moveTo(int pos) {
- mPos = pos;
- }
-
- public boolean moveToNext() {
- int size = getCount();
- if (mPos >= size) {
- // Already past the end
- return false;
- }
- mPos++;
- return mPos < size;
- }
-
- public void registerDataSetObserver(DataSetObserver observer) {
- }
-
- public void unregisterDataSetObserver(DataSetObserver observer) {
- }
-
- public String getSuggestionText1() {
- return getSuggestionQuery();
- }
-
- public Source getSuggestionSource() {
- return mSource;
- }
-
- public boolean isSuggestionShortcut() {
- return false;
- }
-
- public String getShortcutId() {
- return null;
- }
-
- public String getSuggestionFormat() {
- return null;
- }
-
- public String getSuggestionIcon1() {
- return String.valueOf(R.drawable.magnifying_glass);
- }
-
- public String getSuggestionIcon2() {
- return null;
- }
-
- public String getSuggestionIntentAction() {
- return mSource.getDefaultIntentAction();
- }
-
- public ComponentName getSuggestionIntentComponent() {
- return mSource.getIntentComponent();
- }
-
- public String getSuggestionIntentDataString() {
- return null;
- }
-
- public String getSuggestionIntentExtraData() {
- return null;
- }
-
- public String getSuggestionLogType() {
- return null;
- }
-
- public String getSuggestionText2() {
- return null;
- }
-
- public String getSuggestionText2Url() {
- return null;
- }
-
- public boolean isSpinnerWhileRefreshing() {
- return false;
- }
-
- public boolean isWebSearchSuggestion() {
- return true;
- }
-
- public boolean isHistorySuggestion() {
- return false;
- }
-
- public SuggestionExtras getExtras() {
- return null;
- }
-
- public Collection<String> getExtraColumns() {
- return null;
- }
-}
diff --git a/src/com/android/quicksearchbox/google/GoogleSearch.java b/src/com/android/quicksearchbox/google/GoogleSearch.java
deleted file mode 100644
index 58755d8..0000000
--- a/src/com/android/quicksearchbox/google/GoogleSearch.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2008 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.google;
-
-import com.android.common.Search;
-import com.android.quicksearchbox.QsbApplication;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.app.SearchManager;
-import android.content.ActivityNotFoundException;
-import android.content.Context;
-import android.content.Intent;
-import android.location.Location;
-import android.net.Uri;
-import android.os.Bundle;
-import android.provider.Browser;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.Locale;
-
-/**
- * This class is purely here to get search queries and route them to
- * the global {@link Intent#ACTION_WEB_SEARCH}.
- */
-public class GoogleSearch extends Activity {
- private static final String TAG = "GoogleSearch";
- private static final boolean DBG = false;
-
- // Used to figure out which domain to base search requests
- // on.
- private SearchBaseUrlHelper mSearchDomainHelper;
-
- // "source" parameter for Google search requests from unknown sources (e.g. apps). This will get
- // prefixed with the string 'android-' before being sent on the wire.
- final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Intent intent = getIntent();
- String action = intent != null ? intent.getAction() : null;
-
- // This should probably be moved so as to
- // send out the request to /checksearchdomain as early as possible.
- mSearchDomainHelper = QsbApplication.get(this).getSearchBaseUrlHelper();
-
- if (Intent.ACTION_WEB_SEARCH.equals(action) || Intent.ACTION_SEARCH.equals(action)) {
- handleWebSearchIntent(intent);
- }
-
- finish();
- }
-
- /**
- * Construct the language code (hl= paramater) for the given locale.
- */
- public static String getLanguage(Locale locale) {
- String language = locale.getLanguage();
- StringBuilder hl = new StringBuilder(language);
- String country = locale.getCountry();
-
- if (!TextUtils.isEmpty(country) && useLangCountryHl(language, country)) {
- hl.append('-');
- hl.append(country);
- }
-
- if (DBG) Log.d(TAG, "language " + language + ", country " + country + " -> hl=" + hl);
- return hl.toString();
- }
-
- // TODO: This is a workaround for bug 3232296. When that is fixed, this method can be removed.
- private static boolean useLangCountryHl(String language, String country) {
- // lang-country is currently only supported for a small number of locales
- if ("en".equals(language)) {
- return "GB".equals(country);
- } else if ("zh".equals(language)) {
- return "CN".equals(country) || "TW".equals(country);
- } else if ("pt".equals(language)) {
- return "BR".equals(country) || "PT".equals(country);
- } else {
- return false;
- }
- }
-
- private void handleWebSearchIntent(Intent intent) {
- Intent launchUriIntent = createLaunchUriIntentFromSearchIntent(intent);
- PendingIntent pending =
- intent.getParcelableExtra(SearchManager.EXTRA_WEB_SEARCH_PENDINGINTENT);
- if (pending == null || !launchPendingIntent(pending, launchUriIntent)) {
- launchIntent(launchUriIntent);
- }
- }
-
- private Intent createLaunchUriIntentFromSearchIntent(Intent intent) {
- String query = intent.getStringExtra(SearchManager.QUERY);
- if (TextUtils.isEmpty(query)) {
- Log.w(TAG, "Got search intent with no query.");
- return null;
- }
-
- // If the caller specified a 'source' url parameter, use that and if not use default.
- Bundle appSearchData = intent.getBundleExtra(SearchManager.APP_DATA);
- String source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
- if (appSearchData != null) {
- source = appSearchData.getString(Search.SOURCE);
- }
-
- // The browser can pass along an application id which it uses to figure out which
- // window to place a new search into. So if this exists, we'll pass it back to
- // the browser. Otherwise, add our own package name as the application id, so that
- // the browser can organize all searches launched from this provider together.
- String applicationId = intent.getStringExtra(Browser.EXTRA_APPLICATION_ID);
- if (applicationId == null) {
- applicationId = getPackageName();
- }
-
- try {
- String searchUri = mSearchDomainHelper.getSearchBaseUrl()
- + "&source=android-" + source
- + "&q=" + URLEncoder.encode(query, "UTF-8");
- Intent launchUriIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(searchUri));
- launchUriIntent.putExtra(Browser.EXTRA_APPLICATION_ID, applicationId);
- launchUriIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- return launchUriIntent;
- } catch (UnsupportedEncodingException e) {
- Log.w(TAG, "Error", e);
- return null;
- }
-
- }
-
- private void launchIntent(Intent intent) {
- try {
- Log.i(TAG, "Launching intent: " + intent.toUri(0));
- startActivity(intent);
- } catch (ActivityNotFoundException ex) {
- Log.w(TAG, "No activity found to handle: " + intent);
- }
- }
-
- private boolean launchPendingIntent(PendingIntent pending, Intent fillIn) {
- try {
- pending.send(this, Activity.RESULT_OK, fillIn);
- return true;
- } catch (PendingIntent.CanceledException ex) {
- Log.i(TAG, "Pending intent cancelled: " + pending);
- return false;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/google/GoogleSource.java b/src/com/android/quicksearchbox/google/GoogleSource.java
deleted file mode 100644
index b566817..0000000
--- a/src/com/android/quicksearchbox/google/GoogleSource.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.google;
-
-import com.android.quicksearchbox.Source;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionCursor;
-
-/**
- * Special source interface for Google suggestions.
- */
-public interface GoogleSource extends Source {
-
- SuggestionCursor refreshShortcut(String shortcutId, String extraData);
-
- /**
- * Called by QSB to get web suggestions for a query.
- */
- SourceResult queryInternal(String query);
-
- /**
- * Called by external apps to get web suggestions for a query.
- */
- SourceResult queryExternal(String query);
-
-}
diff --git a/src/com/android/quicksearchbox/google/GoogleSuggestClient.java b/src/com/android/quicksearchbox/google/GoogleSuggestClient.java
deleted file mode 100644
index 51c5129..0000000
--- a/src/com/android/quicksearchbox/google/GoogleSuggestClient.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * 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.google;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.os.Build;
-import android.os.Handler;
-import android.text.TextUtils;
-import android.util.Log;
-
-import com.android.quicksearchbox.Config;
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Source;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.util.NamedTaskExecutor;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-
-import java.io.BufferedReader;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.HttpURLConnection;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.Locale;
-
-/**
- * Use network-based Google Suggests to provide search suggestions.
- */
-public class GoogleSuggestClient extends AbstractGoogleSource {
-
- private static final boolean DBG = false;
- private static final String LOG_TAG = "GoogleSearch";
-
- private static final String USER_AGENT = "Android/" + Build.VERSION.RELEASE;
- private String mSuggestUri;
-
- // TODO: this should be defined somewhere
- private static final String HTTP_TIMEOUT = "http.conn-manager.timeout";
-
- private final int mConnectTimeout;
-
- public GoogleSuggestClient(Context context, Handler uiThread,
- NamedTaskExecutor iconLoader, Config config) {
- super(context, uiThread, iconLoader);
-
- mConnectTimeout = config.getHttpConnectTimeout();
- // NOTE: Do not look up the resource here; Localization changes may not have completed
- // yet (e.g. we may still be reading the SIM card).
- mSuggestUri = null;
- }
-
- @Override
- public ComponentName getIntentComponent() {
- return new ComponentName(getContext(), GoogleSearch.class);
- }
-
- @Override
- public SourceResult queryInternal(String query) {
- return query(query);
- }
-
- @Override
- public SourceResult queryExternal(String query) {
- return query(query);
- }
-
- /**
- * Queries for a given search term and returns a cursor containing
- * suggestions ordered by best match.
- */
- private SourceResult query(String query) {
- if (TextUtils.isEmpty(query)) {
- return null;
- }
- if (!isNetworkConnected()) {
- Log.i(LOG_TAG, "Not connected to network.");
- return null;
- }
- HttpURLConnection connection = null;
- try {
- String encodedQuery = URLEncoder.encode(query, "UTF-8");
- if (mSuggestUri == null) {
- Locale l = Locale.getDefault();
- String language = GoogleSearch.getLanguage(l);
- mSuggestUri = getContext().getResources().getString(R.string.google_suggest_base,
- language);
- }
-
- String suggestUri = mSuggestUri + encodedQuery;
- if (DBG) Log.d(LOG_TAG, "Sending request: " + suggestUri);
- URL url = URI.create(suggestUri).toURL();
- connection = (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(mConnectTimeout);
- connection.setRequestProperty("User-Agent", USER_AGENT);
- connection.setRequestMethod("GET");
- connection.setDoInput(true);
- connection.connect();
- InputStream inputStream = connection.getInputStream();
- if (connection.getResponseCode() == 200) {
-
- /* Goto http://www.google.com/complete/search?json=true&q=foo
- * to see what the data format looks like. It's basically a json
- * array containing 4 other arrays. We only care about the middle
- * 2 which contain the suggestions and their popularity.
- */
- BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- sb.append(line).append("\n");
- }
- reader.close();
- JSONArray results = new JSONArray(sb.toString());
- JSONArray suggestions = results.getJSONArray(1);
- JSONArray popularity = results.getJSONArray(2);
- if (DBG) Log.d(LOG_TAG, "Got " + suggestions.length() + " results");
- return new GoogleSuggestCursor(this, query, suggestions, popularity);
- } else {
- if (DBG)
- Log.d(LOG_TAG, "Request failed " + connection.getResponseMessage());
- }
- } catch (UnsupportedEncodingException e) {
- Log.w(LOG_TAG, "Error", e);
- } catch (IOException e) {
- Log.w(LOG_TAG, "Error", e);
- } catch (JSONException e) {
- Log.w(LOG_TAG, "Error", e);
- } finally {
- if (connection != null) connection.disconnect();
- }
- return null;
- }
-
- @Override
- public SuggestionCursor refreshShortcut(String shortcutId, String oldExtraData) {
- return null;
- }
-
- private boolean isNetworkConnected() {
- NetworkInfo networkInfo = getActiveNetworkInfo();
- return networkInfo != null && networkInfo.isConnected();
- }
-
- private NetworkInfo getActiveNetworkInfo() {
- ConnectivityManager connectivity =
- (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity == null) {
- return null;
- }
- return connectivity.getActiveNetworkInfo();
- }
-
- private static class GoogleSuggestCursor extends AbstractGoogleSourceResult {
-
- /* Contains the actual suggestions */
- private final JSONArray mSuggestions;
-
- /* This contains the popularity of each suggestion
- * i.e. 165,000 results. It's not related to sorting.
- */
- private final JSONArray mPopularity;
-
- public GoogleSuggestCursor(Source source, String userQuery,
- JSONArray suggestions, JSONArray popularity) {
- super(source, userQuery);
- mSuggestions = suggestions;
- mPopularity = popularity;
- }
-
- @Override
- public int getCount() {
- return mSuggestions.length();
- }
-
- @Override
- public String getSuggestionQuery() {
- try {
- return mSuggestions.getString(getPosition());
- } catch (JSONException e) {
- Log.w(LOG_TAG, "Error parsing response: " + e);
- return null;
- }
- }
-
- @Override
- public String getSuggestionText2() {
- try {
- return mPopularity.getString(getPosition());
- } catch (JSONException e) {
- Log.w(LOG_TAG, "Error parsing response: " + e);
- return null;
- }
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/google/GoogleSuggestionProvider.java b/src/com/android/quicksearchbox/google/GoogleSuggestionProvider.java
deleted file mode 100644
index 02f9d38..0000000
--- a/src/com/android/quicksearchbox/google/GoogleSuggestionProvider.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2008 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.google;
-
-import com.android.quicksearchbox.CursorBackedSourceResult;
-import com.android.quicksearchbox.QsbApplication;
-import com.android.quicksearchbox.Source;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionCursorBackedCursor;
-
-import android.app.SearchManager;
-import android.content.ContentProvider;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.UriMatcher;
-import android.database.Cursor;
-import android.net.Uri;
-import android.util.Log;
-
-/**
- * A suggestion provider which provides content from Genie, a service that offers
- * a superset of the content provided by Google Suggest.
- */
-public class GoogleSuggestionProvider extends ContentProvider {
- private static final boolean DBG = false;
- private static final String TAG = "QSB.GoogleSuggestionProvider";
-
- // UriMatcher constants
- private static final int SEARCH_SUGGEST = 0;
- private static final int SEARCH_SHORTCUT = 1;
-
- private UriMatcher mUriMatcher;
-
- private GoogleSource mSource;
-
- @Override
- public boolean onCreate() {
- mSource = QsbApplication.get(getContext()).getGoogleSource();
- mUriMatcher = buildUriMatcher(getContext());
- return true;
- }
-
- /**
- * This will always return {@link SearchManager#SUGGEST_MIME_TYPE} as this
- * provider is purely to provide suggestions.
- */
- @Override
- public String getType(Uri uri) {
- return SearchManager.SUGGEST_MIME_TYPE;
- }
-
- private SourceResult emptyIfNull(SourceResult result, GoogleSource source, String query) {
- return result == null ? new CursorBackedSourceResult(source, query) : result;
- }
-
- @Override
- public Cursor query(Uri uri, String[] projection, String selection,
- String[] selectionArgs, String sortOrder) {
-
- if (DBG) Log.d(TAG, "query uri=" + uri);
- int match = mUriMatcher.match(uri);
-
- if (match == SEARCH_SUGGEST) {
- String query = getQuery(uri);
- return new SuggestionCursorBackedCursor(
- emptyIfNull(mSource.queryExternal(query), mSource, query));
- } else if (match == SEARCH_SHORTCUT) {
- String shortcutId = getQuery(uri);
- String extraData =
- uri.getQueryParameter(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
- return new SuggestionCursorBackedCursor(mSource.refreshShortcut(shortcutId, extraData));
- } else {
- throw new IllegalArgumentException("Unknown URI " + uri);
- }
- }
-
- /**
- * Gets the search text from a uri.
- */
- private String getQuery(Uri uri) {
- if (uri.getPathSegments().size() > 1) {
- return uri.getLastPathSegment();
- } else {
- return "";
- }
- }
-
- @Override
- public Uri insert(Uri uri, ContentValues values) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int update(Uri uri, ContentValues values, String selection,
- String[] selectionArgs) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int delete(Uri uri, String selection, String[] selectionArgs) {
- throw new UnsupportedOperationException();
- }
-
- private UriMatcher buildUriMatcher(Context context) {
- String authority = getAuthority(context);
- UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
- matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY,
- SEARCH_SUGGEST);
- matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
- SEARCH_SUGGEST);
- matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_SHORTCUT,
- SEARCH_SHORTCUT);
- matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*",
- SEARCH_SHORTCUT);
- return matcher;
- }
-
- protected String getAuthority(Context context) {
- return context.getPackageName() + ".google";
- }
-
-}
diff --git a/src/com/android/quicksearchbox/google/SearchBaseUrlHelper.java b/src/com/android/quicksearchbox/google/SearchBaseUrlHelper.java
deleted file mode 100644
index d95214f..0000000
--- a/src/com/android/quicksearchbox/google/SearchBaseUrlHelper.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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.google;
-
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.SearchSettings;
-import com.android.quicksearchbox.SearchSettingsImpl;
-import com.android.quicksearchbox.util.HttpHelper;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.os.AsyncTask;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.util.Locale;
-
-/**
- * Helper to build the base URL for all search requests.
- */
-public class SearchBaseUrlHelper implements SharedPreferences.OnSharedPreferenceChangeListener {
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SearchBaseUrlHelper";
-
- private static final String DOMAIN_CHECK_URL =
- "https://www.google.com/searchdomaincheck?format=domain";
-
- private static final long SEARCH_BASE_URL_EXPIRY_MS = 24 * 3600 * 1000L;
-
- private final HttpHelper mHttpHelper;
- private final Context mContext;
- private final SearchSettings mSearchSettings;
-
- /**
- * Note that this constructor will spawn a thread to issue a HTTP
- * request if shouldUseGoogleCom is false.
- */
- public SearchBaseUrlHelper(Context context, HttpHelper helper,
- SearchSettings searchSettings, SharedPreferences prefs) {
- mHttpHelper = helper;
- mContext = context;
- mSearchSettings = searchSettings;
-
- // Note: This earlier used an inner class, but that causes issues
- // because SharedPreferencesImpl uses a WeakHashMap< > and the listener
- // will be GC'ed unless we keep a reference to it here.
- prefs.registerOnSharedPreferenceChangeListener(this);
-
- maybeUpdateBaseUrlSetting(false);
- }
-
- /**
- * Update the base search url, either:
- * (a) it has never been set (first run)
- * (b) it has expired
- * (c) if the caller forces an update by setting the "force" parameter.
- *
- * @param force if true, then the URL is reset whether or not it has
- * expired.
- */
- public void maybeUpdateBaseUrlSetting(boolean force) {
- long lastUpdateTime = mSearchSettings.getSearchBaseDomainApplyTime();
- long currentTime = System.currentTimeMillis();
-
- if (force || lastUpdateTime == -1 ||
- currentTime - lastUpdateTime >= SEARCH_BASE_URL_EXPIRY_MS) {
- if (mSearchSettings.shouldUseGoogleCom()) {
- setSearchBaseDomain(getDefaultBaseDomain());
- } else {
- checkSearchDomain();
- }
- }
- }
-
- /**
- * @return the base url for searches.
- */
- public String getSearchBaseUrl() {
- return mContext.getResources().getString(R.string.google_search_base_pattern,
- getSearchDomain(), GoogleSearch.getLanguage(Locale.getDefault()));
- }
-
- /**
- * @return the search domain. This is of the form "google.co.xx" or "google.com",
- * used by UI code.
- */
- public String getSearchDomain() {
- String domain = mSearchSettings.getSearchBaseDomain();
-
- if (domain == null) {
- if (DBG) {
- Log.w(TAG, "Search base domain was null, last apply time=" +
- mSearchSettings.getSearchBaseDomainApplyTime());
- }
-
- // This is required to deal with the case wherein getSearchDomain
- // is called before checkSearchDomain returns a valid URL. This will
- // happen *only* on the first run of the app when the "use google.com"
- // option is unchecked. In other cases, the previously set domain (or
- // the default) will be returned.
- //
- // We have no choice in this case but to use the default search domain.
- domain = getDefaultBaseDomain();
- }
-
- if (domain.startsWith(".")) {
- if (DBG) Log.d(TAG, "Prepending www to " + domain);
- domain = "www" + domain;
- }
- return domain;
- }
-
- /**
- * Issue a request to google.com/searchdomaincheck to retrieve the base
- * URL for search requests.
- */
- private void checkSearchDomain() {
- final HttpHelper.GetRequest request = new HttpHelper.GetRequest(DOMAIN_CHECK_URL);
-
- new AsyncTask<Void, Void, Void>() {
- @Override
- protected Void doInBackground(Void ... params) {
- if (DBG) Log.d(TAG, "Starting request to /searchdomaincheck");
- String domain;
- try {
- domain = mHttpHelper.get(request);
- } catch (Exception e) {
- if (DBG) Log.d(TAG, "Request to /searchdomaincheck failed : " + e);
- // Swallow any exceptions thrown by the HTTP helper, in
- // this rare case, we just use the default URL.
- domain = getDefaultBaseDomain();
-
- return null;
- }
-
- if (DBG) Log.d(TAG, "Request to /searchdomaincheck succeeded");
- setSearchBaseDomain(domain);
-
- return null;
- }
- }.execute();
- }
-
- private String getDefaultBaseDomain() {
- return mContext.getResources().getString(R.string.default_search_domain);
- }
-
- private void setSearchBaseDomain(String domain) {
- if (DBG) Log.d(TAG, "Setting search domain to : " + domain);
-
- mSearchSettings.setSearchBaseDomain(domain);
- }
-
- @Override
- public void onSharedPreferenceChanged(SharedPreferences pref, String key) {
- // Listen for changes only to the SEARCH_BASE_URL preference.
- if (DBG) Log.d(TAG, "Handling changed preference : " + key);
- if (SearchSettingsImpl.USE_GOOGLE_COM_PREF.equals(key)) {
- maybeUpdateBaseUrlSetting(true);
- }
- }
-} \ No newline at end of file
diff --git a/src/com/android/quicksearchbox/ui/BaseSuggestionView.java b/src/com/android/quicksearchbox/ui/BaseSuggestionView.java
deleted file mode 100644
index ed7f74b..0000000
--- a/src/com/android/quicksearchbox/ui/BaseSuggestionView.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Suggestion;
-
-import android.content.Context;
-import android.text.TextUtils;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.ImageView;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-/**
- * Base class for suggestion views.
- */
-public abstract class BaseSuggestionView extends RelativeLayout implements SuggestionView {
-
- protected TextView mText1;
- protected TextView mText2;
- protected ImageView mIcon1;
- protected ImageView mIcon2;
- private long mSuggestionId;
- private SuggestionsAdapter<?> mAdapter;
-
- public BaseSuggestionView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public BaseSuggestionView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public BaseSuggestionView(Context context) {
- super(context);
- }
-
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- mText1 = (TextView) findViewById(R.id.text1);
- mText2 = (TextView) findViewById(R.id.text2);
- mIcon1 = (ImageView) findViewById(R.id.icon1);
- mIcon2 = (ImageView) findViewById(R.id.icon2);
- }
-
- @Override
- public void bindAsSuggestion(Suggestion suggestion, String userQuery) {
- setOnClickListener(new ClickListener());
- }
-
- @Override
- public void bindAdapter(SuggestionsAdapter<?> adapter, long suggestionId) {
- mAdapter = adapter;
- mSuggestionId = suggestionId;
- }
-
- protected boolean isFromHistory(Suggestion suggestion) {
- return suggestion.isSuggestionShortcut() || suggestion.isHistorySuggestion();
- }
-
- /**
- * Sets the first text line.
- */
- protected void setText1(CharSequence text) {
- mText1.setText(text);
- }
-
- /**
- * Sets the second text line.
- */
- protected void setText2(CharSequence text) {
- mText2.setText(text);
- if (TextUtils.isEmpty(text)) {
- mText2.setVisibility(GONE);
- } else {
- mText2.setVisibility(VISIBLE);
- }
- }
-
- protected void onSuggestionClicked() {
- if (mAdapter != null) {
- mAdapter.onSuggestionClicked(mSuggestionId);
- }
- }
-
- protected void onSuggestionQueryRefineClicked() {
- if (mAdapter != null) {
- mAdapter.onSuggestionQueryRefineClicked(mSuggestionId);
- }
- }
-
- private class ClickListener implements OnClickListener {
- @Override
- public void onClick(View v) {
- onSuggestionClicked();
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/ClusteredSuggestionsView.java b/src/com/android/quicksearchbox/ui/ClusteredSuggestionsView.java
deleted file mode 100644
index 9427024..0000000
--- a/src/com/android/quicksearchbox/ui/ClusteredSuggestionsView.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.ui;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.ExpandableListAdapter;
-import android.widget.ExpandableListView;
-
-/**
- * Suggestions view that displays suggestions clustered by corpus type.
- */
-public class ClusteredSuggestionsView extends ExpandableListView
- implements SuggestionsListView<ExpandableListAdapter> {
-
- SuggestionsAdapter<ExpandableListAdapter> mSuggestionsAdapter;
-
- public ClusteredSuggestionsView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public void setSuggestionsAdapter(SuggestionsAdapter<ExpandableListAdapter> adapter) {
- mSuggestionsAdapter = adapter;
- super.setAdapter(adapter == null ? null : adapter.getListAdapter());
- }
-
- public SuggestionsAdapter<ExpandableListAdapter> getSuggestionsAdapter() {
- return mSuggestionsAdapter;
- }
-
- public void setLimitSuggestionsToViewHeight(boolean limit) {
- // not supported
- }
-
- @Override
- public void onFinishInflate() {
- super.onFinishInflate();
- setItemsCanFocus(false);
- setOnGroupClickListener(new OnGroupClickListener(){
- public boolean onGroupClick(
- ExpandableListView parent, View v, int groupPosition, long id) {
- // disable collapsing / expanding
- return true;
- }});
- }
-
- public void expandAll() {
- if (mSuggestionsAdapter != null) {
- ExpandableListAdapter adapter = mSuggestionsAdapter.getListAdapter();
- for (int i = 0; i < adapter.getGroupCount(); ++i) {
- expandGroup(i);
- }
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/ContactBadge.java b/src/com/android/quicksearchbox/ui/ContactBadge.java
deleted file mode 100644
index 15b8320..0000000
--- a/src/com/android/quicksearchbox/ui/ContactBadge.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.ui;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.QuickContactBadge;
-
-/**
- * A {@link QuickContactBadge} that allows setting a click listener.
- * The base class may use {@link View#setOnClickListener} internally,
- * so this class adds a separate click listener field.
- */
-public class ContactBadge extends QuickContactBadge {
-
- private View.OnClickListener mExtraOnClickListener;
-
- public ContactBadge(Context context) {
- super(context);
- }
-
- public ContactBadge(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public ContactBadge(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- @Override
- public void onClick(View v) {
- super.onClick(v);
- if (mExtraOnClickListener != null) {
- mExtraOnClickListener.onClick(v);
- }
- }
-
- public void setExtraOnClickListener(View.OnClickListener extraOnClickListener) {
- mExtraOnClickListener = extraOnClickListener;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/CorpusView.java b/src/com/android/quicksearchbox/ui/CorpusView.java
deleted file mode 100644
index 23982d1..0000000
--- a/src/com/android/quicksearchbox/ui/CorpusView.java
+++ /dev/null
@@ -1,95 +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.ui;
-
-import com.android.quicksearchbox.R;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.util.AttributeSet;
-import android.view.ViewDebug;
-import android.widget.Checkable;
-import android.widget.ImageView;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-
-/**
- * A corpus in the corpus selection list.
- */
-public class CorpusView extends RelativeLayout implements Checkable {
-
- private ImageView mIcon;
- private TextView mLabel;
- private boolean mChecked;
-
- private static final int[] CHECKED_STATE_SET = {
- android.R.attr.state_checked
- };
-
- public CorpusView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public CorpusView(Context context) {
- super(context);
- }
-
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- mIcon = (ImageView) findViewById(R.id.source_icon);
- mLabel = (TextView) findViewById(R.id.source_label);
- }
-
- public void setLabel(CharSequence label) {
- mLabel.setText(label);
- }
-
- public void setIcon(Drawable icon) {
- mIcon.setImageDrawable(icon);
- }
-
- @Override
- @ViewDebug.ExportedProperty
- public boolean isChecked() {
- return mChecked;
- }
-
- @Override
- public void setChecked(boolean checked) {
- if (mChecked != checked) {
- mChecked = checked;
- refreshDrawableState();
- }
- }
-
- @Override
- public void toggle() {
- setChecked(!mChecked);
- }
-
- @Override
- protected int[] onCreateDrawableState(int extraSpace) {
- final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
- if (isChecked()) {
- mergeDrawableStates(drawableState, CHECKED_STATE_SET);
- }
- return drawableState;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/DefaultSuggestionView.java b/src/com/android/quicksearchbox/ui/DefaultSuggestionView.java
deleted file mode 100644
index c946568..0000000
--- a/src/com/android/quicksearchbox/ui/DefaultSuggestionView.java
+++ /dev/null
@@ -1,254 +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.ui;
-
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Source;
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.util.Consumer;
-import com.android.quicksearchbox.util.NowOrLater;
-
-import android.content.Context;
-import android.content.res.ColorStateList;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.text.Html;
-import android.text.Spannable;
-import android.text.SpannableString;
-import android.text.TextUtils;
-import android.text.style.TextAppearanceSpan;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.View;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-/**
- * View for the items in the suggestions list. This includes promoted suggestions,
- * sources, and suggestions under each source.
- */
-public class DefaultSuggestionView extends BaseSuggestionView {
-
- private static final boolean DBG = false;
-
- private static final String VIEW_ID = "default";
-
- private final String TAG = "QSB.DefaultSuggestionView";
-
- private AsyncIcon mAsyncIcon1;
- private AsyncIcon mAsyncIcon2;
-
- public DefaultSuggestionView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public DefaultSuggestionView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public DefaultSuggestionView(Context context) {
- super(context);
- }
-
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- mText1 = (TextView) findViewById(R.id.text1);
- mText2 = (TextView) findViewById(R.id.text2);
- mAsyncIcon1 = new AsyncIcon(mIcon1) {
- // override default icon (when no other available) with default source icon
- @Override
- protected String getFallbackIconId(Source source) {
- return source.getSourceIconUri().toString();
- }
- @Override
- protected Drawable getFallbackIcon(Source source) {
- return source.getSourceIcon();
- }
- };
- mAsyncIcon2 = new AsyncIcon(mIcon2);
- }
-
- @Override
- public void bindAsSuggestion(Suggestion suggestion, String userQuery) {
- super.bindAsSuggestion(suggestion, userQuery);
-
- CharSequence text1 = formatText(suggestion.getSuggestionText1(), suggestion);
- CharSequence text2 = suggestion.getSuggestionText2Url();
- if (text2 != null) {
- text2 = formatUrl(text2);
- } else {
- text2 = formatText(suggestion.getSuggestionText2(), suggestion);
- }
- // If there is no text for the second line, allow the first line to be up to two lines
- if (TextUtils.isEmpty(text2)) {
- mText1.setSingleLine(false);
- mText1.setMaxLines(2);
- mText1.setEllipsize(TextUtils.TruncateAt.START);
- } else {
- mText1.setSingleLine(true);
- mText1.setMaxLines(1);
- mText1.setEllipsize(TextUtils.TruncateAt.MIDDLE);
- }
- setText1(text1);
- setText2(text2);
- mAsyncIcon1.set(suggestion.getSuggestionSource(), suggestion.getSuggestionIcon1());
- mAsyncIcon2.set(suggestion.getSuggestionSource(), suggestion.getSuggestionIcon2());
-
- if (DBG) {
- Log.d(TAG, "bindAsSuggestion(), text1=" + text1 + ",text2=" + text2 + ",q='" +
- userQuery + ",fromHistory=" + isFromHistory(suggestion));
- }
- }
-
- private CharSequence formatUrl(CharSequence url) {
- SpannableString text = new SpannableString(url);
- ColorStateList colors = getResources().getColorStateList(R.color.url_text);
- text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null),
- 0, url.length(),
- Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- return text;
- }
-
- private CharSequence formatText(String str, Suggestion suggestion) {
- boolean isHtml = "html".equals(suggestion.getSuggestionFormat());
- if (isHtml && looksLikeHtml(str)) {
- return Html.fromHtml(str);
- } else {
- return str;
- }
- }
-
- private boolean looksLikeHtml(String str) {
- if (TextUtils.isEmpty(str)) return false;
- for (int i = str.length() - 1; i >= 0; i--) {
- char c = str.charAt(i);
- if (c == '>' || c == '&') return true;
- }
- return false;
- }
-
- /**
- * Sets the drawable in an image view, makes sure the view is only visible if there
- * is a drawable.
- */
- private static void setViewDrawable(ImageView v, Drawable drawable) {
- // Set the icon even if the drawable is null, since we need to clear any
- // previous icon.
- v.setImageDrawable(drawable);
-
- if (drawable == null) {
- v.setVisibility(View.GONE);
- } else {
- v.setVisibility(View.VISIBLE);
-
- // This is a hack to get any animated drawables (like a 'working' spinner)
- // to animate. You have to setVisible true on an AnimationDrawable to get
- // it to start animating, but it must first have been false or else the
- // call to setVisible will be ineffective. We need to clear up the story
- // about animated drawables in the future, see http://b/1878430.
- drawable.setVisible(false, false);
- drawable.setVisible(true, false);
- }
- }
-
- private class AsyncIcon {
- private final ImageView mView;
- private String mCurrentId;
- private String mWantedId;
-
- public AsyncIcon(ImageView view) {
- mView = view;
- }
-
- public void set(final Source source, final String sourceIconId) {
- if (sourceIconId != null) {
- // The iconId can just be a package-relative resource ID, which may overlap with
- // other packages. Make sure it's globally unique.
- Uri iconUri = source.getIconUri(sourceIconId);
- final String uniqueIconId = iconUri == null ? null : iconUri.toString();
- mWantedId = uniqueIconId;
- if (!TextUtils.equals(mWantedId, mCurrentId)) {
- if (DBG) Log.d(TAG, "getting icon Id=" + uniqueIconId);
- NowOrLater<Drawable> icon = source.getIcon(sourceIconId);
- if (icon.haveNow()) {
- if (DBG) Log.d(TAG, "getIcon ready now");
- handleNewDrawable(icon.getNow(), uniqueIconId, source);
- } else {
- // make sure old icon is not visible while new one is loaded
- if (DBG) Log.d(TAG , "getIcon getting later");
- clearDrawable();
- icon.getLater(new Consumer<Drawable>(){
- @Override
- public boolean consume(Drawable icon) {
- if (DBG) {
- Log.d(TAG, "IconConsumer.consume got id " + uniqueIconId +
- " want id " + mWantedId);
- }
- // ensure we have not been re-bound since the request was made.
- if (TextUtils.equals(uniqueIconId, mWantedId)) {
- handleNewDrawable(icon, uniqueIconId, source);
- return true;
- }
- return false;
- }});
- }
- }
- } else {
- mWantedId = null;
- handleNewDrawable(null, null, source);
- }
- }
-
- private void handleNewDrawable(Drawable icon, String id, Source source) {
- if (icon == null) {
- mWantedId = getFallbackIconId(source);
- if (TextUtils.equals(mWantedId, mCurrentId)) {
- return;
- }
- icon = getFallbackIcon(source);
- }
- setDrawable(icon, id);
- }
-
- private void setDrawable(Drawable icon, String id) {
- mCurrentId = id;
- setViewDrawable(mView, icon);
- }
-
- private void clearDrawable() {
- mCurrentId = null;
- mView.setImageDrawable(null);
- }
-
- protected String getFallbackIconId(Source source) {
- return null;
- }
-
- protected Drawable getFallbackIcon(Source source) {
- return null;
- }
-
- }
-
- public static class Factory extends SuggestionViewInflater {
- public Factory(Context context) {
- super(VIEW_ID, DefaultSuggestionView.class, R.layout.suggestion, context);
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/DefaultSuggestionViewFactory.java b/src/com/android/quicksearchbox/ui/DefaultSuggestionViewFactory.java
deleted file mode 100644
index ed4625f..0000000
--- a/src/com/android/quicksearchbox/ui/DefaultSuggestionViewFactory.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.ui;
-
-import android.content.Context;
-import android.view.View;
-import android.view.ViewGroup;
-
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.SuggestionCursor;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedList;
-
-/**
- * Suggestion view factory for Google suggestions.
- */
-public class DefaultSuggestionViewFactory implements SuggestionViewFactory {
-
- private final LinkedList<SuggestionViewFactory> mFactories
- = new LinkedList<SuggestionViewFactory>();
- private final SuggestionViewFactory mDefaultFactory;
- private HashSet<String> mViewTypes;
-
- public DefaultSuggestionViewFactory(Context context) {
- mDefaultFactory = new DefaultSuggestionView.Factory(context);
- addFactory(new WebSearchSuggestionView.Factory(context));
- }
-
- /**
- * Must only be called from the constructor
- */
- protected final void addFactory(SuggestionViewFactory factory) {
- mFactories.addFirst(factory);
- }
-
- @Override
- public Collection<String> getSuggestionViewTypes() {
- if (mViewTypes == null) {
- mViewTypes = new HashSet<String>();
- mViewTypes.addAll(mDefaultFactory.getSuggestionViewTypes());
- for (SuggestionViewFactory factory : mFactories) {
- mViewTypes.addAll(factory.getSuggestionViewTypes());
- }
- }
- return mViewTypes;
- }
-
- @Override
- public View getView(SuggestionCursor suggestion, String userQuery,
- View convertView, ViewGroup parent) {
- for (SuggestionViewFactory factory : mFactories) {
- if (factory.canCreateView(suggestion)) {
- return factory.getView(suggestion, userQuery, convertView, parent);
- }
- }
- return mDefaultFactory.getView(suggestion, userQuery, convertView, parent);
- }
-
- @Override
- public String getViewType(Suggestion suggestion) {
- for (SuggestionViewFactory factory : mFactories) {
- if (factory.canCreateView(suggestion)) {
- return factory.getViewType(suggestion);
- }
- }
- return mDefaultFactory.getViewType(suggestion);
- }
-
- @Override
- public boolean canCreateView(Suggestion suggestion) {
- return true;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/DelayingSuggestionsAdapter.java b/src/com/android/quicksearchbox/ui/DelayingSuggestionsAdapter.java
deleted file mode 100644
index 6b7d47e..0000000
--- a/src/com/android/quicksearchbox/ui/DelayingSuggestionsAdapter.java
+++ /dev/null
@@ -1,172 +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.ui;
-
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.SuggestionPosition;
-import com.android.quicksearchbox.Suggestions;
-
-import android.database.DataSetObserver;
-import android.util.Log;
-import android.view.View.OnFocusChangeListener;
-
-/**
- * A {@link SuggestionsListAdapter} that doesn't expose the new suggestions
- * until there are some results to show.
- */
-public class DelayingSuggestionsAdapter<A> implements SuggestionsAdapter<A> {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.DelayingSuggestionsAdapter";
-
- private DataSetObserver mPendingDataSetObserver;
-
- private Suggestions mPendingSuggestions;
-
- private final SuggestionsAdapterBase<A> mDelayedAdapter;
-
- public DelayingSuggestionsAdapter(SuggestionsAdapterBase<A> delayed) {
- mDelayedAdapter = delayed;
- }
-
- public void close() {
- setPendingSuggestions(null);
- mDelayedAdapter.close();
- }
-
- @Override
- public void setSuggestions(Suggestions suggestions) {
- if (suggestions == null) {
- mDelayedAdapter.setSuggestions(null);
- setPendingSuggestions(null);
- return;
- }
- if (shouldPublish(suggestions)) {
- if (DBG) Log.d(TAG, "Publishing suggestions immediately: " + suggestions);
- mDelayedAdapter.setSuggestions(suggestions);
- // Clear any old pending suggestions.
- setPendingSuggestions(null);
- } else {
- if (DBG) Log.d(TAG, "Delaying suggestions publishing: " + suggestions);
- setPendingSuggestions(suggestions);
- }
- }
-
- /**
- * Gets whether the given suggestions are non-empty for the selected source.
- */
- private boolean shouldPublish(Suggestions suggestions) {
- if (suggestions.isDone()) return true;
- SuggestionCursor cursor = suggestions.getResult();
- if (cursor != null && cursor.getCount() > 0) {
- return true;
- }
- return false;
- }
-
- private void setPendingSuggestions(Suggestions suggestions) {
- if (mPendingSuggestions == suggestions) {
- return;
- }
- if (mDelayedAdapter.isClosed()) {
- if (suggestions != null) {
- suggestions.release();
- }
- return;
- }
- if (mPendingDataSetObserver == null) {
- mPendingDataSetObserver = new PendingSuggestionsObserver();
- }
- if (mPendingSuggestions != null) {
- mPendingSuggestions.unregisterDataSetObserver(mPendingDataSetObserver);
- // Close old suggestions, but only if they are not also the current
- // suggestions.
- if (mPendingSuggestions != getSuggestions()) {
- mPendingSuggestions.release();
- }
- }
- mPendingSuggestions = suggestions;
- if (mPendingSuggestions != null) {
- mPendingSuggestions.registerDataSetObserver(mPendingDataSetObserver);
- }
- }
-
- protected void onPendingSuggestionsChanged() {
- if (DBG) {
- Log.d(TAG, "onPendingSuggestionsChanged(), mPendingSuggestions="
- + mPendingSuggestions);
- }
- if (shouldPublish(mPendingSuggestions)) {
- if (DBG) Log.d(TAG, "Suggestions now available, publishing: " + mPendingSuggestions);
- mDelayedAdapter.setSuggestions(mPendingSuggestions);
- // The suggestions are no longer pending.
- setPendingSuggestions(null);
- }
- }
-
- private class PendingSuggestionsObserver extends DataSetObserver {
- @Override
- public void onChanged() {
- onPendingSuggestionsChanged();
- }
- }
-
- @Override
- public A getListAdapter() {
- return mDelayedAdapter.getListAdapter();
- }
-
- public SuggestionCursor getCurrentPromotedSuggestions() {
- return mDelayedAdapter.getCurrentSuggestions();
- }
-
- @Override
- public Suggestions getSuggestions() {
- return mDelayedAdapter.getSuggestions();
- }
-
- @Override
- public SuggestionPosition getSuggestion(long suggestionId) {
- return mDelayedAdapter.getSuggestion(suggestionId);
- }
-
- @Override
- public void onSuggestionClicked(long suggestionId) {
- mDelayedAdapter.onSuggestionClicked(suggestionId);
- }
-
- @Override
- public void onSuggestionQueryRefineClicked(long suggestionId) {
- mDelayedAdapter.onSuggestionQueryRefineClicked(suggestionId);
- }
-
- @Override
- public void setOnFocusChangeListener(OnFocusChangeListener l) {
- mDelayedAdapter.setOnFocusChangeListener(l);
- }
-
- @Override
- public void setSuggestionClickListener(SuggestionClickListener listener) {
- mDelayedAdapter.setSuggestionClickListener(listener);
- }
-
- @Override
- public boolean isEmpty() {
- return mDelayedAdapter.isEmpty();
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/QueryTextView.java b/src/com/android/quicksearchbox/ui/QueryTextView.java
deleted file mode 100644
index 2531204..0000000
--- a/src/com/android/quicksearchbox/ui/QueryTextView.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * 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.ui;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.inputmethod.CompletionInfo;
-import android.view.inputmethod.InputMethodManager;
-import android.widget.EditText;
-
-/**
- * The query text field.
- */
-public class QueryTextView extends EditText {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.QueryTextView";
-
- private CommitCompletionListener mCommitCompletionListener;
-
- public QueryTextView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public QueryTextView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public QueryTextView(Context context) {
- super(context);
- }
-
- /**
- * Sets the text selection in the query text view.
- *
- * @param selectAll If {@code true}, selects the entire query.
- * If {@false}, no characters are selected, and the cursor is placed
- * at the end of the query.
- */
- public void setTextSelection(boolean selectAll) {
- if (selectAll) {
- selectAll();
- } else {
- setSelection(length());
- }
- }
-
- protected void replaceText(CharSequence text) {
- clearComposingText();
- setText(text);
- setTextSelection(false);
- }
-
- public void setCommitCompletionListener(CommitCompletionListener listener) {
- mCommitCompletionListener = listener;
- }
-
- private InputMethodManager getInputMethodManager() {
- return (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- }
-
- public void showInputMethod() {
- InputMethodManager imm = getInputMethodManager();
- if (imm != null) {
- imm.showSoftInput(this, 0);
- }
- }
-
- public void hideInputMethod() {
- InputMethodManager imm = getInputMethodManager();
- if (imm != null) {
- imm.hideSoftInputFromWindow(getWindowToken(), 0);
- }
- }
-
- @Override
- public void onCommitCompletion(CompletionInfo completion) {
- if (DBG) Log.d(TAG, "onCommitCompletion(" + completion + ")");
- hideInputMethod();
- replaceText(completion.getText());
- if (mCommitCompletionListener != null) {
- mCommitCompletionListener.onCommitCompletion(completion.getPosition());
- }
- }
-
- public interface CommitCompletionListener {
- void onCommitCompletion(int position);
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SearchActivityView.java b/src/com/android/quicksearchbox/ui/SearchActivityView.java
deleted file mode 100644
index 6060e4f..0000000
--- a/src/com/android/quicksearchbox/ui/SearchActivityView.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*
- * 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.ui;
-
-import android.content.Context;
-import android.database.DataSetObserver;
-import android.graphics.drawable.Drawable;
-import android.text.Editable;
-import android.text.TextUtils;
-import android.text.TextWatcher;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.KeyEvent;
-import android.view.View;
-import android.view.inputmethod.CompletionInfo;
-import android.view.inputmethod.InputMethodManager;
-import android.widget.AbsListView;
-import android.widget.ImageButton;
-import android.widget.ListAdapter;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.widget.TextView.OnEditorActionListener;
-
-import com.android.quicksearchbox.Logger;
-import com.android.quicksearchbox.QsbApplication;
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.SearchActivity;
-import com.android.quicksearchbox.SourceResult;
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.Suggestions;
-import com.android.quicksearchbox.VoiceSearch;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-public abstract class SearchActivityView extends RelativeLayout {
- protected static final boolean DBG = false;
- protected static final String TAG = "QSB.SearchActivityView";
-
- // The string used for privateImeOptions to identify to the IME that it should not show
- // a microphone button since one already exists in the search dialog.
- // TODO: This should move to android-common or something.
- private static final String IME_OPTION_NO_MICROPHONE = "nm";
-
- protected QueryTextView mQueryTextView;
- // True if the query was empty on the previous call to updateQuery()
- protected boolean mQueryWasEmpty = true;
- protected Drawable mQueryTextEmptyBg;
- protected Drawable mQueryTextNotEmptyBg;
-
- protected SuggestionsListView<ListAdapter> mSuggestionsView;
- protected SuggestionsAdapter<ListAdapter> mSuggestionsAdapter;
-
- protected ImageButton mSearchGoButton;
- protected ImageButton mVoiceSearchButton;
-
- protected ButtonsKeyListener mButtonsKeyListener;
-
- private boolean mUpdateSuggestions;
-
- private QueryListener mQueryListener;
- private SearchClickListener mSearchClickListener;
- protected View.OnClickListener mExitClickListener;
-
- public SearchActivityView(Context context) {
- super(context);
- }
-
- public SearchActivityView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public SearchActivityView(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- @Override
- protected void onFinishInflate() {
- mQueryTextView = (QueryTextView) findViewById(R.id.search_src_text);
-
- mSuggestionsView = (SuggestionsView) findViewById(R.id.suggestions);
- mSuggestionsView.setOnScrollListener(new InputMethodCloser());
- mSuggestionsView.setOnKeyListener(new SuggestionsViewKeyListener());
- mSuggestionsView.setOnFocusChangeListener(new SuggestListFocusListener());
-
- mSuggestionsAdapter = createSuggestionsAdapter();
- // TODO: why do we need focus listeners both on the SuggestionsView and the individual
- // suggestions?
- mSuggestionsAdapter.setOnFocusChangeListener(new SuggestListFocusListener());
-
- mSearchGoButton = (ImageButton) findViewById(R.id.search_go_btn);
- mVoiceSearchButton = (ImageButton) findViewById(R.id.search_voice_btn);
- mVoiceSearchButton.setImageDrawable(getVoiceSearchIcon());
-
- mQueryTextView.addTextChangedListener(new SearchTextWatcher());
- mQueryTextView.setOnEditorActionListener(new QueryTextEditorActionListener());
- mQueryTextView.setOnFocusChangeListener(new QueryTextViewFocusListener());
- mQueryTextEmptyBg = mQueryTextView.getBackground();
-
- mSearchGoButton.setOnClickListener(new SearchGoButtonClickListener());
-
- mButtonsKeyListener = new ButtonsKeyListener();
- mSearchGoButton.setOnKeyListener(mButtonsKeyListener);
- mVoiceSearchButton.setOnKeyListener(mButtonsKeyListener);
-
- mUpdateSuggestions = true;
- }
-
- public abstract void onResume();
-
- public abstract void onStop();
-
- public void onPause() {
- // Override if necessary
- }
-
- public void start() {
- mSuggestionsAdapter.getListAdapter().registerDataSetObserver(new SuggestionsObserver());
- mSuggestionsView.setSuggestionsAdapter(mSuggestionsAdapter);
- }
-
- public void destroy() {
- mSuggestionsView.setSuggestionsAdapter(null); // closes mSuggestionsAdapter
- }
-
- // TODO: Get rid of this. To make it more easily testable,
- // the SearchActivityView should not depend on QsbApplication.
- protected QsbApplication getQsbApplication() {
- return QsbApplication.get(getContext());
- }
-
- protected Drawable getVoiceSearchIcon() {
- return getResources().getDrawable(R.drawable.ic_btn_speak_now);
- }
-
- protected VoiceSearch getVoiceSearch() {
- return getQsbApplication().getVoiceSearch();
- }
-
- protected SuggestionsAdapter<ListAdapter> createSuggestionsAdapter() {
- return new DelayingSuggestionsAdapter<ListAdapter>(new SuggestionsListAdapter(
- getQsbApplication().getSuggestionViewFactory()));
- }
-
- public void setMaxPromotedResults(int maxPromoted) {
- }
-
- public void limitResultsToViewHeight() {
- }
-
- public void setQueryListener(QueryListener listener) {
- mQueryListener = listener;
- }
-
- public void setSearchClickListener(SearchClickListener listener) {
- mSearchClickListener = listener;
- }
-
- public void setVoiceSearchButtonClickListener(View.OnClickListener listener) {
- if (mVoiceSearchButton != null) {
- mVoiceSearchButton.setOnClickListener(listener);
- }
- }
-
- public void setSuggestionClickListener(final SuggestionClickListener listener) {
- mSuggestionsAdapter.setSuggestionClickListener(listener);
- mQueryTextView.setCommitCompletionListener(new QueryTextView.CommitCompletionListener() {
- @Override
- public void onCommitCompletion(int position) {
- mSuggestionsAdapter.onSuggestionClicked(position);
- }
- });
- }
-
- public void setExitClickListener(final View.OnClickListener listener) {
- mExitClickListener = listener;
- }
-
- public Suggestions getSuggestions() {
- return mSuggestionsAdapter.getSuggestions();
- }
-
- public SuggestionCursor getCurrentSuggestions() {
- return mSuggestionsAdapter.getSuggestions().getResult();
- }
-
- public void setSuggestions(Suggestions suggestions) {
- suggestions.acquire();
- mSuggestionsAdapter.setSuggestions(suggestions);
- }
-
- public void clearSuggestions() {
- mSuggestionsAdapter.setSuggestions(null);
- }
-
- public String getQuery() {
- CharSequence q = mQueryTextView.getText();
- return q == null ? "" : q.toString();
- }
-
- public boolean isQueryEmpty() {
- return TextUtils.isEmpty(getQuery());
- }
-
- /**
- * Sets the text in the query box. Does not update the suggestions.
- */
- public void setQuery(String query, boolean selectAll) {
- mUpdateSuggestions = false;
- mQueryTextView.setText(query);
- mQueryTextView.setTextSelection(selectAll);
- mUpdateSuggestions = true;
- }
-
- protected SearchActivity getActivity() {
- Context context = getContext();
- if (context instanceof SearchActivity) {
- return (SearchActivity) context;
- } else {
- return null;
- }
- }
-
- public void hideSuggestions() {
- mSuggestionsView.setVisibility(GONE);
- }
-
- public void showSuggestions() {
- mSuggestionsView.setVisibility(VISIBLE);
- }
-
- public void focusQueryTextView() {
- mQueryTextView.requestFocus();
- }
-
- protected void updateUi() {
- updateUi(isQueryEmpty());
- }
-
- protected void updateUi(boolean queryEmpty) {
- updateQueryTextView(queryEmpty);
- updateSearchGoButton(queryEmpty);
- updateVoiceSearchButton(queryEmpty);
- }
-
- protected void updateQueryTextView(boolean queryEmpty) {
- if (queryEmpty) {
- mQueryTextView.setBackgroundDrawable(mQueryTextEmptyBg);
- mQueryTextView.setHint(null);
- } else {
- mQueryTextView.setBackgroundResource(R.drawable.textfield_search);
- }
- }
-
- private void updateSearchGoButton(boolean queryEmpty) {
- if (queryEmpty) {
- mSearchGoButton.setVisibility(View.GONE);
- } else {
- mSearchGoButton.setVisibility(View.VISIBLE);
- }
- }
-
- protected void updateVoiceSearchButton(boolean queryEmpty) {
- if (shouldShowVoiceSearch(queryEmpty)
- && getVoiceSearch().shouldShowVoiceSearch()) {
- mVoiceSearchButton.setVisibility(View.VISIBLE);
- mQueryTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE);
- } else {
- mVoiceSearchButton.setVisibility(View.GONE);
- mQueryTextView.setPrivateImeOptions(null);
- }
- }
-
- protected boolean shouldShowVoiceSearch(boolean queryEmpty) {
- return queryEmpty;
- }
-
- /**
- * Hides the input method.
- */
- protected void hideInputMethod() {
- InputMethodManager imm = (InputMethodManager)
- getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- if (imm != null) {
- imm.hideSoftInputFromWindow(getWindowToken(), 0);
- }
- }
-
- public abstract void considerHidingInputMethod();
-
- public void showInputMethodForQuery() {
- mQueryTextView.showInputMethod();
- }
-
- /**
- * Dismiss the activity if BACK is pressed when the search box is empty.
- */
- @Override
- public boolean dispatchKeyEventPreIme(KeyEvent event) {
- SearchActivity activity = getActivity();
- if (activity != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
- && isQueryEmpty()) {
- KeyEvent.DispatcherState state = getKeyDispatcherState();
- if (state != null) {
- if (event.getAction() == KeyEvent.ACTION_DOWN
- && event.getRepeatCount() == 0) {
- state.startTracking(event, this);
- return true;
- } else if (event.getAction() == KeyEvent.ACTION_UP
- && !event.isCanceled() && state.isTracking(event)) {
- hideInputMethod();
- activity.onBackPressed();
- return true;
- }
- }
- }
- return super.dispatchKeyEventPreIme(event);
- }
-
- /**
- * If the input method is in fullscreen mode, and the selector corpus
- * is All or Web, use the web search suggestions as completions.
- */
- protected void updateInputMethodSuggestions() {
- InputMethodManager imm = (InputMethodManager)
- getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- if (imm == null || !imm.isFullscreenMode()) return;
- Suggestions suggestions = mSuggestionsAdapter.getSuggestions();
- if (suggestions == null) return;
- CompletionInfo[] completions = webSuggestionsToCompletions(suggestions);
- if (DBG) Log.d(TAG, "displayCompletions(" + Arrays.toString(completions) + ")");
- imm.displayCompletions(mQueryTextView, completions);
- }
-
- private CompletionInfo[] webSuggestionsToCompletions(Suggestions suggestions) {
- SourceResult cursor = suggestions.getWebResult();
- if (cursor == null) return null;
- int count = cursor.getCount();
- ArrayList<CompletionInfo> completions = new ArrayList<CompletionInfo>(count);
- for (int i = 0; i < count; i++) {
- cursor.moveTo(i);
- String text1 = cursor.getSuggestionText1();
- completions.add(new CompletionInfo(i, i, text1));
- }
- return completions.toArray(new CompletionInfo[completions.size()]);
- }
-
- protected void onSuggestionsChanged() {
- updateInputMethodSuggestions();
- }
-
- protected boolean onSuggestionKeyDown(SuggestionsAdapter<?> adapter,
- long suggestionId, int keyCode, KeyEvent event) {
- // Treat enter or search as a click
- if ( keyCode == KeyEvent.KEYCODE_ENTER
- || keyCode == KeyEvent.KEYCODE_SEARCH
- || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
- if (adapter != null) {
- adapter.onSuggestionClicked(suggestionId);
- return true;
- } else {
- return false;
- }
- }
-
- return false;
- }
-
- protected boolean onSearchClicked(int method) {
- if (mSearchClickListener != null) {
- return mSearchClickListener.onSearchClicked(method);
- }
- return false;
- }
-
- /**
- * Filters the suggestions list when the search text changes.
- */
- private class SearchTextWatcher implements TextWatcher {
- @Override
- public void afterTextChanged(Editable s) {
- boolean empty = s.length() == 0;
- if (empty != mQueryWasEmpty) {
- mQueryWasEmpty = empty;
- updateUi(empty);
- }
- if (mUpdateSuggestions) {
- if (mQueryListener != null) {
- mQueryListener.onQueryChanged();
- }
- }
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- }
- }
-
- /**
- * Handles key events on the suggestions list view.
- */
- protected class SuggestionsViewKeyListener implements View.OnKeyListener {
- @Override
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- if (event.getAction() == KeyEvent.ACTION_DOWN
- && v instanceof SuggestionsListView<?>) {
- SuggestionsListView<?> listView = (SuggestionsListView<?>) v;
- if (onSuggestionKeyDown(listView.getSuggestionsAdapter(),
- listView.getSelectedItemId(), keyCode, event)) {
- return true;
- }
- }
- return forwardKeyToQueryTextView(keyCode, event);
- }
- }
-
- private class InputMethodCloser implements SuggestionsView.OnScrollListener {
-
- @Override
- public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
- int totalItemCount) {
- }
-
- @Override
- public void onScrollStateChanged(AbsListView view, int scrollState) {
- considerHidingInputMethod();
- }
- }
-
- /**
- * Listens for clicks on the source selector.
- */
- private class SearchGoButtonClickListener implements View.OnClickListener {
- @Override
- public void onClick(View view) {
- onSearchClicked(Logger.SEARCH_METHOD_BUTTON);
- }
- }
-
- /**
- * This class handles enter key presses in the query text view.
- */
- private class QueryTextEditorActionListener implements OnEditorActionListener {
- @Override
- public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
- boolean consumed = false;
- if (event != null) {
- if (event.getAction() == KeyEvent.ACTION_UP) {
- consumed = onSearchClicked(Logger.SEARCH_METHOD_KEYBOARD);
- } else if (event.getAction() == KeyEvent.ACTION_DOWN) {
- // we have to consume the down event so that we receive the up event too
- consumed = true;
- }
- }
- if (DBG) Log.d(TAG, "onEditorAction consumed=" + consumed);
- return consumed;
- }
- }
-
- /**
- * Handles key events on the search and voice search buttons,
- * by refocusing to EditText.
- */
- private class ButtonsKeyListener implements View.OnKeyListener {
- @Override
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- return forwardKeyToQueryTextView(keyCode, event);
- }
- }
-
- private boolean forwardKeyToQueryTextView(int keyCode, KeyEvent event) {
- if (!event.isSystem() && shouldForwardToQueryTextView(keyCode)) {
- if (DBG) Log.d(TAG, "Forwarding key to query box: " + event);
- if (mQueryTextView.requestFocus()) {
- return mQueryTextView.dispatchKeyEvent(event);
- }
- }
- return false;
- }
-
- private boolean shouldForwardToQueryTextView(int keyCode) {
- switch (keyCode) {
- case KeyEvent.KEYCODE_DPAD_UP:
- case KeyEvent.KEYCODE_DPAD_DOWN:
- case KeyEvent.KEYCODE_DPAD_LEFT:
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- case KeyEvent.KEYCODE_DPAD_CENTER:
- case KeyEvent.KEYCODE_ENTER:
- case KeyEvent.KEYCODE_SEARCH:
- return false;
- default:
- return true;
- }
- }
-
- /**
- * Hides the input method when the suggestions get focus.
- */
- private class SuggestListFocusListener implements OnFocusChangeListener {
- @Override
- public void onFocusChange(View v, boolean focused) {
- if (DBG) Log.d(TAG, "Suggestions focus change, now: " + focused);
- if (focused) {
- considerHidingInputMethod();
- }
- }
- }
-
- private class QueryTextViewFocusListener implements OnFocusChangeListener {
- @Override
- public void onFocusChange(View v, boolean focused) {
- if (DBG) Log.d(TAG, "Query focus change, now: " + focused);
- if (focused) {
- // The query box got focus, show the input method
- showInputMethodForQuery();
- }
- }
- }
-
- protected class SuggestionsObserver extends DataSetObserver {
- @Override
- public void onChanged() {
- onSuggestionsChanged();
- }
- }
-
- public interface QueryListener {
- void onQueryChanged();
- }
-
- public interface SearchClickListener {
- boolean onSearchClicked(int method);
- }
-
- private class CloseClickListener implements OnClickListener {
- @Override
- public void onClick(View v) {
- if (!isQueryEmpty()) {
- mQueryTextView.setText("");
- } else {
- mExitClickListener.onClick(v);
- }
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/ui/SearchActivityViewSinglePane.java b/src/com/android/quicksearchbox/ui/SearchActivityViewSinglePane.java
deleted file mode 100644
index 9288fb6..0000000
--- a/src/com/android/quicksearchbox/ui/SearchActivityViewSinglePane.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Source;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.util.AttributeSet;
-import android.view.View;
-import android.widget.ImageButton;
-
-/**
- * Finishes the containing activity on BACK, even if input method is showing.
- */
-public class SearchActivityViewSinglePane extends SearchActivityView {
-
- public SearchActivityViewSinglePane(Context context) {
- super(context);
- }
-
- public SearchActivityViewSinglePane(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public SearchActivityViewSinglePane(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- @Override
- public void onResume() {
- focusQueryTextView();
- }
-
- @Override
- public void considerHidingInputMethod() {
- mQueryTextView.hideInputMethod();
- }
-
- @Override
- public void onStop() {
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionClickListener.java b/src/com/android/quicksearchbox/ui/SuggestionClickListener.java
deleted file mode 100644
index da062cd..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionClickListener.java
+++ /dev/null
@@ -1,41 +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.ui;
-
-/**
- * Listener interface for clicks on suggestions.
- */
-public interface SuggestionClickListener {
-
- /**
- * Called when a suggestion is clicked.
- *
- * @param adapter Adapter that contains the clicked suggestion.
- * @param suggestionId The ID of the suggestion clicked. If the suggestion list is flat, this
- * will be the position within the list.
- */
- void onSuggestionClicked(SuggestionsAdapter<?> adapter, long suggestionId);
-
- /**
- * Called when the "query refine" button of a suggestion is clicked.
- *
- * @param adapter Adapter that contains the clicked suggestion.
- * @param suggestionId The ID of the suggestion clicked. If the suggestion list is flat, this
- * will be the position within the list.
- */
- void onSuggestionQueryRefineClicked(SuggestionsAdapter<?> adapter, long suggestionId);
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionView.java b/src/com/android/quicksearchbox/ui/SuggestionView.java
deleted file mode 100644
index 636ecd5..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionView.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.Suggestion;
-
-/**
- * Interface to be implemented by any view appearing in the list of suggestions.
- */
-public interface SuggestionView {
- /**
- * Set the view's contents based on the given suggestion.
- */
- void bindAsSuggestion(Suggestion suggestion, String userQuery);
-
- /**
- * Binds this view to a list adapter.
- *
- * @param adapter The adapter of the list which the view is appearing in
- * @param position The position of this view with the list.
- */
- void bindAdapter(SuggestionsAdapter<?> adapter, long position);
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionViewFactory.java b/src/com/android/quicksearchbox/ui/SuggestionViewFactory.java
deleted file mode 100644
index 27cb596..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionViewFactory.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.SuggestionCursor;
-
-import android.view.View;
-import android.view.ViewGroup;
-
-import java.util.Collection;
-
-/**
- * Factory interface for suggestion views.
- */
-public interface SuggestionViewFactory {
-
- /**
- * Returns all the view types that are used by this factory. Each view type corresponds to a
- * specific layout that is used to display suggestions. The returned set must have at least one
- * item in it.
- *
- * View types must be unique across all suggestion view factories.
- */
- Collection<String> getSuggestionViewTypes();
-
- /**
- * Returns the view type to be used for displaying the given suggestion. This MUST correspond to
- * one of the view types returned by {@link #getSuggestionViewTypes()}.
- */
- String getViewType(Suggestion suggestion);
-
- /**
- * Gets a view corresponding to the current suggestion in the given cursor.
- *
- * @param convertView The old view to reuse, if possible. Note: You should check that this view
- * is non-null and of an appropriate type before using. If it is not possible to convert
- * this view to display the correct data, this method can create a new view.
- * @param parent The parent that this view will eventually be attached to
- * @return A View corresponding to the data within this suggestion.
- */
- View getView(SuggestionCursor suggestion, String userQuery, View convertView, ViewGroup parent);
-
- /**
- * Checks whether this factory can create views for the given suggestion.
- */
- boolean canCreateView(Suggestion suggestion);
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionViewInflater.java b/src/com/android/quicksearchbox/ui/SuggestionViewInflater.java
deleted file mode 100644
index 9275b6e..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionViewInflater.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.SuggestionCursor;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-
-import java.util.Collection;
-import java.util.Collections;
-
-/**
- * Suggestion view factory that inflates views from XML.
- */
-public class SuggestionViewInflater implements SuggestionViewFactory {
-
- private final String mViewType;
- private final Class<?> mViewClass;
- private final int mLayoutId;
- private final Context mContext;
-
- /**
- * @param viewType The unique type of views inflated by this factory
- * @param viewClass The expected type of view classes.
- * @param layoutId resource ID of layout to use.
- * @param context Context to use for inflating the views.
- */
- public SuggestionViewInflater(String viewType, Class<? extends SuggestionView> viewClass,
- int layoutId, Context context) {
- mViewType = viewType;
- mViewClass = viewClass;
- mLayoutId = layoutId;
- mContext = context;
- }
-
- protected LayoutInflater getInflater() {
- return (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
-
- public Collection<String> getSuggestionViewTypes() {
- return Collections.singletonList(mViewType);
- }
-
- public View getView(SuggestionCursor suggestion, String userQuery,
- View convertView, ViewGroup parent) {
- if (convertView == null || !convertView.getClass().equals(mViewClass)) {
- int layoutId = mLayoutId;
- convertView = getInflater().inflate(layoutId, parent, false);
- }
- if (!(convertView instanceof SuggestionView)) {
- throw new IllegalArgumentException("Not a SuggestionView: " + convertView);
- }
- ((SuggestionView) convertView).bindAsSuggestion(suggestion, userQuery);
- return convertView;
- }
-
- public String getViewType(Suggestion suggestion) {
- return mViewType;
- }
-
- public boolean canCreateView(Suggestion suggestion) {
- return true;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionsAdapter.java b/src/com/android/quicksearchbox/ui/SuggestionsAdapter.java
deleted file mode 100644
index 825ae0d..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionsAdapter.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.SuggestionPosition;
-import com.android.quicksearchbox.Suggestions;
-
-import android.view.View.OnFocusChangeListener;
-import android.widget.ExpandableListAdapter;
-import android.widget.ListAdapter;
-
-/**
- * Interface for suggestions adapters.
- *
- * @param <A> the adapter class used by the UI, probably either {@link ListAdapter} or
- * {@link ExpandableListAdapter}.
- */
-public interface SuggestionsAdapter<A> {
-
- /**
- * Sets the listener to be notified of clicks on suggestions.
- */
- void setSuggestionClickListener(SuggestionClickListener listener);
-
- /**
- * Sets the listener to be notified of focus change events on suggestion views.
- */
- void setOnFocusChangeListener(OnFocusChangeListener l);
-
- /**
- * Sets the current suggestions.
- */
- void setSuggestions(Suggestions suggestions);
-
- /**
- * Indicates if there's any suggestions in this adapter.
- */
- boolean isEmpty();
-
- /**
- * Gets the current suggestions.
- */
- Suggestions getSuggestions();
-
- /**
- * Gets the cursor and position corresponding to the given suggestion ID.
- * @param suggestionId Suggestion ID.
- */
- SuggestionPosition getSuggestion(long suggestionId);
-
- /**
- * Handles a regular click on a suggestion.
- *
- * @param suggestionId The ID of the suggestion clicked. If the suggestion list is flat, this
- * will be the position within the list.
- */
- void onSuggestionClicked(long suggestionId);
-
- /**
- * Handles a click on the query refinement button.
- *
- * @param suggestionId The ID of the suggestion clicked. If the suggestion list is flat, this
- * will be the position within the list.
- */
- void onSuggestionQueryRefineClicked(long suggestionId);
-
- /**
- * Gets the adapter to be used by the UI view.
- */
- A getListAdapter();
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionsAdapterBase.java b/src/com/android/quicksearchbox/ui/SuggestionsAdapterBase.java
deleted file mode 100644
index 244e3f9..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionsAdapterBase.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.SuggestionPosition;
-import com.android.quicksearchbox.Suggestions;
-
-import android.database.DataSetObserver;
-import android.util.Log;
-import android.view.View;
-import android.view.View.OnFocusChangeListener;
-import android.view.ViewGroup;
-
-import java.util.HashMap;
-
-/**
- * Base class for suggestions adapters. The templated class A is the list adapter class.
- */
-public abstract class SuggestionsAdapterBase<A> implements SuggestionsAdapter<A> {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SuggestionsAdapter";
-
- private DataSetObserver mDataSetObserver;
-
- private SuggestionCursor mCurrentSuggestions;
- private final HashMap<String, Integer> mViewTypeMap;
- private final SuggestionViewFactory mViewFactory;
-
- private Suggestions mSuggestions;
-
- private SuggestionClickListener mSuggestionClickListener;
- private OnFocusChangeListener mOnFocusChangeListener;
-
- private boolean mClosed = false;
-
- protected SuggestionsAdapterBase(SuggestionViewFactory viewFactory) {
- mViewFactory = viewFactory;
- mViewTypeMap = new HashMap<String, Integer>();
- for (String viewType : mViewFactory.getSuggestionViewTypes()) {
- if (!mViewTypeMap.containsKey(viewType)) {
- mViewTypeMap.put(viewType, mViewTypeMap.size());
- }
- }
- }
-
- @Override
- public abstract boolean isEmpty();
-
- public boolean isClosed() {
- return mClosed;
- }
-
- public void close() {
- setSuggestions(null);
- mClosed = true;
- }
-
- @Override
- public void setSuggestionClickListener(SuggestionClickListener listener) {
- mSuggestionClickListener = listener;
- }
-
- @Override
- public void setOnFocusChangeListener(OnFocusChangeListener l) {
- mOnFocusChangeListener = l;
- }
-
- @Override
- public void setSuggestions(Suggestions suggestions) {
- if (mSuggestions == suggestions) {
- return;
- }
- if (mClosed) {
- if (suggestions != null) {
- suggestions.release();
- }
- return;
- }
- if (mDataSetObserver == null) {
- mDataSetObserver = new MySuggestionsObserver();
- }
- // TODO: delay the change if there are no suggestions for the currently visible tab.
- if (mSuggestions != null) {
- mSuggestions.unregisterDataSetObserver(mDataSetObserver);
- mSuggestions.release();
- }
- mSuggestions = suggestions;
- if (mSuggestions != null) {
- mSuggestions.registerDataSetObserver(mDataSetObserver);
- }
- onSuggestionsChanged();
- }
-
- @Override
- public Suggestions getSuggestions() {
- return mSuggestions;
- }
-
- @Override
- public abstract SuggestionPosition getSuggestion(long suggestionId);
-
- protected int getCount() {
- return mCurrentSuggestions == null ? 0 : mCurrentSuggestions.getCount();
- }
-
- protected SuggestionPosition getSuggestion(int position) {
- if (mCurrentSuggestions == null) return null;
- return new SuggestionPosition(mCurrentSuggestions, position);
- }
-
- protected int getViewTypeCount() {
- return mViewTypeMap.size();
- }
-
- private String suggestionViewType(Suggestion suggestion) {
- String viewType = mViewFactory.getViewType(suggestion);
- if (!mViewTypeMap.containsKey(viewType)) {
- throw new IllegalStateException("Unknown viewType " + viewType);
- }
- return viewType;
- }
-
- protected int getSuggestionViewType(SuggestionCursor cursor, int position) {
- if (cursor == null) {
- return 0;
- }
- cursor.moveTo(position);
- return mViewTypeMap.get(suggestionViewType(cursor));
- }
-
- protected int getSuggestionViewTypeCount() {
- return mViewTypeMap.size();
- }
-
- protected View getView(SuggestionCursor suggestions, int position, long suggestionId,
- View convertView, ViewGroup parent) {
- suggestions.moveTo(position);
- View v = mViewFactory.getView(suggestions, suggestions.getUserQuery(), convertView, parent);
- if (v instanceof SuggestionView) {
- ((SuggestionView) v).bindAdapter(this, suggestionId);
- } else {
- SuggestionViewClickListener l = new SuggestionViewClickListener(suggestionId);
- v.setOnClickListener(l);
- }
-
- if (mOnFocusChangeListener != null) {
- v.setOnFocusChangeListener(mOnFocusChangeListener);
- }
- return v;
- }
-
- protected void onSuggestionsChanged() {
- if (DBG) Log.d(TAG, "onSuggestionsChanged(" + mSuggestions + ")");
- SuggestionCursor cursor = null;
- if (mSuggestions != null) {
- cursor = mSuggestions.getResult();
- }
- changeSuggestions(cursor);
- }
-
- public SuggestionCursor getCurrentSuggestions() {
- return mCurrentSuggestions;
- }
-
- /**
- * Replace the cursor.
- *
- * This does not close the old cursor. Instead, all the cursors are closed in
- * {@link #setSuggestions(Suggestions)}.
- */
- private void changeSuggestions(SuggestionCursor newCursor) {
- if (DBG) {
- Log.d(TAG, "changeCursor(" + newCursor + ") count=" +
- (newCursor == null ? 0 : newCursor.getCount()));
- }
- if (newCursor == mCurrentSuggestions) {
- if (newCursor != null) {
- // Shortcuts may have changed without the cursor changing.
- notifyDataSetChanged();
- }
- return;
- }
- mCurrentSuggestions = newCursor;
- if (mCurrentSuggestions != null) {
- notifyDataSetChanged();
- } else {
- notifyDataSetInvalidated();
- }
- }
-
- @Override
- public void onSuggestionClicked(long suggestionId) {
- if (mClosed) {
- Log.w(TAG, "onSuggestionClicked after close");
- } else if (mSuggestionClickListener != null) {
- mSuggestionClickListener.onSuggestionClicked(this, suggestionId);
- }
- }
-
- @Override
- public void onSuggestionQueryRefineClicked(long suggestionId) {
- if (mClosed) {
- Log.w(TAG, "onSuggestionQueryRefineClicked after close");
- } else if (mSuggestionClickListener != null) {
- mSuggestionClickListener.onSuggestionQueryRefineClicked(this, suggestionId);
- }
- }
-
- @Override
- public abstract A getListAdapter();
-
- protected abstract void notifyDataSetInvalidated();
-
- protected abstract void notifyDataSetChanged();
-
- private class MySuggestionsObserver extends DataSetObserver {
- @Override
- public void onChanged() {
- onSuggestionsChanged();
- }
- }
-
- private class SuggestionViewClickListener implements View.OnClickListener {
- private final long mSuggestionId;
- public SuggestionViewClickListener(long suggestionId) {
- mSuggestionId = suggestionId;
- }
- @Override
- public void onClick(View v) {
- onSuggestionClicked(mSuggestionId);
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionsListAdapter.java b/src/com/android/quicksearchbox/ui/SuggestionsListAdapter.java
deleted file mode 100644
index 8bbdfbf..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionsListAdapter.java
+++ /dev/null
@@ -1,101 +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.ui;
-
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.ListAdapter;
-
-import com.android.quicksearchbox.SuggestionCursor;
-import com.android.quicksearchbox.SuggestionPosition;
-import com.android.quicksearchbox.Suggestions;
-
-/**
- * Uses a {@link Suggestions} object to back a {@link SuggestionsView}.
- */
-public class SuggestionsListAdapter extends SuggestionsAdapterBase<ListAdapter> {
-
- private Adapter mAdapter;
-
- public SuggestionsListAdapter(SuggestionViewFactory viewFactory) {
- super(viewFactory);
- mAdapter = new Adapter();
- }
-
- @Override
- public boolean isEmpty() {
- return mAdapter.getCount() == 0;
- }
-
- @Override
- public SuggestionPosition getSuggestion(long suggestionId) {
- return new SuggestionPosition(getCurrentSuggestions(), (int) suggestionId);
- }
-
- @Override
- public BaseAdapter getListAdapter() {
- return mAdapter;
- }
-
- @Override
- public void notifyDataSetChanged() {
- mAdapter.notifyDataSetChanged();
- }
-
- @Override
- public void notifyDataSetInvalidated() {
- mAdapter.notifyDataSetInvalidated();
- }
-
- class Adapter extends BaseAdapter {
-
- @Override
- public int getCount() {
- SuggestionCursor s = getCurrentSuggestions();
- return s == null ? 0 : s.getCount();
- }
-
- @Override
- public Object getItem(int position) {
- return getSuggestion(position);
- }
-
- @Override
- public long getItemId(int position) {
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- return SuggestionsListAdapter.this.getView(
- getCurrentSuggestions(), position, position, convertView, parent);
- }
-
- @Override
- public int getItemViewType(int position) {
- return getSuggestionViewType(getCurrentSuggestions(), position);
- }
-
- @Override
- public int getViewTypeCount() {
- return getSuggestionViewTypeCount();
- }
-
- }
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionsListView.java b/src/com/android/quicksearchbox/ui/SuggestionsListView.java
deleted file mode 100644
index a162f3a..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionsListView.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.ui;
-
-import android.view.View;
-import android.widget.AbsListView;
-
-/**
- * Interface for suggestions list UI views.
- */
-public interface SuggestionsListView<A> {
-
- /**
- * See {@link View#setOnKeyListener}.
- */
- void setOnKeyListener(View.OnKeyListener l);
-
- /**
- * See {@link AbsListView#setOnScrollListener}.
- */
- void setOnScrollListener(AbsListView.OnScrollListener l);
-
- /**
- * See {@link View#setOnFocusChangeListener}.
- */
- void setOnFocusChangeListener(View.OnFocusChangeListener l);
-
- /**
- * See {@link View#setVisibility}.
- */
- void setVisibility(int visibility);
-
- /**
- * Sets the adapter for the list. See {@link AbsListView#setAdapter}
- */
- void setSuggestionsAdapter(SuggestionsAdapter<A> adapter);
-
- /**
- * Gets the adapter for the list.
- */
- SuggestionsAdapter<A> getSuggestionsAdapter();
-
- /**
- * Gets the ID of the currently selected item.
- */
- long getSelectedItemId();
-
-}
diff --git a/src/com/android/quicksearchbox/ui/SuggestionsView.java b/src/com/android/quicksearchbox/ui/SuggestionsView.java
deleted file mode 100644
index 51deb67..0000000
--- a/src/com/android/quicksearchbox/ui/SuggestionsView.java
+++ /dev/null
@@ -1,76 +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.ui;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-
-import com.android.quicksearchbox.SuggestionPosition;
-
-/**
- * Holds a list of suggestions.
- */
-public class SuggestionsView extends ListView implements SuggestionsListView<ListAdapter> {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SuggestionsView";
-
- private SuggestionsAdapter<ListAdapter> mSuggestionsAdapter;
-
- public SuggestionsView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- @Override
- public void setSuggestionsAdapter(SuggestionsAdapter<ListAdapter> adapter) {
- super.setAdapter(adapter == null ? null : adapter.getListAdapter());
- mSuggestionsAdapter = adapter;
- }
-
- @Override
- public SuggestionsAdapter<ListAdapter> getSuggestionsAdapter() {
- return mSuggestionsAdapter;
- }
-
- @Override
- public void onFinishInflate() {
- super.onFinishInflate();
- setItemsCanFocus(true);
- }
-
- /**
- * Gets the position of the selected suggestion.
- *
- * @return A 0-based index, or {@code -1} if no suggestion is selected.
- */
- public int getSelectedPosition() {
- return getSelectedItemPosition();
- }
-
- /**
- * Gets the selected suggestion.
- *
- * @return {@code null} if no suggestion is selected.
- */
- public SuggestionPosition getSelectedSuggestion() {
- return (SuggestionPosition) getSelectedItem();
- }
-
-
-}
diff --git a/src/com/android/quicksearchbox/ui/WebSearchSuggestionView.java b/src/com/android/quicksearchbox/ui/WebSearchSuggestionView.java
deleted file mode 100644
index e01bd7e..0000000
--- a/src/com/android/quicksearchbox/ui/WebSearchSuggestionView.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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.ui;
-
-import com.android.quicksearchbox.QsbApplication;
-import com.android.quicksearchbox.R;
-import com.android.quicksearchbox.Suggestion;
-import com.android.quicksearchbox.SuggestionFormatter;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.KeyEvent;
-import android.view.View;
-
-/**
- * View for web search suggestions.
- */
-public class WebSearchSuggestionView extends BaseSuggestionView {
-
- private static final String VIEW_ID = "web_search";
-
- private final SuggestionFormatter mSuggestionFormatter;
-
- public WebSearchSuggestionView(Context context, AttributeSet attrs) {
- super(context, attrs);
- mSuggestionFormatter = QsbApplication.get(context).getSuggestionFormatter();
- }
-
- @Override
- protected void onFinishInflate() {
- super.onFinishInflate();
- KeyListener keyListener = new KeyListener();
- setOnKeyListener(keyListener);
- mIcon2.setOnKeyListener(keyListener);
- mIcon2.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- onSuggestionQueryRefineClicked();
- }
- });
- mIcon2.setFocusable(true);
- }
-
- @Override
- public void bindAsSuggestion(Suggestion suggestion, String userQuery) {
- super.bindAsSuggestion(suggestion, userQuery);
-
- CharSequence text1 = mSuggestionFormatter.formatSuggestion(userQuery,
- suggestion.getSuggestionText1());
- setText1(text1);
- setIsHistorySuggestion(suggestion.isHistorySuggestion());
- }
-
- private void setIsHistorySuggestion(boolean isHistory) {
- if (isHistory) {
- mIcon1.setImageResource(R.drawable.ic_history_suggestion);
- mIcon1.setVisibility(VISIBLE);
- } else {
- mIcon1.setVisibility(INVISIBLE);
- }
- }
-
- private class KeyListener implements View.OnKeyListener {
- public boolean onKey(View v, int keyCode, KeyEvent event) {
- boolean consumed = false;
- if (event.getAction() == KeyEvent.ACTION_DOWN) {
- if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && v != mIcon2) {
- consumed = mIcon2.requestFocus();
- } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && v == mIcon2) {
- consumed = requestFocus();
- }
- }
- return consumed;
- }
- }
-
- public static class Factory extends SuggestionViewInflater {
-
- public Factory(Context context) {
- super(VIEW_ID, WebSearchSuggestionView.class, R.layout.web_search_suggestion, context);
- }
-
- @Override
- public boolean canCreateView(Suggestion suggestion) {
- return suggestion.isWebSearchSuggestion();
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/AsyncDataSetObservable.java b/src/com/android/quicksearchbox/util/AsyncDataSetObservable.java
deleted file mode 100644
index 5a75ff6..0000000
--- a/src/com/android/quicksearchbox/util/AsyncDataSetObservable.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.util;
-
-import android.database.DataSetObservable;
-import android.os.Handler;
-
-/**
- * A version of {@link DataSetObservable} that performs callbacks on given {@link Handler}.
- */
-public class AsyncDataSetObservable extends DataSetObservable {
-
- private final Handler mHandler;
-
- private final Runnable mChangedRunnable = new Runnable() {
- public void run() {
- AsyncDataSetObservable.super.notifyChanged();
- }
- };
-
- private final Runnable mInvalidatedRunnable = new Runnable() {
- public void run() {
- AsyncDataSetObservable.super.notifyInvalidated();
- }
- };
-
- /**
- * @param handler Handler to run callbacks on.
- */
- public AsyncDataSetObservable(Handler handler) {
- mHandler = handler;
- }
-
- @Override
- public void notifyChanged() {
- if (mHandler == null) {
- super.notifyChanged();
- } else {
- mHandler.post(mChangedRunnable);
- }
- }
-
- @Override
- public void notifyInvalidated() {
- if (mHandler == null) {
- super.notifyInvalidated();
- } else {
- mHandler.post(mInvalidatedRunnable);
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/BarrierConsumer.java b/src/com/android/quicksearchbox/util/BarrierConsumer.java
deleted file mode 100644
index d02ae79..0000000
--- a/src/com/android/quicksearchbox/util/BarrierConsumer.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.util;
-
-import java.util.ArrayList;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * A consumer that consumes a fixed number of values. When the expected number of values
- * has been consumed, further values are rejected.
- */
-public class BarrierConsumer<A> implements Consumer<A> {
-
- private final Lock mLock = new ReentrantLock();
- private final Condition mNotFull = mLock.newCondition();
-
- private final int mExpectedCount;
-
- // Set to null when getValues() returns.
- private ArrayList<A> mValues;
-
- /**
- * Constructs a new BarrierConsumer.
- *
- * @param expectedCount The number of values to consume.
- */
- public BarrierConsumer(int expectedCount) {
- mExpectedCount = expectedCount;
- mValues = new ArrayList<A>(expectedCount);
- }
-
- /**
- * Blocks until the expected number of results is available, or until the thread is
- * interrupted. This method should not be called multiple times.
- *
- * @return A list of values, never {@code null}.
- */
- public ArrayList<A> getValues() {
- mLock.lock();
- try {
- try {
- while (!isFull()) {
- mNotFull.await();
- }
- } catch (InterruptedException ex) {
- // Return the values that we've gotten so far
- }
- ArrayList<A> values = mValues;
- mValues = null; // mark that getValues() has returned
- return values;
- } finally {
- mLock.unlock();
- }
- }
-
- public boolean consume(A value) {
- mLock.lock();
- try {
- // Do nothing if getValues() has alrady returned,
- // or enough values have already been consumed
- if (mValues == null || isFull()) {
- return false;
- }
- mValues.add(value);
- if (isFull()) {
- // Wake up any thread waiting in getValues()
- mNotFull.signal();
- }
- return true;
- } finally {
- mLock.unlock();
- }
- }
-
- private boolean isFull() {
- return mValues.size() == mExpectedCount;
- }
-}
diff --git a/src/com/android/quicksearchbox/util/BatchingNamedTaskExecutor.java b/src/com/android/quicksearchbox/util/BatchingNamedTaskExecutor.java
deleted file mode 100644
index 08d3ed7..0000000
--- a/src/com/android/quicksearchbox/util/BatchingNamedTaskExecutor.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * 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.util;
-
-
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Executes NamedTasks in batches of a given size. Tasks are queued until
- * executeNextBatch is called.
- */
-public class BatchingNamedTaskExecutor implements NamedTaskExecutor {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.BatchingNamedTaskExecutor";
-
- private final NamedTaskExecutor mExecutor;
-
- /** Queue of tasks waiting to be dispatched to mExecutor **/
- private final ArrayList<NamedTask> mQueuedTasks = new ArrayList<NamedTask>();
-
- /**
- * Creates a new BatchingSourceTaskExecutor.
- *
- * @param executor A SourceTaskExecutor for actually executing the tasks.
- */
- public BatchingNamedTaskExecutor(NamedTaskExecutor executor) {
- mExecutor = executor;
- }
-
- public void execute(NamedTask task) {
- synchronized (mQueuedTasks) {
- if (DBG) Log.d(TAG, "Queuing " + task);
- mQueuedTasks.add(task);
- }
- }
-
- private void dispatch(NamedTask task) {
- if (DBG) Log.d(TAG, "Dispatching " + task);
- mExecutor.execute(task);
- }
-
- /**
- * Instructs the executor to submit the next batch of results.
- * @param batchSize the maximum number of entries to execute.
- */
- public void executeNextBatch(int batchSize) {
- NamedTask[] batch = new NamedTask[0];
- synchronized (mQueuedTasks) {
- int count = Math.min(mQueuedTasks.size(), batchSize);
- List<NamedTask> nextTasks = mQueuedTasks.subList(0, count);
- batch = nextTasks.toArray(batch);
- nextTasks.clear();
- if (DBG) Log.d(TAG, "Dispatching batch of " + count);
- }
-
- for (NamedTask task : batch) {
- dispatch(task);
- }
- }
-
- /**
- * Cancel any unstarted tasks running in this executor. This instance
- * should not be re-used after calling this method.
- */
- public void cancelPendingTasks() {
- synchronized (mQueuedTasks) {
- mQueuedTasks.clear();
- }
- }
-
- public void close() {
- cancelPendingTasks();
- mExecutor.close();
- }
-}
diff --git a/src/com/android/quicksearchbox/util/CachedLater.java b/src/com/android/quicksearchbox/util/CachedLater.java
deleted file mode 100644
index 49e86ba..0000000
--- a/src/com/android/quicksearchbox/util/CachedLater.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.util;
-
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Abstract base class for a one-place cache that holds a value that is produced
- * asynchronously.
- *
- * @param <A> The type of the data held in the cache.
- */
-public abstract class CachedLater<A> implements NowOrLater<A> {
-
- private static final String TAG = "QSB.AsyncCache";
- private static final boolean DBG = false;
-
- private final Object mLock = new Object();
-
- private A mValue;
-
- private boolean mCreating;
- private boolean mValid;
-
- private List<Consumer<? super A>> mWaitingConsumers;
-
- /**
- * Creates the object to store in the cache. This method must call
- * {@link #store} when it's done.
- * This method must not block.
- */
- protected abstract void create();
-
- /**
- * Saves a new value to the cache.
- */
- protected void store(A value) {
- if (DBG) Log.d(TAG, "store()");
- List<Consumer<? super A>> waitingConsumers;
- synchronized (mLock) {
- mValue = value;
- mValid = true;
- mCreating = false;
- waitingConsumers = mWaitingConsumers;
- mWaitingConsumers = null;
- }
- if (waitingConsumers != null) {
- for (Consumer<? super A> consumer : waitingConsumers) {
- if (DBG) Log.d(TAG, "Calling consumer: " + consumer);
- consumer.consume(value);
- }
- }
- }
-
- /**
- * Gets the value.
- *
- * @param consumer A consumer that will be given the cached value.
- * The consumer may be called synchronously, or asynchronously on
- * an unspecified thread.
- */
- public void getLater(Consumer<? super A> consumer) {
- if (DBG) Log.d(TAG, "getLater()");
- boolean valid;
- A value;
- synchronized (mLock) {
- valid = mValid;
- value = mValue;
- if (!valid) {
- if (mWaitingConsumers == null) {
- mWaitingConsumers = new ArrayList<Consumer<? super A>>();
- }
- mWaitingConsumers.add(consumer);
- }
- }
- if (valid) {
- if (DBG) Log.d(TAG, "valid, calling consumer synchronously");
- consumer.consume(value);
- } else {
- boolean create = false;
- synchronized (mLock) {
- if (!mCreating) {
- mCreating = true;
- create = true;
- }
- }
- if (create) {
- if (DBG) Log.d(TAG, "not valid, calling create()");
- create();
- } else {
- if (DBG) Log.d(TAG, "not valid, already creating");
- }
- }
- }
-
- /**
- * Clears the cache.
- */
- public void clear() {
- if (DBG) Log.d(TAG, "clear()");
- synchronized (mLock) {
- mValue = null;
- mValid = false;
- }
- }
-
- public boolean haveNow() {
- synchronized (mLock) {
- return mValid;
- }
- }
-
- public synchronized A getNow() {
- synchronized (mLock) {
- if (!haveNow()) {
- throw new IllegalStateException("getNow() called when haveNow() is false");
- }
- return mValue;
- }
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/Consumer.java b/src/com/android/quicksearchbox/util/Consumer.java
deleted file mode 100644
index 942b5dc..0000000
--- a/src/com/android/quicksearchbox/util/Consumer.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.util;
-
-/**
- * Interface for data consumers.
- *
- * @param <A> The type of data to consume.
- */
-public interface Consumer<A> {
-
- /**
- * Consumes a value.
- *
- * @param value The value to consume.
- * @return {@code true} if the value was accepted, {@code false} otherwise.
- */
- boolean consume(A value);
-
-}
diff --git a/src/com/android/quicksearchbox/util/Consumers.java b/src/com/android/quicksearchbox/util/Consumers.java
deleted file mode 100644
index 52a97b1..0000000
--- a/src/com/android/quicksearchbox/util/Consumers.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.util;
-
-import android.os.Handler;
-
-/**
- * Consumer utilities.
- */
-public class Consumers {
-
- private Consumers() {}
-
- public static <A extends QuietlyCloseable> void consumeCloseable(Consumer<A> consumer,
- A value) {
- boolean accepted = false;
- try {
- accepted = consumer.consume(value);
- } finally {
- if (!accepted && value != null) value.close();
- }
- }
-
- public static <A> void consumeAsync(Handler handler,
- final Consumer<A> consumer, final A value) {
- if (handler == null) {
- consumer.consume(value);
- } else {
- handler.post(new Runnable() {
- public void run() {
- consumer.consume(value);
- }
- });
- }
- }
-
- public static <A extends QuietlyCloseable> void consumeCloseableAsync(Handler handler,
- final Consumer<A> consumer, final A value) {
- if (handler == null) {
- consumeCloseable(consumer, value);
- } else {
- handler.post(new Runnable() {
- public void run() {
- consumeCloseable(consumer, value);
- }
- });
- }
- }
-
- public static <A> Consumer<A> createAsyncConsumer(
- final Handler handler, final Consumer<A> consumer) {
- return new Consumer<A>() {
- public boolean consume(A value) {
- consumeAsync(handler, consumer, value);
- return true;
- }
- };
- }
-
- public static <A extends QuietlyCloseable> Consumer<A> createAsyncCloseableConsumer(
- final Handler handler, final Consumer<A> consumer) {
- return new Consumer<A>() {
- public boolean consume(A value) {
- consumeCloseableAsync(handler, consumer, value);
- return true;
- }
- };
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/Factory.java b/src/com/android/quicksearchbox/util/Factory.java
deleted file mode 100644
index 8aebe5c..0000000
--- a/src/com/android/quicksearchbox/util/Factory.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.util;
-
-public interface Factory<A> {
-
- A create();
-
-}
diff --git a/src/com/android/quicksearchbox/util/HttpHelper.java b/src/com/android/quicksearchbox/util/HttpHelper.java
deleted file mode 100644
index f300db4..0000000
--- a/src/com/android/quicksearchbox/util/HttpHelper.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.util;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * An interface that can issue HTTP GET / POST requests
- * with timeouts.
- */
-public interface HttpHelper {
-
- public String get(GetRequest request) throws IOException, HttpException;
-
- public String get(String url, Map<String,String> requestHeaders)
- throws IOException, HttpException;
-
- public String post(PostRequest request) throws IOException, HttpException;
-
- public String post(String url, Map<String,String> requestHeaders, String content)
- throws IOException, HttpException;
-
- public void setConnectTimeout(int timeoutMillis);
-
- public void setReadTimeout(int timeoutMillis);
-
- public static class GetRequest {
- private String mUrl;
- private Map<String,String> mHeaders;
-
- /**
- * Creates a new request.
- */
- public GetRequest() {
- }
-
- /**
- * Creates a new request.
- *
- * @param url Request URI.
- */
- public GetRequest(String url) {
- mUrl = url;
- }
-
- /**
- * Gets the request URI.
- */
- public String getUrl() {
- return mUrl;
- }
- /**
- * Sets the request URI.
- */
- public void setUrl(String url) {
- mUrl = url;
- }
-
- /**
- * Gets the request headers.
- *
- * @return The response headers. May return {@code null} if no headers are set.
- */
- public Map<String, String> getHeaders() {
- return mHeaders;
- }
-
- /**
- * Sets a request header.
- *
- * @param name Header name.
- * @param value Header value.
- */
- public void setHeader(String name, String value) {
- if (mHeaders == null) {
- mHeaders = new HashMap<String,String>();
- }
- mHeaders.put(name, value);
- }
- }
-
- public static class PostRequest extends GetRequest {
-
- private String mContent;
-
- public PostRequest() {
- }
-
- public PostRequest(String url) {
- super(url);
- }
-
- public void setContent(String content) {
- mContent = content;
- }
-
- public String getContent() {
- return mContent;
- }
- }
-
- /**
- * A HTTP exception.
- */
- public static class HttpException extends IOException {
- private final int mStatusCode;
- private final String mReasonPhrase;
-
- public HttpException(int statusCode, String reasonPhrase) {
- super(statusCode + " " + reasonPhrase);
- mStatusCode = statusCode;
- mReasonPhrase = reasonPhrase;
- }
-
- /**
- * Gets the HTTP response status code.
- */
- public int getStatusCode() {
- return mStatusCode;
- }
-
- /**
- * Gets the HTTP response reason phrase.
- */
- public String getReasonPhrase() {
- return mReasonPhrase;
- }
- }
-
- /**
- * An interface for URL rewriting.
- */
- public static interface UrlRewriter {
- public String rewrite(String url);
- }
-}
diff --git a/src/com/android/quicksearchbox/util/JavaNetHttpHelper.java b/src/com/android/quicksearchbox/util/JavaNetHttpHelper.java
deleted file mode 100644
index 5a0c8b9..0000000
--- a/src/com/android/quicksearchbox/util/JavaNetHttpHelper.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * 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.util;
-
-import android.os.Build;
-import android.util.Log;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Simple HTTP client API.
- */
-public class JavaNetHttpHelper implements HttpHelper {
- private static final String TAG = "QSB.JavaNetHttpHelper";
- private static final boolean DBG = false;
-
- private static final int BUFFER_SIZE = 1024 * 4;
- private static final String USER_AGENT_HEADER = "User-Agent";
- private static final String DEFAULT_CHARSET = "UTF-8";
-
- private int mConnectTimeout;
- private int mReadTimeout;
- private final String mUserAgent;
- private final HttpHelper.UrlRewriter mRewriter;
-
- /**
- * Creates a new HTTP helper.
- *
- * @param rewriter URI rewriter
- * @param userAgent User agent string, e.g. "MyApp/1.0".
- */
- public JavaNetHttpHelper(UrlRewriter rewriter, String userAgent) {
- mUserAgent = userAgent + " (" + Build.DEVICE + " " + Build.ID + ")";
- mRewriter = rewriter;
- }
-
- /**
- * Executes a GET request and returns the response content.
- *
- * @param request Request.
- * @return The response content. This is the empty string if the response
- * contained no content.
- * @throws IOException If an IO error occurs.
- * @throws HttpException If the response has a status code other than 200.
- */
- public String get(GetRequest request) throws IOException, HttpException {
- return get(request.getUrl(), request.getHeaders());
- }
-
- /**
- * Executes a GET request and returns the response content.
- *
- * @param url Request URI.
- * @param requestHeaders Request headers.
- * @return The response content. This is the empty string if the response
- * contained no content.
- * @throws IOException If an IO error occurs.
- * @throws HttpException If the response has a status code other than 200.
- */
- public String get(String url, Map<String,String> requestHeaders)
- throws IOException, HttpException {
- HttpURLConnection c = null;
- try {
- c = createConnection(url, requestHeaders);
- c.setRequestMethod("GET");
- c.connect();
- return getResponseFrom(c);
- } finally {
- if (c != null) {
- c.disconnect();
- }
- }
- }
-
- @Override
- public String post(PostRequest request) throws IOException, HttpException {
- return post(request.getUrl(), request.getHeaders(), request.getContent());
- }
-
- public String post(String url, Map<String,String> requestHeaders, String content)
- throws IOException, HttpException {
- HttpURLConnection c = null;
- try {
- if (requestHeaders == null) {
- requestHeaders = new HashMap<String, String>();
- }
- requestHeaders.put("Content-Length",
- Integer.toString(content == null ? 0 : content.length()));
- c = createConnection(url, requestHeaders);
- c.setDoOutput(content != null);
- c.setRequestMethod("POST");
- c.connect();
- if (content != null) {
- OutputStreamWriter writer = new OutputStreamWriter(c.getOutputStream());
- writer.write(content);
- writer.close();
- }
- return getResponseFrom(c);
- } finally {
- if (c != null) {
- c.disconnect();
- }
- }
- }
-
- private HttpURLConnection createConnection(String url, Map<String, String> headers)
- throws IOException, HttpException {
- URL u = new URL(mRewriter.rewrite(url));
- if (DBG) Log.d(TAG, "URL=" + url + " rewritten='" + u + "'");
- HttpURLConnection c = (HttpURLConnection) u.openConnection();
- if (headers != null) {
- for (Map.Entry<String,String> e : headers.entrySet()) {
- String name = e.getKey();
- String value = e.getValue();
- if (DBG) Log.d(TAG, " " + name + ": " + value);
- c.addRequestProperty(name, value);
- }
- }
- c.addRequestProperty(USER_AGENT_HEADER, mUserAgent);
- if (mConnectTimeout != 0) {
- c.setConnectTimeout(mConnectTimeout);
- }
- if (mReadTimeout != 0) {
- c.setReadTimeout(mReadTimeout);
- }
- return c;
- }
-
- private String getResponseFrom(HttpURLConnection c) throws IOException, HttpException {
- if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
- throw new HttpException(c.getResponseCode(), c.getResponseMessage());
- }
- if (DBG) {
- Log.d(TAG, "Content-Type: " + c.getContentType() + " (assuming " +
- DEFAULT_CHARSET + ")");
- }
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(c.getInputStream(), DEFAULT_CHARSET));
- StringBuilder string = new StringBuilder();
- char[] chars = new char[BUFFER_SIZE];
- int bytes;
- while ((bytes = reader.read(chars)) != -1) {
- string.append(chars, 0, bytes);
- }
- return string.toString();
- }
-
- public void setConnectTimeout(int timeoutMillis) {
- mConnectTimeout = timeoutMillis;
- }
-
- public void setReadTimeout(int timeoutMillis) {
- mReadTimeout = timeoutMillis;
- }
-
- /**
- * A Url rewriter that does nothing, i.e., returns the
- * url that is passed to it.
- */
- public static class PassThroughRewriter implements UrlRewriter {
- @Override
- public String rewrite(String url) {
- return url;
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/util/LevenshteinDistance.java b/src/com/android/quicksearchbox/util/LevenshteinDistance.java
deleted file mode 100644
index ad86d41..0000000
--- a/src/com/android/quicksearchbox/util/LevenshteinDistance.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * 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.util;
-
-/**
- * This class represents the matrix used in the Levenshtein distance algorithm, together
- * with the algorithm itself which operates on the matrix.
- *
- * We also track of the individual operations applied to transform the source string into the
- * target string so we can trace the path taken through the matrix afterwards, in order to
- * perform the formatting as required.
- */
-public class LevenshteinDistance {
- public static final int EDIT_DELETE = 0;
- public static final int EDIT_INSERT = 1;
- public static final int EDIT_REPLACE = 2;
- public static final int EDIT_UNCHANGED = 3;
-
- private final Token[] mSource;
- private final Token[] mTarget;
- private final int[][] mEditTypeTable;
- private final int[][] mDistanceTable;
-
- public LevenshteinDistance(Token[] source, Token[] target) {
- final int sourceSize = source.length;
- final int targetSize = target.length;
- final int[][] editTab = new int[sourceSize+1][targetSize+1];
- final int[][] distTab = new int[sourceSize+1][targetSize+1];
- editTab[0][0] = EDIT_UNCHANGED;
- distTab[0][0] = 0;
- for (int i = 1; i <= sourceSize; ++i) {
- editTab[i][0] = EDIT_DELETE;
- distTab[i][0] = i;
- }
- for (int i = 1; i <= targetSize; ++i) {
- editTab[0][i] = EDIT_INSERT;
- distTab[0][i] = i;
- }
- mEditTypeTable = editTab;
- mDistanceTable = distTab;
- mSource = source;
- mTarget = target;
- }
-
- /**
- * Implementation of Levenshtein distance algorithm.
- *
- * @return The Levenshtein distance.
- */
- public int calculate() {
- final Token[] src = mSource;
- final Token[] trg = mTarget;
- final int sourceLen = src.length;
- final int targetLen = trg.length;
- final int[][] distTab = mDistanceTable;
- final int[][] editTab = mEditTypeTable;
- for (int s = 1; s <= sourceLen; ++s) {
- Token sourceToken = src[s-1];
- for (int t = 1; t <= targetLen; ++t) {
- Token targetToken = trg[t-1];
- int cost = sourceToken.prefixOf(targetToken) ? 0 : 1;
-
- int distance = distTab[s-1][t] + 1;
- int type = EDIT_DELETE;
-
- int d = distTab[s][t - 1];
- if (d + 1 < distance ) {
- distance = d + 1;
- type = EDIT_INSERT;
- }
-
- d = distTab[s - 1][t - 1];
- if (d + cost < distance) {
- distance = d + cost;
- type = cost == 0 ? EDIT_UNCHANGED : EDIT_REPLACE;
- }
- distTab[s][t] = distance;
- editTab[s][t] = type;
- }
- }
- return distTab[sourceLen][targetLen];
- }
-
- /**
- * Gets the list of operations which were applied to each target token; {@link #calculate} must
- * have been called on this object before using this method.
- * @return A list of {@link EditOperation}s indicating the origin of each token in the target
- * string. The position of the token indicates the position in the source string of the
- * token that was unchanged/replaced, or the position in the source after which a target
- * token was inserted.
- */
- public EditOperation[] getTargetOperations() {
- final int trgLen = mTarget.length;
- final EditOperation[] ops = new EditOperation[trgLen];
- int targetPos = trgLen;
- int sourcePos = mSource.length;
- final int[][] editTab = mEditTypeTable;
- while (targetPos > 0) {
- int editType = editTab[sourcePos][targetPos];
- switch (editType) {
- case LevenshteinDistance.EDIT_DELETE:
- sourcePos--;
- break;
- case LevenshteinDistance.EDIT_INSERT:
- targetPos--;
- ops[targetPos] = new EditOperation(editType, sourcePos);
- break;
- case LevenshteinDistance.EDIT_UNCHANGED:
- case LevenshteinDistance.EDIT_REPLACE:
- targetPos--;
- sourcePos--;
- ops[targetPos] = new EditOperation(editType, sourcePos);
- break;
- }
- }
-
- return ops;
- }
-
- public static final class EditOperation {
- private final int mType;
- private final int mPosition;
- public EditOperation(int type, int position) {
- mType = type;
- mPosition = position;
- }
- public int getType() {
- return mType;
- }
- public int getPosition() {
- return mPosition;
- }
- }
-
- public static final class Token implements CharSequence {
- private final char[] mContainer;
- public final int mStart;
- public final int mEnd;
-
- public Token(char[] container, int start, int end) {
- mContainer = container;
- mStart = start;
- mEnd = end;
- }
-
- public int length() {
- return mEnd - mStart;
- }
-
- @Override
- public String toString() {
- // used in tests only.
- return subSequence(0, length());
- }
-
- public boolean prefixOf(final Token that) {
- final int len = length();
- if (len > that.length()) return false;
- final int thisStart = mStart;
- final int thatStart = that.mStart;
- final char[] thisContainer = mContainer;
- final char[] thatContainer = that.mContainer;
- for (int i = 0; i < len; ++i) {
- if (thisContainer[thisStart + i] != thatContainer[thatStart + i]) {
- return false;
- }
- }
- return true;
- }
-
- public char charAt(int index) {
- return mContainer[index + mStart];
- }
-
- public String subSequence(int start, int end) {
- return new String(mContainer, mStart + start, length());
- }
-
- }
-}
diff --git a/src/com/android/quicksearchbox/util/NamedTask.java b/src/com/android/quicksearchbox/util/NamedTask.java
deleted file mode 100644
index fa11267..0000000
--- a/src/com/android/quicksearchbox/util/NamedTask.java
+++ /dev/null
@@ -1,26 +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.util;
-
-/**
- * A task that has a name.
- */
-public interface NamedTask extends Runnable {
-
- String getName();
-
-}
diff --git a/src/com/android/quicksearchbox/util/NamedTaskExecutor.java b/src/com/android/quicksearchbox/util/NamedTaskExecutor.java
deleted file mode 100644
index 67670af..0000000
--- a/src/com/android/quicksearchbox/util/NamedTaskExecutor.java
+++ /dev/null
@@ -1,44 +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.util;
-
-/**
- * Runs tasks that have a name tag.
- */
-public interface NamedTaskExecutor {
-
- /**
- * Schedules a task for execution. Implementations should not throw
- * {@link java.util.concurrent.RejectedExecutionException} if the task
- * cannot be run. They should drop it silently instead.
- */
- void execute(NamedTask task);
-
- /**
- * Stops any unstarted tasks from running. Implementations of this method must be
- * idempotent.
- */
- void cancelPendingTasks();
-
- /**
- * Shuts down this executor, freeing any resources that it owns. The executor
- * may not be used after calling this method. Implementations of this method must be
- * idempotent.
- */
- void close();
-
-}
diff --git a/src/com/android/quicksearchbox/util/NoOpConsumer.java b/src/com/android/quicksearchbox/util/NoOpConsumer.java
deleted file mode 100644
index bac138c..0000000
--- a/src/com/android/quicksearchbox/util/NoOpConsumer.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.util;
-
-import com.android.quicksearchbox.util.Consumer;
-
-/**
- * A Consumer that does nothing with the objects it receives.
- */
-public class NoOpConsumer<A> implements Consumer<A> {
- public boolean consume(A result) {
- // Tell the caller that we haven't taken ownership of this result.
- return false;
- }
-}
-
diff --git a/src/com/android/quicksearchbox/util/Now.java b/src/com/android/quicksearchbox/util/Now.java
deleted file mode 100644
index 88328fd..0000000
--- a/src/com/android/quicksearchbox/util/Now.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.util;
-
-/**
- * A {@link NowOrLater} object that is always ready now.
- */
-public class Now<C> implements NowOrLater<C> {
-
- private final C mValue;
-
- public Now(C value) {
- mValue = value;
- }
-
- public void getLater(Consumer<? super C> consumer) {
- consumer.consume(getNow());
- }
-
- public C getNow() {
- return mValue;
- }
-
- public boolean haveNow() {
- return true;
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/NowOrLater.java b/src/com/android/quicksearchbox/util/NowOrLater.java
deleted file mode 100644
index 6029ef6..0000000
--- a/src/com/android/quicksearchbox/util/NowOrLater.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.util;
-
-/**
- * Interface for an object that may be constructed asynchronously. In cases when the object is ready
- * (on constructible) immediately, it provides synchronous access to it. Otherwise, the object can
- * be sent to a {@link Consumer} later.
- */
-public interface NowOrLater<C> {
-
- /**
- * Indicates if the object is ready (or constructible synchronously).
- */
- boolean haveNow();
-
- /**
- * Gets the object now. Should only be called if {@link #haveNow()} returns {@code true},
- * otherwise an {@link IllegalStateException} will be thrown.
- */
- C getNow();
-
- /**
- * Request the object asynchronously. This can be called even if the object is ready now, in
- * which case the callback may be made in context. The thread on which the consumer is called
- * back depends on the implementation.
- */
- void getLater(Consumer<? super C> consumer);
-
-}
diff --git a/src/com/android/quicksearchbox/util/NowOrLaterWrapper.java b/src/com/android/quicksearchbox/util/NowOrLaterWrapper.java
deleted file mode 100644
index efe0901..0000000
--- a/src/com/android/quicksearchbox/util/NowOrLaterWrapper.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.util;
-
-/**
- * {@link NowOrLater} class that converts from one type to another.
- */
-public abstract class NowOrLaterWrapper<A, B> implements NowOrLater<B> {
-
- private final NowOrLater<A> mWrapped;
-
- public NowOrLaterWrapper(NowOrLater<A> wrapped) {
- mWrapped = wrapped;
- }
-
- public void getLater(final Consumer<? super B> consumer) {
- mWrapped.getLater(new Consumer<A>(){
- public boolean consume(A value) {
- return consumer.consume(get(value));
- }});
- }
-
- public B getNow() {
- return get(mWrapped.getNow());
- }
-
- public boolean haveNow() {
- return mWrapped.haveNow();
- }
-
- /**
- * Perform the appropriate conversion. This will be called once for every call to
- * {@link #getLater(Consumer)} or {@link #getNow()}. The thread that it's called on will depend
- * on the behaviour of the wrapped object and the caller.
- */
- public abstract B get(A value);
-
-}
diff --git a/src/com/android/quicksearchbox/util/PerNameExecutor.java b/src/com/android/quicksearchbox/util/PerNameExecutor.java
deleted file mode 100644
index 3abd58f..0000000
--- a/src/com/android/quicksearchbox/util/PerNameExecutor.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.util;
-
-
-import java.util.HashMap;
-
-/**
- * Uses a separate executor for each task name.
- */
-public class PerNameExecutor implements NamedTaskExecutor {
-
- private final Factory<NamedTaskExecutor> mExecutorFactory;
- private HashMap<String, NamedTaskExecutor> mExecutors;
-
- /**
- * @param executorFactory Used to run the commands.
- */
- public PerNameExecutor(Factory<NamedTaskExecutor> executorFactory) {
- mExecutorFactory = executorFactory;
- }
-
- public synchronized void cancelPendingTasks() {
- if (mExecutors == null) return;
- for (NamedTaskExecutor executor : mExecutors.values()) {
- executor.cancelPendingTasks();
- }
- }
-
- public synchronized void close() {
- if (mExecutors == null) return;
- for (NamedTaskExecutor executor : mExecutors.values()) {
- executor.close();
- }
- }
-
- public synchronized void execute(NamedTask task) {
- if (mExecutors == null) {
- mExecutors = new HashMap<String, NamedTaskExecutor>();
- }
- String name = task.getName();
- NamedTaskExecutor executor = mExecutors.get(name);
- if (executor == null) {
- executor = mExecutorFactory.create();
- mExecutors.put(name, executor);
- }
- executor.execute(task);
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/PriorityThreadFactory.java b/src/com/android/quicksearchbox/util/PriorityThreadFactory.java
deleted file mode 100644
index b75df0d..0000000
--- a/src/com/android/quicksearchbox/util/PriorityThreadFactory.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.util;
-
-import android.os.Process;
-
-import java.util.concurrent.ThreadFactory;
-
-/**
- * A thread factory that creates threads with a given thread priority.
- */
-public class PriorityThreadFactory implements ThreadFactory {
-
- private final int mPriority;
-
- /**
- * Creates a new thread factory.
- *
- * @param priority The thread priority of the threads created by this factory.
- * For values, see {@link Process}.
- */
- public PriorityThreadFactory(int priority) {
- mPriority = priority;
- }
-
- public Thread newThread(Runnable r) {
- return new Thread(r) {
- @Override
- public void run() {
- Process.setThreadPriority(mPriority);
- super.run();
- }
- };
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/QuietlyCloseable.java b/src/com/android/quicksearchbox/util/QuietlyCloseable.java
deleted file mode 100644
index d442f8f..0000000
--- a/src/com/android/quicksearchbox/util/QuietlyCloseable.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.util;
-
-import java.io.Closeable;
-
-/**
- * Interface for closeable objects whose close method doesn't throw IOExceptions.
- */
-public interface QuietlyCloseable extends Closeable {
-
- void close();
-
-}
diff --git a/src/com/android/quicksearchbox/util/SQLiteAsyncQuery.java b/src/com/android/quicksearchbox/util/SQLiteAsyncQuery.java
deleted file mode 100644
index e4afecb..0000000
--- a/src/com/android/quicksearchbox/util/SQLiteAsyncQuery.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.util;
-
-import android.database.sqlite.SQLiteDatabase;
-
-/**
- * Abstract helper base class for asynchronous SQLite queries.
- *
- * @param <A> The type of the result of the query.
- */
-public abstract class SQLiteAsyncQuery<A> {
-
- /**
- * Performs a query and computes some value from the result
- *
- * @param db A readable database.
- * @return The result of the query.
- */
- protected abstract A performQuery(SQLiteDatabase db);
-
- /**
- * Runs the query against the database and passes the result to the consumer.
- */
- public void run(SQLiteDatabase db, Consumer<A> consumer) {
- A result = performQuery(db);
- consumer.consume(result);
- }
-}
diff --git a/src/com/android/quicksearchbox/util/SQLiteTransaction.java b/src/com/android/quicksearchbox/util/SQLiteTransaction.java
deleted file mode 100644
index aa423cd..0000000
--- a/src/com/android/quicksearchbox/util/SQLiteTransaction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.util;
-
-import android.database.sqlite.SQLiteDatabase;
-
-/**
- * Abstract helper base class for SQLite write transactions.
- */
-public abstract class SQLiteTransaction {
-
- /**
- * Executes the statements that form the transaction.
- *
- * @param db A writable database.
- * @return {@code true} if the transaction should be committed.
- */
- protected abstract boolean performTransaction(SQLiteDatabase db);
-
- /**
- * Runs the transaction against the database. The results are committed if
- * {@link #performTransaction(SQLiteDatabase)} completes normally and returns {@code true}.
- */
- public void run(SQLiteDatabase db) {
- db.beginTransaction();
- try {
- if (performTransaction(db)) {
- db.setTransactionSuccessful();
- }
- } finally {
- db.endTransaction();
- }
- }
-}
diff --git a/src/com/android/quicksearchbox/util/SingleThreadNamedTaskExecutor.java b/src/com/android/quicksearchbox/util/SingleThreadNamedTaskExecutor.java
deleted file mode 100644
index be4012f..0000000
--- a/src/com/android/quicksearchbox/util/SingleThreadNamedTaskExecutor.java
+++ /dev/null
@@ -1,102 +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.util;
-
-import android.util.Log;
-
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-
-/**
- * Executor that uses a single thread and an unbounded work queue.
- */
-public class SingleThreadNamedTaskExecutor implements NamedTaskExecutor {
-
- private static final boolean DBG = false;
- private static final String TAG = "QSB.SingleThreadNamedTaskExecutor";
-
- private final LinkedBlockingQueue<NamedTask> mQueue;
- private final Thread mWorker;
- private volatile boolean mClosed = false;
-
- public SingleThreadNamedTaskExecutor(ThreadFactory threadFactory) {
- mQueue = new LinkedBlockingQueue<NamedTask>();
- mWorker = threadFactory.newThread(new Worker());
- mWorker.start();
- }
-
- public void cancelPendingTasks() {
- if (DBG) Log.d(TAG, "Cancelling " + mQueue.size() + " tasks: " + mWorker.getName());
- if (mClosed) {
- throw new IllegalStateException("cancelPendingTasks() after close()");
- }
- mQueue.clear();
- }
-
- public void close() {
- mClosed = true;
- mWorker.interrupt();
- mQueue.clear();
- }
-
- public void execute(NamedTask task) {
- if (mClosed) {
- throw new IllegalStateException("execute() after close()");
- }
- mQueue.add(task);
- }
-
- private class Worker implements Runnable {
- public void run() {
- try {
- loop();
- } finally {
- if (!mClosed) Log.w(TAG, "Worker exited before close");
- }
- }
-
- private void loop() {
- Thread currentThread = Thread.currentThread();
- String threadName = currentThread.getName();
- while (!mClosed) {
- NamedTask task;
- try {
- task = mQueue.take();
- } catch (InterruptedException ex) {
- continue;
- }
- currentThread.setName(threadName + " " + task.getName());
- try {
- if (DBG) Log.d(TAG, "Running task " + task.getName());
- task.run();
- if (DBG) Log.d(TAG, "Task " + task.getName() + " complete");
- } catch (RuntimeException ex) {
- Log.e(TAG, "Task " + task.getName() + " failed", ex);
- }
- }
- }
- }
-
- public static Factory<NamedTaskExecutor> factory(final ThreadFactory threadFactory) {
- return new Factory<NamedTaskExecutor>() {
- public NamedTaskExecutor create() {
- return new SingleThreadNamedTaskExecutor(threadFactory);
- }
- };
- }
-
-}
diff --git a/src/com/android/quicksearchbox/util/Util.java b/src/com/android/quicksearchbox/util/Util.java
deleted file mode 100644
index 373d2af..0000000
--- a/src/com/android/quicksearchbox/util/Util.java
+++ /dev/null
@@ -1,90 +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.util;
-
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.res.Resources;
-import android.net.Uri;
-import android.util.Log;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * General utilities.
- */
-public class Util {
-
- private static final String TAG = "QSB.Util";
-
- public static <A> Set<A> setOfFirstN(List<A> list, int n) {
- int end = Math.min(list.size(), n);
- HashSet<A> set = new HashSet<A>(end);
- for (int i = 0; i < end; i++) {
- set.add(list.get(i));
- }
- return set;
- }
-
- public static Uri getResourceUri(Context packageContext, int res) {
- try {
- Resources resources = packageContext.getResources();
- return getResourceUri(resources, packageContext.getPackageName(), res);
- } catch (Resources.NotFoundException e) {
- Log.e(TAG, "Resource not found: " + res + " in " + packageContext.getPackageName());
- return null;
- }
- }
-
- public static Uri getResourceUri(Context context, ApplicationInfo appInfo, int res) {
- try {
- Resources resources = context.getPackageManager().getResourcesForApplication(appInfo);
- return getResourceUri(resources, appInfo.packageName, res);
- } catch (PackageManager.NameNotFoundException e) {
- Log.e(TAG, "Resources not found for " + appInfo.packageName);
- return null;
- } catch (Resources.NotFoundException e) {
- Log.e(TAG, "Resource not found: " + res + " in " + appInfo.packageName);
- return null;
- }
- }
-
- private static Uri getResourceUri(Resources resources, String appPkg, int res)
- throws Resources.NotFoundException {
- String resPkg = resources.getResourcePackageName(res);
- String type = resources.getResourceTypeName(res);
- String name = resources.getResourceEntryName(res);
- return makeResourceUri(appPkg, resPkg, type, name);
- }
-
- private static Uri makeResourceUri(String appPkg, String resPkg, String type, String name) {
- Uri.Builder uriBuilder = new Uri.Builder();
- uriBuilder.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE);
- uriBuilder.encodedAuthority(appPkg);
- uriBuilder.appendEncodedPath(type);
- if (!appPkg.equals(resPkg)) {
- uriBuilder.appendEncodedPath(resPkg + ":" + name);
- } else {
- uriBuilder.appendEncodedPath(name);
- }
- return uriBuilder.build();
- }
-}