blob: 7cfd78e457f2187fda5280e47a97e648bdaa619b [file] [log] [blame]
Michael Kolb21ce4d22010-09-15 14:55:05 -07001/*
2 * Copyright (C) 2010 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.browser;
18
19import com.android.browser.search.SearchEngine;
20
21import android.app.SearchManager;
22import android.content.Context;
23import android.database.Cursor;
24import android.net.Uri;
25import android.provider.BrowserContract;
26import android.text.TextUtils;
27import android.view.LayoutInflater;
28import android.view.View;
29import android.view.View.OnClickListener;
30import android.view.ViewGroup;
31import android.widget.BaseAdapter;
32import android.widget.Filter;
33import android.widget.Filterable;
34import android.widget.ImageView;
35import android.widget.LinearLayout.LayoutParams;
36import android.widget.TextView;
37
38import java.util.ArrayList;
39import java.util.List;
40import java.util.regex.Matcher;
41import java.util.regex.Pattern;
42
43/**
44 * adapter to wrap multiple cursors for url/search completions
45 */
46public class SuggestionsAdapter extends BaseAdapter implements Filterable, OnClickListener {
47
48 static final int TYPE_SEARCH = 0;
49 static final int TYPE_SUGGEST = 1;
50 static final int TYPE_BOOKMARK = 2;
51 static final int TYPE_SUGGEST_URL = 3;
52 static final int TYPE_HISTORY = 4;
53
54 private static final String[] COMBINED_PROJECTION =
55 {BrowserContract.Combined._ID, BrowserContract.Combined.TITLE,
56 BrowserContract.Combined.URL, BrowserContract.Combined.IS_BOOKMARK};
57
58 private static final String[] SEARCHES_PROJECTION = {BrowserContract.Searches.SEARCH};
59
60 private static final String COMBINED_SELECTION =
61 "(url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ? OR title LIKE ?)";
62
63 // Regular expression which matches http://, followed by some stuff, followed by
64 // optionally a trailing slash, all matched as separate groups.
65 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
66
67 Context mContext;
68 Filter mFilter;
69 SuggestionResults mResults;
70 List<CursorSource> mSources;
71 boolean mLandscapeMode;
72 CompletionListener mListener;
73 int mLinesPortrait;
74 int mLinesLandscape;
75
76 interface CompletionListener {
77
78 public void onSearch(String txt);
79
80 public void onSelect(String txt);
81
82 }
83
84 public SuggestionsAdapter(Context ctx, CompletionListener listener) {
85 mContext = ctx;
86 mListener = listener;
87 mLinesPortrait = mContext.getResources().
88 getInteger(R.integer.max_suggest_lines_portrait);
89 mLinesLandscape = mContext.getResources().
90 getInteger(R.integer.max_suggest_lines_landscape);
91 mFilter = new SuggestFilter();
92 addSource(new SuggestCursor());
93 addSource(new SearchesCursor());
94 addSource(new CombinedCursor());
95 }
96
97 public void setLandscapeMode(boolean mode) {
98 mLandscapeMode = mode;
99 }
100
101 public int getLeftCount() {
102 return mResults.getLeftCount();
103 }
104
105 public int getRightCount() {
106 return mResults.getRightCount();
107 }
108
109 public void addSource(CursorSource c) {
110 if (mSources == null) {
111 mSources = new ArrayList<CursorSource>(5);
112 }
113 mSources.add(c);
114 }
115
116 @Override
117 public void onClick(View v) {
118 if (R.id.icon2 == v.getId()) {
119 // replace input field text with suggestion text
120 SuggestItem item = (SuggestItem) ((View) v.getParent()).getTag();
121 mListener.onSearch(item.title);
122 } else {
123 SuggestItem item = (SuggestItem) v.getTag();
124 mListener.onSelect((TextUtils.isEmpty(item.url)? item.title : item.url));
125 }
126 }
127
128 @Override
129 public Filter getFilter() {
130 return mFilter;
131 }
132
133 @Override
134 public int getCount() {
135 return (mResults == null) ? 0 : mResults.getLineCount();
136 }
137
138 @Override
139 public SuggestItem getItem(int position) {
140 if (mResults == null) {
141 return null;
142 }
143 if (mLandscapeMode) {
144 if (position >= mResults.getLineCount()) {
145 // right column
146 position = position - mResults.getLineCount();
147 // index in column
148 if (position >= mResults.getRightCount()) {
149 return null;
150 }
151 return mResults.items.get(position + mResults.getLeftCount());
152 } else {
153 // left column
154 if (position >= mResults.getLeftCount()) {
155 return null;
156 }
157 return mResults.items.get(position);
158 }
159 } else {
160 return mResults.items.get(position);
161 }
162 }
163
164 @Override
165 public long getItemId(int position) {
166 return 0;
167 }
168
169 @Override
170 public View getView(int position, View convertView, ViewGroup parent) {
171 final LayoutInflater inflater = LayoutInflater.from(mContext);
172 if (mLandscapeMode) {
173 View view = inflater.inflate(R.layout.suggestion_two_column, parent, false);
174 SuggestItem item = getItem(position);
175 View iv = view.findViewById(R.id.suggest1);
176 LayoutParams lp = new LayoutParams(iv.getLayoutParams());
177 lp.weight = 0.5f;
178 iv.setLayoutParams(lp);
179 if (item != null) {
180 bindView(iv, item);
181 } else {
182 iv.setVisibility((mResults.getLeftCount() == 0) ? View.GONE :
183 View.INVISIBLE);
184 }
185 item = getItem(position + mResults.getLineCount());
186 iv = view.findViewById(R.id.suggest2);
187 lp = new LayoutParams(iv.getLayoutParams());
188 lp.weight = 0.5f;
189 iv.setLayoutParams(lp);
190 if (item != null) {
191 bindView(iv, item);
192 } else {
193 iv.setVisibility((mResults.getRightCount() == 0) ? View.GONE :
194 View.INVISIBLE);
195 }
196 return view;
197 } else {
198 View view = inflater.inflate(R.layout.suggestion_item, parent, false);
199 bindView(view, getItem(position));
200 return view;
201 }
202 }
203
204 private void bindView(View view, SuggestItem item) {
205 // store item for click handling
206 view.setTag(item);
207 TextView tv1 = (TextView) view.findViewById(android.R.id.text1);
208 TextView tv2 = (TextView) view.findViewById(android.R.id.text2);
209 ImageView ic1 = (ImageView) view.findViewById(R.id.icon1);
210 View spacer = view.findViewById(R.id.spacer);
211 View ic2 = view.findViewById(R.id.icon2);
212 tv1.setText(item.title);
213 tv2.setText(item.url);
214 int id = -1;
215 switch (item.type) {
216 case TYPE_SUGGEST:
217 case TYPE_SEARCH:
218 id = R.drawable.ic_search_category_suggest;
219 break;
220 case TYPE_BOOKMARK:
221 id = R.drawable.ic_search_category_bookmark;
222 break;
223 case TYPE_HISTORY:
224 id = R.drawable.ic_search_category_history;
225 break;
226 case TYPE_SUGGEST_URL:
227 id = R.drawable.ic_search_category_browser;
228 break;
229 default:
230 id = -1;
231 }
232 if (id != -1) {
233 ic1.setImageDrawable(mContext.getResources().getDrawable(id));
234 }
235 ic2.setVisibility(((TYPE_SUGGEST == item.type) || (TYPE_SEARCH == item.type))
236 ? View.VISIBLE : View.GONE);
237 spacer.setVisibility(((TYPE_SUGGEST == item.type) || (TYPE_SEARCH == item.type))
238 ? View.GONE : View.INVISIBLE);
239 view.setOnClickListener(this);
240 ic2.setOnClickListener(this);
241 }
242
243 class SuggestFilter extends Filter {
244
245 int count;
246 SuggestionResults results;
247
248 @Override
249 public CharSequence convertResultToString(Object item) {
250 if (item == null) {
251 return "";
252 }
253 SuggestItem sitem = (SuggestItem) item;
254 if (sitem.title != null) {
255 return sitem.title;
256 } else {
257 return sitem.url;
258 }
259 }
260
261 @Override
262 protected FilterResults performFiltering(CharSequence constraint) {
263 FilterResults res = new FilterResults();
264 if (TextUtils.isEmpty(constraint)) {
265 res.count = 0;
266 res.values = null;
267 return res;
268 }
269 results = new SuggestionResults();
270 count = 0;
271 if (constraint != null) {
272 for (CursorSource sc : mSources) {
273 sc.runQuery(constraint);
274 }
275 mixResults();
276 }
277 res.count = count;
278 res.values = results;
279 return res;
280 }
281
282 void mixResults() {
283 for (int i = 0; i < mSources.size(); i++) {
284 CursorSource s = mSources.get(i);
285 int n = Math.min(s.getCount(), (mLandscapeMode ? mLinesLandscape
286 : mLinesPortrait));
287 boolean more = true;
288 for (int j = 0; j < n; j++) {
289 results.addResult(s.getItem());
290 more = s.moveToNext();
291 }
292 if (s instanceof SuggestCursor) {
293 int k = n;
294 while (more && (k < mLinesPortrait)) {
295 SuggestItem item = s.getItem();
296 if (item.type == TYPE_SUGGEST_URL) {
297 results.addResult(item);
298 break;
299 }
300 more = s.moveToNext();
301 k++;
302
303 }
304 }
305 }
306
307 }
308
309 @Override
310 protected void publishResults(CharSequence constraint, FilterResults fresults) {
311 mResults = (SuggestionResults) fresults.values;
312 notifyDataSetChanged();
313 }
314
315 }
316
317 /**
318 * sorted list of results of a suggestion query
319 *
320 */
321 class SuggestionResults {
322
323 ArrayList<SuggestItem> items;
324 // count per type
325 int[] counts;
326
327 SuggestionResults() {
328 items = new ArrayList<SuggestItem>(24);
329 // n of types:
330 counts = new int[5];
331 }
332
333 int getTypeCount(int type) {
334 return counts[type];
335 }
336
337 void addResult(SuggestItem item) {
338 int ix = 0;
339 while ((ix < items.size()) && (item.type >= items.get(ix).type))
340 ix++;
341 items.add(ix, item);
342 counts[item.type]++;
343 }
344
345 int getLineCount() {
346 if (mLandscapeMode) {
347 return Math.max(getLeftCount(), getRightCount());
348 } else {
349 return getLeftCount() + getRightCount();
350 }
351 }
352
353 int getLeftCount() {
354 return counts[TYPE_SEARCH] + counts[TYPE_SUGGEST];
355 }
356
357 int getRightCount() {
358 return counts[TYPE_BOOKMARK] + counts[TYPE_HISTORY] + counts[TYPE_SUGGEST_URL];
359 }
360
361 public String toString() {
362 if (items == null) return null;
363 if (items.size() == 0) return "[]";
364 StringBuilder sb = new StringBuilder();
365 for (int i = 0; i < items.size(); i++) {
366 SuggestItem item = items.get(i);
367 sb.append(item.type + ": " + item.title);
368 if (i < items.size() - 1) {
369 sb.append(", ");
370 }
371 }
372 return sb.toString();
373 }
374 }
375
376 /**
377 * data object to hold suggestion values
378 */
379 class SuggestItem {
380 String title;
381 String url;
382 int type;
383
384 public SuggestItem(String text, String u, int t) {
385 title = text;
386 url = u;
387 type = t;
388 }
389 }
390
391 abstract class CursorSource {
392
393 Cursor mCursor;
394
395 boolean moveToNext() {
396 return mCursor.moveToNext();
397 }
398
399 public abstract void runQuery(CharSequence constraint);
400
401 public abstract SuggestItem getItem();
402
403 public int getCount() {
404 return (mCursor != null) ? mCursor.getCount() : 0;
405 }
406
407 public void close() {
408 if (mCursor != null) {
409 mCursor.close();
410 }
411 }
412 }
413
414 /**
415 * combined bookmark & history source
416 */
417 class CombinedCursor extends CursorSource {
418
419 @Override
420 public SuggestItem getItem() {
421 if ((mCursor != null) && (!mCursor.isAfterLast())) {
422 String title = mCursor.getString(1);
423 String url = mCursor.getString(2);
424 boolean isBookmark = (mCursor.getInt(3) == 1);
425 return new SuggestItem(getTitle(title, url), getUrl(title, url),
426 isBookmark ? TYPE_BOOKMARK : TYPE_HISTORY);
427 }
428 return null;
429 }
430
431 @Override
432 public void runQuery(CharSequence constraint) {
433 // constraint != null
434 if (mCursor != null) {
435 mCursor.close();
436 }
437 String like = constraint + "%";
438 String[] args = null;
439 String selection = null;
440 if (like.startsWith("http") || like.startsWith("file")) {
441 args = new String[1];
442 args[0] = like;
443 selection = "url LIKE ?";
444 } else {
445 args = new String[5];
446 args[0] = "http://" + like;
447 args[1] = "http://www." + like;
448 args[2] = "https://" + like;
449 args[3] = "https://www." + like;
450 // To match against titles.
451 args[4] = like;
452 selection = COMBINED_SELECTION;
453 }
454 Uri.Builder ub = BrowserContract.Combined.CONTENT_URI.buildUpon();
455 ub.appendQueryParameter(BrowserContract.PARAM_LIMIT,
456 Integer.toString(mLinesPortrait));
457 mCursor =
458 mContext.getContentResolver().query(ub.build(), COMBINED_PROJECTION,
459 selection,
460 (constraint != null) ? args : null,
461 BrowserContract.Combined.VISITS + " DESC, " +
462 BrowserContract.Combined.DATE_LAST_VISITED + " DESC");
463 if (mCursor != null) {
464 mCursor.moveToFirst();
465 }
466 }
467
468 /**
469 * Provides the title (text line 1) for a browser suggestion, which should be the
470 * webpage title. If the webpage title is empty, returns the stripped url instead.
471 *
472 * @return the title string to use
473 */
474 private String getTitle(String title, String url) {
475 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
476 title = stripUrl(url);
477 }
478 return title;
479 }
480
481 /**
482 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
483 * webpage url. If the webpage title is empty, then the url should go in the title
484 * instead, and the subtitle should be empty, so this would return null.
485 *
486 * @return the subtitle string to use, or null if none
487 */
488 private String getUrl(String title, String url) {
489 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
490 return null;
491 } else {
492 return stripUrl(url);
493 }
494 }
495
496 /**
497 * Strips the provided url of preceding "http://" and any trailing "/". Does not
498 * strip "https://". If the provided string cannot be stripped, the original string
499 * is returned.
500 *
501 * TODO: Put this in TextUtils to be used by other packages doing something similar.
502 *
503 * @param url a url to strip, like "http://www.google.com/"
504 * @return a stripped url like "www.google.com", or the original string if it could
505 * not be stripped
506 */
507 private String stripUrl(String url) {
508 if (url == null) return null;
509 Matcher m = STRIP_URL_PATTERN.matcher(url);
510 if (m.matches() && m.groupCount() == 3) {
511 return m.group(2);
512 } else {
513 return url;
514 }
515 }
516
517 }
518
519 class SearchesCursor extends CursorSource {
520
521 @Override
522 public SuggestItem getItem() {
523 if ((mCursor != null) && (!mCursor.isAfterLast())) {
524 return new SuggestItem(mCursor.getString(0), null, TYPE_SEARCH);
525 }
526 return null;
527 }
528
529 @Override
530 public void runQuery(CharSequence constraint) {
531 // constraint != null
532 if (mCursor != null) {
533 mCursor.close();
534 }
535 String like = constraint + "%";
536 String[] args = new String[] {constraint.toString()};
537 String selection = BrowserContract.Searches.SEARCH + " LIKE ?";
538 Uri.Builder ub = BrowserContract.Searches.CONTENT_URI.buildUpon();
539 ub.appendQueryParameter(BrowserContract.PARAM_LIMIT,
540 Integer.toString(mLinesPortrait));
541 mCursor =
542 mContext.getContentResolver().query(ub.build(), SEARCHES_PROJECTION,
543 selection,
544 args, BrowserContract.Searches.DATE + " DESC");
545 if (mCursor != null) {
546 mCursor.moveToFirst();
547 }
548 }
549
550 }
551
552 class SuggestCursor extends CursorSource {
553
554 @Override
555 public SuggestItem getItem() {
556 if (mCursor != null) {
557 String title = mCursor.getString(
558 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
559 String text2 = mCursor.getString(
560 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2));
561 String url = mCursor.getString(
562 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2_URL));
563 String uri = mCursor.getString(
564 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA));
565 int type = (TextUtils.isEmpty(url)) ? TYPE_SUGGEST : TYPE_SUGGEST_URL;
566 return new SuggestItem(title, url, type);
567 }
568 return null;
569 }
570
571 @Override
572 public void runQuery(CharSequence constraint) {
573 if (mCursor != null) {
574 mCursor.close();
575 }
576 if (!TextUtils.isEmpty(constraint)) {
577 SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
578 if (searchEngine != null && searchEngine.supportsSuggestions()) {
579 mCursor = searchEngine.getSuggestions(mContext, constraint.toString());
580 if (mCursor != null) {
581 mCursor.moveToFirst();
582 }
583 }
584 } else {
585 mCursor = null;
586 }
587 }
588
589 }
590
591}