blob: 1d9bdd6f392d8e2155c40e7433c6f039b4fe5ab2 [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.
84 if (mSearchBox == null & !isInstantPage()) {
85 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;
188 mSearchBox.addSearchBoxListener(mListener);
189 }
190 }
191
192 private boolean isInstantPage() {
193 String currentUrl = getCurrentWebview().getUrl();
194
195 if (currentUrl != null) {
196 Uri uri = Uri.parse(currentUrl);
197 final String host = uri.getHost();
198 final String path = uri.getPath();
199
200 // Is there a utility class that does this ?
201 if (path != null && host != null) {
202 return host.startsWith("www.google.") &&
203 (path.startsWith("/search") || path.startsWith("/webhp"));
204 }
205 return false;
206 }
207
208 return false;
209 }
210
211 private void loadInstantPage() {
212 mController.getActivity().runOnUiThread(new Runnable() {
213 @Override
214 public void run() {
215 getCurrentWebview().loadUrl(getInstantBaseUrl());
216 }
217 });
218 }
219
220 /**
221 * Queries for a given search term and returns a cursor containing
222 * suggestions ordered by best match.
223 */
224 @Override
225 public Cursor getSuggestions(Context context, String query) {
226 if (DBG) Log.d(TAG, "getSuggestions(" + query + ")");
227 if (query == null) {
228 return null;
229 }
230
231 if (!isInstantPage()) {
232 loadInstantPage();
233 }
234
235 switchSearchboxIfNeeded();
236
237 mController.registerDropdownChangeListener(this);
238
239 mSearchBox.setDimensions(0, 0, 0, mHeight);
240 mSearchBox.onresize();
241
242 if (TextUtils.isEmpty(query)) {
243 // To force the SRP to render an empty (no results) page.
244 mSearchBox.setVerbatim(true);
245 } else {
246 mSearchBox.setVerbatim(false);
247 }
248 mSearchBox.setQuery(query);
249 mSearchBox.onchange();
250
251 // Don't bother waiting for suggestions for an empty query. We still
252 // set the query so that the SRP clears itself.
253 if (TextUtils.isEmpty(query)) {
254 return new SuggestionsCursor(Collections.<String>emptyList());
255 } else {
256 return new SuggestionsCursor(mListener.tryWaitForSuggestions(query));
257 }
258 }
259
260 @Override
261 public boolean supportsSuggestions() {
262 return true;
263 }
264
265 @Override
266 public void close() {
267 if (mController != null) {
268 mController.registerDropdownChangeListener(null);
269 }
270 if (mSearchBox != null) {
271 mSearchBox.removeSearchBoxListener(mListener);
272 }
273 mListener.clear();
274 mWrapped.close();
275 }
276
277 @Override
278 public boolean supportsVoiceSearch() {
279 return false;
280 }
281
282 @Override
283 public String toString() {
284 return "InstantSearchEngine {" + hashCode() + "}";
285 }
286
287 @Override
288 public boolean wantsEmptyQuery() {
289 return true;
290 }
291
292 private int rescaleHeight(int height) {
293 final float scale = getCurrentWebview().getScale();
294 if (scale != 0) {
295 return (int) (height / scale);
296 }
297
298 return height;
299 }
300
301 @Override
302 public void onNewDropdownDimensions(int height) {
303 final int rescaledHeight = rescaleHeight(height);
304
305 if (rescaledHeight != mHeight) {
306 mHeight = rescaledHeight;
307 mSearchBox.setDimensions(0, 0, 0, rescaledHeight);
308 mSearchBox.onresize();
309 }
310 }
311
312 private String getInstantBaseUrl() {
313 if (mInstantBaseUrl == null) {
314 String url = mContext.getResources().getString(R.string.instant_base);
315 if (url.indexOf("{CID}") != -1) {
316 url = url.replace("{CID}",
317 BrowserProvider.getClientId(mContext.getContentResolver()));
318 }
319 mInstantBaseUrl = url;
320 }
321
322 return mInstantBaseUrl;
323 }
324
325 // Indices of the columns in the below arrays.
326 private static final int COLUMN_INDEX_ID = 0;
327 private static final int COLUMN_INDEX_QUERY = 1;
328 private static final int COLUMN_INDEX_ICON = 2;
329 private static final int COLUMN_INDEX_TEXT_1 = 3;
330
331 private static final String[] COLUMNS_WITHOUT_DESCRIPTION = new String[] {
332 "_id",
333 SearchManager.SUGGEST_COLUMN_QUERY,
334 SearchManager.SUGGEST_COLUMN_ICON_1,
335 SearchManager.SUGGEST_COLUMN_TEXT_1,
336 };
337
338 private static class SuggestionsCursor extends AbstractCursor {
339 private final List<String> mSuggestions;
340
341 public SuggestionsCursor(List<String> suggestions) {
342 mSuggestions = suggestions;
343 }
344
345 @Override
346 public int getCount() {
347 return mSuggestions.size();
348 }
349
350 @Override
351 public String[] getColumnNames() {
352 return COLUMNS_WITHOUT_DESCRIPTION;
353 }
354
355 private String format(String suggestion) {
356 if (TextUtils.isEmpty(suggestion)) {
357 return "";
358 }
359 return suggestion;
360 }
361
362 @Override
363 public String getString(int column) {
364 if (mPos >= 0 && mPos < mSuggestions.size()) {
365 if ((column == COLUMN_INDEX_QUERY) || (column == COLUMN_INDEX_TEXT_1)) {
366 return format(mSuggestions.get(mPos));
367 } else if (column == COLUMN_INDEX_ICON) {
368 return String.valueOf(R.drawable.magnifying_glass);
369 }
370 }
371 return null;
372 }
373
374 @Override
375 public double getDouble(int column) {
376 throw new UnsupportedOperationException();
377 }
378
379 @Override
380 public float getFloat(int column) {
381 throw new UnsupportedOperationException();
382 }
383
384 @Override
385 public int getInt(int column) {
386 if (column == COLUMN_INDEX_ID) {
387 return mPos;
388 }
389 throw new UnsupportedOperationException();
390 }
391
392 @Override
393 public long getLong(int column) {
394 throw new UnsupportedOperationException();
395 }
396
397 @Override
398 public short getShort(int column) {
399 throw new UnsupportedOperationException();
400 }
401
402 @Override
403 public boolean isNull(int column) {
404 throw new UnsupportedOperationException();
405 }
406 }
407}