blob: 128997c454e10da8da5eeaea5269dcf13c26331d [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;
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
241 mSearchBox.setDimensions(0, 0, 0, mHeight);
242 mSearchBox.onresize();
243
244 if (TextUtils.isEmpty(query)) {
245 // To force the SRP to render an empty (no results) page.
246 mSearchBox.setVerbatim(true);
247 } else {
248 mSearchBox.setVerbatim(false);
249 }
250 mSearchBox.setQuery(query);
251 mSearchBox.onchange();
252
253 // Don't bother waiting for suggestions for an empty query. We still
254 // set the query so that the SRP clears itself.
255 if (TextUtils.isEmpty(query)) {
256 return new SuggestionsCursor(Collections.<String>emptyList());
257 } else {
258 return new SuggestionsCursor(mListener.tryWaitForSuggestions(query));
259 }
260 }
261
262 @Override
263 public boolean supportsSuggestions() {
264 return true;
265 }
266
267 @Override
268 public void close() {
269 if (mController != null) {
270 mController.registerDropdownChangeListener(null);
271 }
272 if (mSearchBox != null) {
273 mSearchBox.removeSearchBoxListener(mListener);
274 }
275 mListener.clear();
276 mWrapped.close();
277 }
278
279 @Override
280 public boolean supportsVoiceSearch() {
281 return false;
282 }
283
284 @Override
285 public String toString() {
286 return "InstantSearchEngine {" + hashCode() + "}";
287 }
288
289 @Override
290 public boolean wantsEmptyQuery() {
291 return true;
292 }
293
294 private int rescaleHeight(int height) {
295 final float scale = getCurrentWebview().getScale();
296 if (scale != 0) {
297 return (int) (height / scale);
298 }
299
300 return height;
301 }
302
303 @Override
304 public void onNewDropdownDimensions(int height) {
305 final int rescaledHeight = rescaleHeight(height);
306
307 if (rescaledHeight != mHeight) {
308 mHeight = rescaledHeight;
309 mSearchBox.setDimensions(0, 0, 0, rescaledHeight);
310 mSearchBox.onresize();
311 }
312 }
313
314 private String getInstantBaseUrl() {
315 if (mInstantBaseUrl == null) {
316 String url = mContext.getResources().getString(R.string.instant_base);
317 if (url.indexOf("{CID}") != -1) {
318 url = url.replace("{CID}",
319 BrowserProvider.getClientId(mContext.getContentResolver()));
320 }
321 mInstantBaseUrl = url;
322 }
323
324 return mInstantBaseUrl;
325 }
326
327 // Indices of the columns in the below arrays.
328 private static final int COLUMN_INDEX_ID = 0;
329 private static final int COLUMN_INDEX_QUERY = 1;
330 private static final int COLUMN_INDEX_ICON = 2;
331 private static final int COLUMN_INDEX_TEXT_1 = 3;
332
333 private static final String[] COLUMNS_WITHOUT_DESCRIPTION = new String[] {
334 "_id",
335 SearchManager.SUGGEST_COLUMN_QUERY,
336 SearchManager.SUGGEST_COLUMN_ICON_1,
337 SearchManager.SUGGEST_COLUMN_TEXT_1,
338 };
339
340 private static class SuggestionsCursor extends AbstractCursor {
341 private final List<String> mSuggestions;
342
343 public SuggestionsCursor(List<String> suggestions) {
344 mSuggestions = suggestions;
345 }
346
347 @Override
348 public int getCount() {
349 return mSuggestions.size();
350 }
351
352 @Override
353 public String[] getColumnNames() {
354 return COLUMNS_WITHOUT_DESCRIPTION;
355 }
356
357 private String format(String suggestion) {
358 if (TextUtils.isEmpty(suggestion)) {
359 return "";
360 }
361 return suggestion;
362 }
363
364 @Override
365 public String getString(int column) {
366 if (mPos >= 0 && mPos < mSuggestions.size()) {
367 if ((column == COLUMN_INDEX_QUERY) || (column == COLUMN_INDEX_TEXT_1)) {
368 return format(mSuggestions.get(mPos));
369 } else if (column == COLUMN_INDEX_ICON) {
370 return String.valueOf(R.drawable.magnifying_glass);
371 }
372 }
373 return null;
374 }
375
376 @Override
377 public double getDouble(int column) {
378 throw new UnsupportedOperationException();
379 }
380
381 @Override
382 public float getFloat(int column) {
383 throw new UnsupportedOperationException();
384 }
385
386 @Override
387 public int getInt(int column) {
388 if (column == COLUMN_INDEX_ID) {
389 return mPos;
390 }
391 throw new UnsupportedOperationException();
392 }
393
394 @Override
395 public long getLong(int column) {
396 throw new UnsupportedOperationException();
397 }
398
399 @Override
400 public short getShort(int column) {
401 throw new UnsupportedOperationException();
402 }
403
404 @Override
405 public boolean isNull(int column) {
406 throw new UnsupportedOperationException();
407 }
408 }
409}