package com.actionbarsherlock.widget;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.ResourceCursorAdapter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.R;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.WeakHashMap;
private static final boolean DBG = false;
private static final String LOG_TAG = "SuggestionsAdapter";
private static final int QUERY_LIMIT = 50;
static final int REFINE_NONE = 0;
static final int REFINE_BY_ENTRY = 1;
static final int REFINE_ALL = 2;
private SearchManager mSearchManager;
private SearchView mSearchView;
private Context mProviderContext;
private WeakHashMap<String, Drawable.ConstantState> mOutsideDrawablesCache;
private boolean mClosed = false;
private int mQueryRefinement = REFINE_BY_ENTRY;
private ColorStateList mUrlColor;
static final int INVALID_INDEX = -1;
private int mText1Col = INVALID_INDEX;
private int mText2Col = INVALID_INDEX;
private int mText2UrlCol = INVALID_INDEX;
private int mIconName1Col = INVALID_INDEX;
private int mIconName2Col = INVALID_INDEX;
private int mFlagsCol = INVALID_INDEX;
SearchableInfo mSearchable, WeakHashMap<String, Drawable.ConstantState> outsideDrawablesCache) {
super(context,
R.layout.abs__search_dropdown_item_icons_2line,
null,
true);
mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
mProviderContext = mContext;
mSearchView = searchView;
mOutsideDrawablesCache = outsideDrawablesCache;
}
mQueryRefinement = refineWhat;
}
return mQueryRefinement;
}
@Override
return false;
}
@Override
if (DBG) Log.d(LOG_TAG, "runQueryOnBackgroundThread(" + constraint + ")");
String query = (constraint == null) ? "" : constraint.toString();
Cursor cursor = null;
if (mSearchView.getVisibility() != View.VISIBLE
|| mSearchView.getWindowVisibility() != View.VISIBLE) {
return null;
}
try {
cursor = getSuggestions(query, QUERY_LIMIT);
if (cursor != null) {
cursor.getCount();
return cursor;
}
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Search suggestions query threw an exception.", e);
}
return null;
}
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.query("")
.fragment("");
uriBuilder.appendPath(SearchManager.SUGGEST_URI_PATH_QUERY);
uriBuilder.appendPath(query);
if (limit > 0) {
uriBuilder.appendQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT, String.valueOf(limit));
}
Uri uri = uriBuilder.build();
return mContext.getContentResolver().query(uri, null, null, null, null);
}
if (DBG) Log.d(LOG_TAG, "close()");
changeCursor(null);
mClosed = true;
}
@Override
if (DBG) Log.d(LOG_TAG, "notifyDataSetChanged");
super.notifyDataSetChanged();
updateSpinnerState(getCursor());
}
@Override
if (DBG) Log.d(LOG_TAG, "notifyDataSetInvalidated");
super.notifyDataSetInvalidated();
updateSpinnerState(getCursor());
}
Bundle extras = cursor != null ? cursor.getExtras() : null;
if (DBG) {
Log.d(LOG_TAG, "updateSpinnerState - extra = "
+ (extras != null
? extras.getBoolean(SearchManager.CURSOR_EXTRA_KEY_IN_PROGRESS)
: null));
}
if (extras != null
&& extras.getBoolean(SearchManager.CURSOR_EXTRA_KEY_IN_PROGRESS)) {
return;
}
}
@Override
if (DBG) Log.d(LOG_TAG, "changeCursor(" + c + ")");
if (mClosed) {
Log.w(LOG_TAG, "Tried to change cursor after adapter was closed.");
if (c != null) c.close();
return;
}
try {
super.changeCursor(c);
if (c != null) {
mText1Col = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
mText2Col = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2);
mText2UrlCol = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2_URL);
mIconName1Col = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_1);
mIconName2Col = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_ICON_2);
mFlagsCol = c.getColumnIndex(SearchManager.SUGGEST_COLUMN_FLAGS);
}
} catch (Exception e) {
Log.e(LOG_TAG, "error changing cursor and caching columns", e);
}
}
@Override
public View
newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
v.setTag(new ChildViewCache(v));
return v;
}
public final TextView mText1;
public final TextView mText2;
public final ImageView mIcon1;
public final ImageView mIcon2;
public final ImageView mIconRefine;
mText1 = (TextView) v.findViewById(android.R.id.text1);
mText2 = (TextView) v.findViewById(android.R.id.text2);
mIcon1 = (ImageView) v.findViewById(android.R.id.icon1);
mIcon2 = (ImageView) v.findViewById(android.R.id.icon2);
mIconRefine = (ImageView) v.findViewById(R.id.edit_query);
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ChildViewCache views = (ChildViewCache) view.getTag();
int flags = 0;
if (mFlagsCol != INVALID_INDEX) {
flags = cursor.getInt(mFlagsCol);
}
if (views.mText1 != null) {
String text1 = getStringOrNull(cursor, mText1Col);
setViewText(views.mText1, text1);
}
if (views.mText2 != null) {
CharSequence text2 = getStringOrNull(cursor, mText2UrlCol);
if (text2 != null) {
text2 = formatUrl(text2);
} else {
text2 = getStringOrNull(cursor, mText2Col);
}
if (TextUtils.isEmpty(text2)) {
if (views.mText1 != null) {
views.mText1.setSingleLine(false);
views.mText1.setMaxLines(2);
}
} else {
if (views.mText1 != null) {
views.mText1.setSingleLine(true);
views.mText1.setMaxLines(1);
}
}
setViewText(views.mText2, text2);
}
if (views.mIcon1 != null) {
setViewDrawable(views.mIcon1, getIcon1(cursor), View.INVISIBLE);
}
if (views.mIcon2 != null) {
setViewDrawable(views.mIcon2, getIcon2(cursor), View.GONE);
}
if (mQueryRefinement == REFINE_ALL
|| (mQueryRefinement == REFINE_BY_ENTRY
&& (flags & SearchManager.FLAG_QUERY_REFINEMENT) != 0)) {
views.mIconRefine.setVisibility(View.VISIBLE);
views.mIconRefine.setTag(views.mText1.getText());
views.mIconRefine.setOnClickListener(this);
} else {
views.mIconRefine.setVisibility(View.GONE);
}
}
Object tag = v.getTag();
if (tag instanceof CharSequence) {
mSearchView.onQueryRefine((CharSequence) tag);
}
}
private CharSequence
formatUrl(CharSequence url) {
if (mUrlColor == null) {
TypedValue colorValue = new TypedValue();
mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl, colorValue, true);
mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
}
SpannableString text = new SpannableString(url);
text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null),
0, url.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return text;
}
private void setViewText(TextView v, CharSequence text) {
v.setText(text);
if (TextUtils.isEmpty(text)) {
v.setVisibility(View.GONE);
} else {
v.setVisibility(View.VISIBLE);
}
}
private Drawable
getIcon1(Cursor cursor) {
if (mIconName1Col == INVALID_INDEX) {
return null;
}
String value = cursor.getString(mIconName1Col);
Drawable drawable = getDrawableFromResourceValue(value);
if (drawable != null) {
return drawable;
}
return getDefaultIcon1(cursor);
}
private Drawable
getIcon2(Cursor cursor) {
if (mIconName2Col == INVALID_INDEX) {
return null;
}
String value = cursor.getString(mIconName2Col);
return getDrawableFromResourceValue(value);
}
private void setViewDrawable(ImageView v, Drawable drawable,
int nullVisibility) {
v.setImageDrawable(drawable);
if (drawable == null) {
v.setVisibility(nullVisibility);
} else {
v.setVisibility(View.VISIBLE);
drawable.setVisible(false, false);
drawable.setVisible(true, false);
}
}
@Override
if (cursor == null) {
return null;
}
String query = getColumnString(cursor, SearchManager.SUGGEST_COLUMN_QUERY);
if (query != null) {
return query;
}
return null;
}
@Override
public View
getView(
int position, View convertView, ViewGroup parent) {
try {
return super.getView(position, convertView, parent);
} catch (RuntimeException e) {
Log.w(LOG_TAG, "Search suggestions cursor threw exception.", e);
View v = newView(mContext, mCursor, parent);
if (v != null) {
ChildViewCache views = (ChildViewCache) v.getTag();
TextView tv = views.mText1;
tv.setText(e.toString());
}
return v;
}
}
if (drawableId == null || drawableId.length() == 0 || "0".equals(drawableId)) {
return null;
}
try {
int resourceId = Integer.parseInt(drawableId);
String drawableUri = ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mProviderContext.getPackageName() + "/" + resourceId;
Drawable drawable = checkIconCache(drawableUri);
if (drawable != null) {
return drawable;
}
drawable = mProviderContext.getResources().getDrawable(resourceId);
storeInIconCache(drawableUri, drawable);
return drawable;
} catch (NumberFormatException nfe) {
Drawable drawable = checkIconCache(drawableId);
if (drawable != null) {
return drawable;
}
Uri uri = Uri.parse(drawableId);
drawable = getDrawable(uri);
storeInIconCache(drawableId, drawable);
return drawable;
} catch (Resources.NotFoundException nfe) {
Log.w(LOG_TAG, "Icon resource not found: " + drawableId);
return null;
}
}
try {
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
try {
return getTheDrawable(uri);
} catch (Resources.NotFoundException ex) {
throw new FileNotFoundException("Resource does not exist: " + uri);
}
} else {
InputStream stream = mProviderContext.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(LOG_TAG, "Error closing icon stream for " + uri, ex);
}
}
}
} catch (FileNotFoundException fnfe) {
Log.w(LOG_TAG, "Icon not found: " + uri + ", " + fnfe.getMessage());
return null;
}
}
public Drawable
getTheDrawable(Uri uri)
throws FileNotFoundException {
String authority = uri.getAuthority();
Resources r;
if (TextUtils.isEmpty(authority)) {
throw new FileNotFoundException("No authority: " + uri);
} else {
try {
r = mContext.getPackageManager().getResourcesForApplication(authority);
} catch (NameNotFoundException ex) {
throw new FileNotFoundException("No package found for authority: " + uri);
}
}
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);
}
return r.getDrawable(id);
}
Drawable.ConstantState cached = mOutsideDrawablesCache.get(resourceUri);
if (cached == null) {
return null;
}
if (DBG) Log.d(LOG_TAG, "Found icon in cache: " + resourceUri);
return cached.newDrawable();
}
if (drawable != null) {
mOutsideDrawablesCache.put(resourceUri, drawable.getConstantState());
}
}
return mContext.getPackageManager().getDefaultActivityIcon();
}
String componentIconKey = component.flattenToShortString();
if (mOutsideDrawablesCache.containsKey(componentIconKey)) {
Drawable.ConstantState cached = mOutsideDrawablesCache.get(componentIconKey);
return cached == null ? null : cached.newDrawable(mProviderContext.getResources());
}
Drawable drawable = getActivityIcon(component);
Drawable.ConstantState toCache = drawable == null ? null : drawable.getConstantState();
mOutsideDrawablesCache.put(componentIconKey, toCache);
return drawable;
}
PackageManager pm = mContext.getPackageManager();
final ActivityInfo activityInfo;
try {
activityInfo = pm.getActivityInfo(component, PackageManager.GET_META_DATA);
} catch (NameNotFoundException ex) {
Log.w(LOG_TAG, ex.toString());
return null;
}
int iconId = activityInfo.getIconResource();
if (iconId == 0) return null;
String pkg = component.getPackageName();
Drawable drawable = pm.getDrawable(pkg, iconId, activityInfo.applicationInfo);
if (drawable == null) {
Log.w(LOG_TAG, "Invalid icon resource " + iconId + " for "
+ component.flattenToShortString());
return null;
}
return drawable;
}
int col = cursor.getColumnIndex(columnName);
return getStringOrNull(cursor, col);
}
if (col == INVALID_INDEX) {
return null;
}
try {
return cursor.getString(col);
} catch (Exception e) {
Log.e(LOG_TAG,
"unexpected error retrieving valid column from cursor, "
+ "did the remote process die?", e);
return null;
}
}
}