DefaultSuggestionView.java revision f97ad17bd38e8b8331c53f4ba543998e7a0e7e4a
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.QsbApplication;
20import com.android.quicksearchbox.R;
21import com.android.quicksearchbox.Source;
22import com.android.quicksearchbox.Suggestion;
23import com.android.quicksearchbox.SuggestionCursor;
24import com.android.quicksearchbox.SuggestionFormatter;
25
26import android.content.Context;
27import android.content.res.ColorStateList;
28import android.graphics.drawable.Drawable;
29import android.text.Html;
30import android.text.Spannable;
31import android.text.SpannableString;
32import android.text.TextUtils;
33import android.text.style.TextAppearanceSpan;
34import android.util.AttributeSet;
35import android.util.Log;
36import android.view.KeyEvent;
37import android.view.View;
38import android.widget.ImageView;
39import android.widget.ListView;
40import android.widget.RelativeLayout;
41import android.widget.TextView;
42
43/**
44 * View for the items in the suggestions list. This includes promoted suggestions,
45 * sources, and suggestions under each source.
46 */
47public class DefaultSuggestionView extends RelativeLayout implements SuggestionView {
48
49    private static final boolean DBG = false;
50    private static final String TAG = "QSB.SuggestionView";
51
52    private TextView mText1;
53    private TextView mText2;
54    private ImageView mIcon1;
55    private ImageView mIcon2;
56    private final SuggestionFormatter mSuggestionFormatter;
57    private boolean mRefineable;
58    private int mPosition;
59    private SuggestionClickListener mClickListener;
60    private KeyListener mKeyListener;
61
62    public DefaultSuggestionView(Context context, AttributeSet attrs, int defStyle) {
63        super(context, attrs, defStyle);
64        mSuggestionFormatter = QsbApplication.get(context).getSuggestionFormatter();
65    }
66
67    public DefaultSuggestionView(Context context, AttributeSet attrs) {
68        super(context, attrs);
69        mSuggestionFormatter = QsbApplication.get(context).getSuggestionFormatter();
70    }
71
72    public DefaultSuggestionView(Context context) {
73        super(context);
74        mSuggestionFormatter = QsbApplication.get(context).getSuggestionFormatter();
75    }
76
77    @Override
78    protected void onFinishInflate() {
79        super.onFinishInflate();
80        mText1 = (TextView) findViewById(R.id.text1);
81        mText2 = (TextView) findViewById(R.id.text2);
82        mIcon1 = (ImageView) findViewById(R.id.icon1);
83        mIcon2 = (ImageView) findViewById(R.id.icon2);
84        // for some reason, creating mKeyListener inside the constructor causes it not to work.
85        mKeyListener = new KeyListener();
86
87        setOnKeyListener(mKeyListener);
88    }
89
90    public void bindAsSuggestion(SuggestionCursor suggestion, SuggestionClickListener onClick) {
91        setOnClickListener(new ClickListener());
92        setOnLongClickListener(new LongClickListener());
93        mPosition = suggestion.getPosition();
94        mClickListener = onClick;
95
96        CharSequence text1 = formatText(suggestion.getSuggestionText1(), suggestion, true);
97        CharSequence text2 = suggestion.getSuggestionText2Url();
98        if (text2 != null) {
99            text2 = formatUrl(text2);
100        } else {
101            text2 = formatText(suggestion.getSuggestionText2(), suggestion, false);
102        }
103        Drawable icon1 = getSuggestionDrawableIcon1(suggestion);
104        Drawable icon2 = getSuggestionDrawableIcon2(suggestion);
105        if (DBG) {
106            Log.d(TAG, "bindAsSuggestion(), text1=" + text1 + ",text2=" + text2
107                    + ",icon1=" + icon1 + ",icon2=" + icon2);
108        }
109        // If there is no text for the second line, allow the first line to be up to two lines
110        if (TextUtils.isEmpty(text2)) {
111            mText1.setSingleLine(false);
112            mText1.setMaxLines(2);
113            mText1.setEllipsize(TextUtils.TruncateAt.START);
114        } else {
115            mText1.setSingleLine(true);
116            mText1.setMaxLines(1);
117            mText1.setEllipsize(TextUtils.TruncateAt.MIDDLE);
118        }
119        setText1(text1);
120        setText2(text2);
121        setIcon1(icon1);
122        setIcon2(icon2);
123        updateRefinable(suggestion);
124    }
125
126    protected void updateRefinable(SuggestionCursor suggestion) {
127        mRefineable =
128                suggestion.isWebSearchSuggestion()
129                && mIcon2.getDrawable() == null
130                && !TextUtils.isEmpty(suggestion.getSuggestionQuery());
131        setRefinable(suggestion, mRefineable);
132    }
133
134    protected void setRefinable(SuggestionCursor suggestion, boolean refinable) {
135        if (refinable) {
136            mIcon2.setOnClickListener(new View.OnClickListener() {
137                public void onClick(View v) {
138                    Log.d(TAG, "Clicked query refine");
139                    SuggestionsAdapter adapter =
140                            (SuggestionsAdapter) ((ListView) getParent()).getAdapter();
141                    adapter.onIcon2Clicked(mPosition);
142                }
143            });
144            mIcon2.setFocusable(true);
145            mIcon2.setOnKeyListener(mKeyListener);
146            Drawable icon2 = getContext().getResources().getDrawable(R.drawable.edit_query);
147            Drawable background =
148                    getContext().getResources().getDrawable(R.drawable.edit_query_background);
149            setIcon2(icon2, background);
150        } else {
151            mIcon2.setOnClickListener(null);
152            mIcon2.setFocusable(false);
153        }
154    }
155
156    private CharSequence formatUrl(CharSequence url) {
157        SpannableString text = new SpannableString(url);
158        ColorStateList colors = getResources().getColorStateList(R.color.url_text);
159        text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null),
160                0, url.length(),
161                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
162        return text;
163    }
164
165    public Drawable getSuggestionDrawableIcon1(Suggestion suggestion) {
166        Source source = suggestion.getSuggestionSource();
167        String iconId = suggestion.getSuggestionIcon1();
168        Drawable icon1 = iconId == null ? null : source.getIcon(iconId);
169        return icon1 == null ? source.getSourceIcon() : icon1;
170    }
171
172    public Drawable getSuggestionDrawableIcon2(Suggestion suggestion) {
173        Source source = suggestion.getSuggestionSource();
174        String iconId = suggestion.getSuggestionIcon2();
175        return iconId == null ? null : source.getIcon(iconId);
176    }
177
178    private CharSequence formatText(String str, SuggestionCursor suggestion,
179                boolean highlightSuggested) {
180        boolean isHtml = "html".equals(suggestion.getSuggestionFormat());
181        if (isHtml && looksLikeHtml(str)) {
182            return Html.fromHtml(str);
183        } else if (highlightSuggested && suggestion.isWebSearchSuggestion() &&
184                !TextUtils.isEmpty(suggestion.getUserQuery())) {
185            return mSuggestionFormatter.formatSuggestion(suggestion.getUserQuery(), str);
186        } else {
187            return str;
188        }
189    }
190
191    private boolean looksLikeHtml(String str) {
192        if (TextUtils.isEmpty(str)) return false;
193        for (int i = str.length() - 1; i >= 0; i--) {
194            char c = str.charAt(i);
195            if (c == '>' || c == '&') return true;
196        }
197        return false;
198    }
199
200    /**
201     * Sets the first text line.
202     */
203    private void setText1(CharSequence text) {
204        mText1.setText(text);
205    }
206
207    /**
208     * Sets the second text line.
209     */
210    private void setText2(CharSequence text) {
211        mText2.setText(text);
212        if (TextUtils.isEmpty(text)) {
213            mText2.setVisibility(GONE);
214        } else {
215            mText2.setVisibility(VISIBLE);
216        }
217    }
218
219    /**
220     * Sets the left-hand-side icon.
221     */
222    private void setIcon1(Drawable icon) {
223        setViewDrawable(mIcon1, icon);
224    }
225
226    /**
227     * Sets the right-hand-side icon.
228     */
229    private void setIcon2(Drawable icon) {
230        setViewDrawable(mIcon2, icon);
231    }
232
233    /**
234     * Sets the right-hand-side icon and its background.
235     */
236    private void setIcon2(Drawable icon, Drawable background) {
237        setViewDrawable(mIcon2, icon);
238        mIcon2.setBackgroundDrawable(background);
239    }
240
241    /**
242     * Sets the drawable in an image view, makes sure the view is only visible if there
243     * is a drawable.
244     */
245    private static void setViewDrawable(ImageView v, Drawable drawable) {
246        // Set the icon even if the drawable is null, since we need to clear any
247        // previous icon.
248        v.setImageDrawable(drawable);
249
250        if (drawable == null) {
251            v.setVisibility(View.GONE);
252        } else {
253            v.setVisibility(View.VISIBLE);
254
255            // This is a hack to get any animated drawables (like a 'working' spinner)
256            // to animate. You have to setVisible true on an AnimationDrawable to get
257            // it to start animating, but it must first have been false or else the
258            // call to setVisible will be ineffective. We need to clear up the story
259            // about animated drawables in the future, see http://b/1878430.
260            drawable.setVisible(false, false);
261            drawable.setVisible(true, false);
262        }
263    }
264
265    private class ClickListener implements OnClickListener {
266        public void onClick(View v) {
267            if (DBG) Log.d(TAG, "onItemClick(" + mPosition + ")");
268            if (mClickListener != null) {
269                mClickListener.onSuggestionClicked(mPosition);
270            }
271        }
272    }
273
274    private class LongClickListener implements OnLongClickListener {
275        public boolean onLongClick(View v) {
276            if (DBG) Log.d(TAG, "onItemLongClick(" + mPosition + ")");
277            if (mClickListener != null) {
278                return mClickListener.onSuggestionLongClicked(mPosition);
279            }
280            return false;
281        }
282    }
283
284    private class KeyListener implements View.OnKeyListener {
285        public boolean onKey(View v, int keyCode, KeyEvent event) {
286            boolean consumed = false;
287            if (event.getAction() == KeyEvent.ACTION_DOWN) {
288                if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && v != mIcon2) {
289                    consumed = mIcon2.requestFocus();
290                    if (DBG) Log.d(TAG, "onKey Icon2 accepted focus: " + consumed);
291                } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && v == mIcon2) {
292                    consumed = requestFocus();
293                    if (DBG) Log.d(TAG, "onKey SuggestionView accepted focus: " + consumed);
294                }
295            }
296            return consumed;
297        }
298    }
299
300}
301