blob: b4ccfa5f157c7b57b4c6c1d1a8b7fed60d5f9e25 [file] [log] [blame]
Narayan Kamath5119edd2011-02-23 15:49:17 +00001/*
2 * Copyright (C) 2011 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 */
16package com.android.browser;
17
18import com.google.android.collect.Maps;
19import com.google.common.collect.Lists;
20
21import com.android.browser.Controller;
22import com.android.browser.R;
23import com.android.browser.UI.DropdownChangeListener;
24import com.android.browser.search.DefaultSearchEngine;
25import com.android.browser.search.SearchEngine;
26
27import android.app.SearchManager;
28import android.content.Context;
29import android.database.AbstractCursor;
30import android.database.Cursor;
31import android.net.Uri;
32import android.os.Bundle;
33import android.text.TextUtils;
34import android.util.Log;
35import android.util.LruCache;
36import android.webkit.SearchBox;
37import android.webkit.WebView;
38
39import java.util.Collections;
40import java.util.List;
41
42public class InstantSearchEngine implements SearchEngine, DropdownChangeListener {
43 private static final String TAG = "Browser.InstantSearchEngine";
44 private static final boolean DBG = false;
45
46 private Controller mController;
47 private SearchBox mSearchBox;
48 private final BrowserSearchboxListener mListener = new BrowserSearchboxListener();
49 private int mHeight;
50
51 private String mInstantBaseUrl;
52 private final Context mContext;
53 // Used for startSearch( ) calls if for some reason instant
54 // is off, or no searchbox is present.
55 private final SearchEngine mWrapped;
56
57 public InstantSearchEngine(Context context, SearchEngine wrapped) {
58 mContext = context;
59 mWrapped = wrapped;
60 }
61
62 public void setController(Controller controller) {
63 mController = controller;
64 }
65
66 @Override
67 public String getName() {
68 return SearchEngine.GOOGLE;
69 }
70
71 @Override
72 public CharSequence getLabel() {
73 return mContext.getResources().getString(R.string.instant_search_label);
74 }
75
76 @Override
77 public void startSearch(Context context, String query, Bundle appData, String extraData) {
78 if (DBG) Log.d(TAG, "startSearch(" + query + ")");
79
80 switchSearchboxIfNeeded();
81
82 // If for some reason we are in a bad state, ensure that the
83 // user gets default search results at the very least.
Narayan Kamath41feb052011-03-04 18:57:30 +000084 if (mSearchBox == null || !isInstantPage()) {
Narayan Kamath5119edd2011-02-23 15:49:17 +000085 mWrapped.startSearch(context, query, appData, extraData);
86 return;
87 }
88
89 mSearchBox.setQuery(query);
90 mSearchBox.setVerbatim(true);
91 mSearchBox.onsubmit();
92 }
93
94 private final class BrowserSearchboxListener implements SearchBox.SearchBoxListener {
95 /*
96 * The maximum number of out of order suggestions we accept
97 * before giving up the wait.
98 */
99 private static final int MAX_OUT_OF_ORDER = 5;
100
101 /*
102 * We wait for suggestions in increments of 600ms. This is primarily to
103 * guard against suggestions arriving out of order.
104 */
105 private static final int WAIT_INCREMENT_MS = 600;
106
107 /*
108 * A cache of suggestions received, keyed by the queries they were
109 * received for.
110 */
111 private final LruCache<String, List<String>> mSuggestions =
112 new LruCache<String, List<String>>(20);
113
114 /*
115 * The last set of suggestions received. We use this reduce UI flicker
116 * in case there is a delay in recieving suggestions.
117 */
118 private List<String> mLatestSuggestion = Collections.emptyList();
119
120 @Override
121 public synchronized void onSuggestionsReceived(String query, List<String> suggestions) {
122 if (DBG) Log.d(TAG, "onSuggestionsReceived(" + query + ")");
123
124 if (!TextUtils.isEmpty(query)) {
125 mSuggestions.put(query, suggestions);
126 mLatestSuggestion = suggestions;
127 }
128
129 notifyAll();
130 }
131
132 public synchronized List<String> tryWaitForSuggestions(String query) {
133 if (DBG) Log.d(TAG, "tryWait(" + query + ")");
134
135 int numWaitReturns = 0;
136
137 // This slightly unusual waiting construct is used to safeguard
138 // to some extent against suggestions arriving out of order. We
139 // wait for upto 5 notifyAll( ) calls to check if we received
140 // suggestions for a given query.
141 while (mSuggestions.get(query) == null) {
142 try {
143 wait(WAIT_INCREMENT_MS);
144 ++numWaitReturns;
145 if (numWaitReturns > MAX_OUT_OF_ORDER) {
146 // We've waited too long for suggestions to be returned.
147 // return the last available suggestion.
148 break;
149 }
150 } catch (InterruptedException e) {
151 return Collections.emptyList();
152 }
153 }
154
155 List<String> suggestions = mSuggestions.get(query);
156 if (suggestions == null) {
157 return mLatestSuggestion;
158 }
159
160 return suggestions;
161 }
162
163 public synchronized void clear() {
164 mSuggestions.evictAll();
165 }
166 }
167
168 private WebView getCurrentWebview() {
169 if (mController != null) {
170 return mController.getTabControl().getCurrentTopWebView();
171 }
172
173 return null;
174 }
175
176 /**
177 * Attaches the searchbox to the right browser page, i.e, the currently
178 * visible tab.
179 */
180 private void switchSearchboxIfNeeded() {
181 final SearchBox searchBox = getCurrentWebview().getSearchBox();
182 if (searchBox != mSearchBox) {
183 if (mSearchBox != null) {
184 mSearchBox.removeSearchBoxListener(mListener);
185 mListener.clear();
186 }
187 mSearchBox = searchBox;
Michael Kolb00a22752011-03-03 17:13:30 -0800188 if (mSearchBox != null) {
189 mSearchBox.addSearchBoxListener(mListener);
190 }
Narayan Kamath5119edd2011-02-23 15:49:17 +0000191 }
192 }
193
194 private boolean isInstantPage() {
195 String currentUrl = getCurrentWebview().getUrl();
196
197 if (currentUrl != null) {
198 Uri uri = Uri.parse(currentUrl);
199 final String host = uri.getHost();
200 final String path = uri.getPath();
201
202 // Is there a utility class that does this ?
203 if (path != null && host != null) {
204 return host.startsWith("www.google.") &&
205 (path.startsWith("/search") || path.startsWith("/webhp"));
206 }
207 return false;
208 }
209
210 return false;
211 }
212
213 private void loadInstantPage() {
214 mController.getActivity().runOnUiThread(new Runnable() {
215 @Override
216 public void run() {
217 getCurrentWebview().loadUrl(getInstantBaseUrl());
218 }
219 });
220 }
221
222 /**
223 * Queries for a given search term and returns a cursor containing
224 * suggestions ordered by best match.
225 */
226 @Override
227 public Cursor getSuggestions(Context context, String query) {
228 if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
229 if (query == null) {
230 return null;
231 }
232
233 if (!isInstantPage()) {
234 loadInstantPage();
235 }
236
237 switchSearchboxIfNeeded();
238
239 mController.registerDropdownChangeListener(this);
240
Narayan Kamath41feb052011-03-04 18:57:30 +0000241 if (mSearchBox == null) {
242 return mWrapped.getSuggestions(context, query);
243 }
244
Narayan Kamath5119edd2011-02-23 15:49:17 +0000245 mSearchBox.setDimensions(0, 0, 0, mHeight);
246 mSearchBox.onresize();
247
248 if (TextUtils.isEmpty(query)) {
249 // To force the SRP to render an empty (no results) page.
250 mSearchBox.setVerbatim(true);
251 } else {
252 mSearchBox.setVerbatim(false);
253 }
254 mSearchBox.setQuery(query);
255 mSearchBox.onchange();
256
257 // Don't bother waiting for suggestions for an empty query. We still
258 // set the query so that the SRP clears itself.
259 if (TextUtils.isEmpty(query)) {
260 return new SuggestionsCursor(Collections.<String>emptyList());
261 } else {
262 return new SuggestionsCursor(mListener.tryWaitForSuggestions(query));
263 }
264 }
265
266 @Override
267 public boolean supportsSuggestions() {
268 return true;
269 }
270
271 @Override
272 public void close() {
273 if (mController != null) {
274 mController.registerDropdownChangeListener(null);
275 }
276 if (mSearchBox != null) {
277 mSearchBox.removeSearchBoxListener(mListener);
278 }
279 mListener.clear();
280 mWrapped.close();
281 }
282
283 @Override
284 public boolean supportsVoiceSearch() {
285 return false;
286 }
287
288 @Override
289 public String toString() {
290 return "InstantSearchEngine {" + hashCode() + "}";
291 }
292
293 @Override
294 public boolean wantsEmptyQuery() {
295 return true;
296 }
297
298 private int rescaleHeight(int height) {
299 final float scale = getCurrentWebview().getScale();
300 if (scale != 0) {
301 return (int) (height / scale);
302 }
303
304 return height;
305 }
306
307 @Override
308 public void onNewDropdownDimensions(int height) {
309 final int rescaledHeight = rescaleHeight(height);
310
311 if (rescaledHeight != mHeight) {
312 mHeight = rescaledHeight;
313 mSearchBox.setDimensions(0, 0, 0, rescaledHeight);
314 mSearchBox.onresize();
315 }
316 }
317
318 private String getInstantBaseUrl() {
319 if (mInstantBaseUrl == null) {
320 String url = mContext.getResources().getString(R.string.instant_base);
321 if (url.indexOf("{CID}") != -1) {
322 url = url.replace("{CID}",
323 BrowserProvider.getClientId(mContext.getContentResolver()));
324 }
325 mInstantBaseUrl = url;
326 }
327
328 return mInstantBaseUrl;
329 }
330
331 // Indices of the columns in the below arrays.
332 private static final int COLUMN_INDEX_ID = 0;
333 private static final int COLUMN_INDEX_QUERY = 1;
334 private static final int COLUMN_INDEX_ICON = 2;
335 private static final int COLUMN_INDEX_TEXT_1 = 3;
336
337 private static final String[] COLUMNS_WITHOUT_DESCRIPTION = new String[] {
338 "_id",
339 SearchManager.SUGGEST_COLUMN_QUERY,
340 SearchManager.SUGGEST_COLUMN_ICON_1,
341 SearchManager.SUGGEST_COLUMN_TEXT_1,
342 };
343
344 private static class SuggestionsCursor extends AbstractCursor {
345 private final List<String> mSuggestions;
346
347 public SuggestionsCursor(List<String> suggestions) {
348 mSuggestions = suggestions;
349 }
350
351 @Override
352 public int getCount() {
353 return mSuggestions.size();
354 }
355
356 @Override
357 public String[] getColumnNames() {
358 return COLUMNS_WITHOUT_DESCRIPTION;
359 }
360
361 private String format(String suggestion) {
362 if (TextUtils.isEmpty(suggestion)) {
363 return "";
364 }
365 return suggestion;
366 }
367
368 @Override
369 public String getString(int column) {
370 if (mPos >= 0 && mPos < mSuggestions.size()) {
371 if ((column == COLUMN_INDEX_QUERY) || (column == COLUMN_INDEX_TEXT_1)) {
372 return format(mSuggestions.get(mPos));
373 } else if (column == COLUMN_INDEX_ICON) {
374 return String.valueOf(R.drawable.magnifying_glass);
375 }
376 }
377 return null;
378 }
379
380 @Override
381 public double getDouble(int column) {
382 throw new UnsupportedOperationException();
383 }
384
385 @Override
386 public float getFloat(int column) {
387 throw new UnsupportedOperationException();
388 }
389
390 @Override
391 public int getInt(int column) {
392 if (column == COLUMN_INDEX_ID) {
393 return mPos;
394 }
395 throw new UnsupportedOperationException();
396 }
397
398 @Override
399 public long getLong(int column) {
400 throw new UnsupportedOperationException();
401 }
402
403 @Override
404 public short getShort(int column) {
405 throw new UnsupportedOperationException();
406 }
407
408 @Override
409 public boolean isNull(int column) {
410 throw new UnsupportedOperationException();
411 }
412 }
413}