DefaultSuggestionView.java revision 77909685887bd6db7454b73cf274afc3aca2f58d
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.quicksearchbox.ui;
18
19import com.android.quicksearchbox.R;
20import com.android.quicksearchbox.Source;
21import com.android.quicksearchbox.Suggestion;
22import com.android.quicksearchbox.util.Consumer;
23import com.android.quicksearchbox.util.NowOrLater;
24
25import android.content.Context;
26import android.content.res.ColorStateList;
27import android.graphics.drawable.Drawable;
28import android.text.Html;
29import android.text.Spannable;
30import android.text.SpannableString;
31import android.text.TextUtils;
32import android.text.style.TextAppearanceSpan;
33import android.util.AttributeSet;
34import android.util.Log;
35import android.view.View;
36import android.widget.ImageView;
37import android.widget.TextView;
38
39/**
40 * View for the items in the suggestions list. This includes promoted suggestions,
41 * sources, and suggestions under each source.
42 */
43public class DefaultSuggestionView extends BaseSuggestionView {
44
45    private static final boolean DBG = false;
46
47    private static final String VIEW_ID = "default";
48
49    private final String TAG = "QSB.DefaultSuggestionView";
50
51    private AsyncIcon mAsyncIcon1;
52    private AsyncIcon mAsyncIcon2;
53
54    public DefaultSuggestionView(Context context, AttributeSet attrs, int defStyle) {
55        super(context, attrs, defStyle);
56    }
57
58    public DefaultSuggestionView(Context context, AttributeSet attrs) {
59        super(context, attrs);
60    }
61
62    public DefaultSuggestionView(Context context) {
63        super(context);
64    }
65
66    @Override
67    protected void onFinishInflate() {
68        super.onFinishInflate();
69        mText1 = (TextView) findViewById(R.id.text1);
70        mText2 = (TextView) findViewById(R.id.text2);
71        mAsyncIcon1 = new AsyncIcon(mIcon1) {
72            // override default icon (when no other available) with default source icon
73            @Override
74            protected String getFallbackIconId(Source source) {
75                return source.getSourceIconUri().toString();
76            }
77            @Override
78            protected Drawable getFallbackIcon(Source source) {
79                return source.getSourceIcon();
80            }
81        };
82        mAsyncIcon2 = new AsyncIcon(mIcon2);
83    }
84
85    @Override
86    public void bindAsSuggestion(Suggestion suggestion, String userQuery) {
87        super.bindAsSuggestion(suggestion, userQuery);
88
89        CharSequence text1 = formatText(suggestion.getSuggestionText1(), suggestion);
90        CharSequence text2 = suggestion.getSuggestionText2Url();
91        if (text2 != null) {
92            text2 = formatUrl(text2);
93        } else {
94            text2 = formatText(suggestion.getSuggestionText2(), suggestion);
95        }
96        // If there is no text for the second line, allow the first line to be up to two lines
97        if (TextUtils.isEmpty(text2)) {
98            mText1.setSingleLine(false);
99            mText1.setMaxLines(2);
100            mText1.setEllipsize(TextUtils.TruncateAt.START);
101        } else {
102            mText1.setSingleLine(true);
103            mText1.setMaxLines(1);
104            mText1.setEllipsize(TextUtils.TruncateAt.MIDDLE);
105        }
106        setText1(text1);
107        setText2(text2);
108        mAsyncIcon1.set(suggestion.getSuggestionSource(), suggestion.getSuggestionIcon1());
109        mAsyncIcon2.set(suggestion.getSuggestionSource(), suggestion.getSuggestionIcon2());
110
111        if (DBG) {
112            Log.d(TAG, "bindAsSuggestion(), text1=" + text1 + ",text2=" + text2 + ",q='" +
113                    userQuery + ",fromHistory=" + isFromHistory());
114        }
115    }
116
117    private CharSequence formatUrl(CharSequence url) {
118        SpannableString text = new SpannableString(url);
119        ColorStateList colors = getResources().getColorStateList(R.color.url_text);
120        text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null),
121                0, url.length(),
122                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
123        return text;
124    }
125
126    private CharSequence formatText(String str, Suggestion suggestion) {
127        boolean isHtml = "html".equals(suggestion.getSuggestionFormat());
128        if (isHtml && looksLikeHtml(str)) {
129            return Html.fromHtml(str);
130        } else {
131            return str;
132        }
133    }
134
135    private boolean looksLikeHtml(String str) {
136        if (TextUtils.isEmpty(str)) return false;
137        for (int i = str.length() - 1; i >= 0; i--) {
138            char c = str.charAt(i);
139            if (c == '>' || c == '&') return true;
140        }
141        return false;
142    }
143
144    /**
145     * Sets the drawable in an image view, makes sure the view is only visible if there
146     * is a drawable.
147     */
148    private static void setViewDrawable(ImageView v, Drawable drawable) {
149        // Set the icon even if the drawable is null, since we need to clear any
150        // previous icon.
151        v.setImageDrawable(drawable);
152
153        if (drawable == null) {
154            v.setVisibility(View.GONE);
155        } else {
156            v.setVisibility(View.VISIBLE);
157
158            // This is a hack to get any animated drawables (like a 'working' spinner)
159            // to animate. You have to setVisible true on an AnimationDrawable to get
160            // it to start animating, but it must first have been false or else the
161            // call to setVisible will be ineffective. We need to clear up the story
162            // about animated drawables in the future, see http://b/1878430.
163            drawable.setVisible(false, false);
164            drawable.setVisible(true, false);
165        }
166    }
167
168    private class AsyncIcon {
169        private final ImageView mView;
170        private String mCurrentId;
171        private String mWantedId;
172
173        public AsyncIcon(ImageView view) {
174            mView = view;
175        }
176
177        public void set(final Source source, final String iconId) {
178            if (iconId != null) {
179                mWantedId = iconId;
180                if (!TextUtils.equals(mWantedId, mCurrentId)) {
181                    if (DBG) Log.d(TAG, "getting icon Id=" + iconId);
182                    NowOrLater<Drawable> icon = source.getIcon(iconId);
183                    if (icon.haveNow()) {
184                        if (DBG) Log.d(TAG, "getIcon ready now");
185                        handleNewDrawable(icon.getNow(), iconId, source);
186                    } else {
187                        // make sure old icon is not visible while new one is loaded
188                        if (DBG) Log.d(TAG , "getIcon getting later");
189                        clearDrawable();
190                        icon.getLater(new Consumer<Drawable>(){
191                            public boolean consume(Drawable icon) {
192                                if (DBG) {
193                                    Log.d(TAG, "IconConsumer.consume got id " + iconId +
194                                            " want id " + mWantedId);
195                                }
196                                // ensure we have not been re-bound since the request was made.
197                                if (TextUtils.equals(iconId, mWantedId)) {
198                                    handleNewDrawable(icon, iconId, source);
199                                    return true;
200                                }
201                                return false;
202                            }});
203                    }
204                }
205            } else {
206                mWantedId = null;
207                handleNewDrawable(null, null, source);
208            }
209        }
210
211        private void handleNewDrawable(Drawable icon, String id, Source source) {
212            if (icon == null) {
213                mWantedId = getFallbackIconId(source);
214                if (TextUtils.equals(mWantedId, mCurrentId)) {
215                    return;
216                }
217                icon = getFallbackIcon(source);
218            }
219            setDrawable(icon, id);
220        }
221
222        private void setDrawable(Drawable icon, String id) {
223            mCurrentId = id;
224            setViewDrawable(mView, icon);
225        }
226
227        private void clearDrawable() {
228            mCurrentId = null;
229            mView.setImageDrawable(null);
230        }
231
232        protected String getFallbackIconId(Source source) {
233            return null;
234        }
235
236        protected Drawable getFallbackIcon(Source source) {
237            return null;
238        }
239
240    }
241
242    public static class Factory extends SuggestionViewInflater {
243        public Factory(Context context) {
244            super(VIEW_ID, DefaultSuggestionView.class, R.layout.suggestion, context);
245        }
246    }
247
248}
249