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