blob: 30e46fe592b99a6de376704c704c1890bc734451 [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);
Michael Kolb7b20ddd2010-10-14 15:03:28 -0700212 View div = view.findViewById(R.id.divider);
Michael Kolb21ce4d22010-09-15 14:55:05 -0700213 tv1.setText(item.title);
214 tv2.setText(item.url);
215 int id = -1;
216 switch (item.type) {
217 case TYPE_SUGGEST:
218 case TYPE_SEARCH:
219 id = R.drawable.ic_search_category_suggest;
220 break;
221 case TYPE_BOOKMARK:
222 id = R.drawable.ic_search_category_bookmark;
223 break;
224 case TYPE_HISTORY:
225 id = R.drawable.ic_search_category_history;
226 break;
227 case TYPE_SUGGEST_URL:
228 id = R.drawable.ic_search_category_browser;
229 break;
230 default:
231 id = -1;
232 }
233 if (id != -1) {
234 ic1.setImageDrawable(mContext.getResources().getDrawable(id));
235 }
236 ic2.setVisibility(((TYPE_SUGGEST == item.type) || (TYPE_SEARCH == item.type))
237 ? View.VISIBLE : View.GONE);
Michael Kolb7b20ddd2010-10-14 15:03:28 -0700238 div.setVisibility(ic2.getVisibility());
Michael Kolb21ce4d22010-09-15 14:55:05 -0700239 spacer.setVisibility(((TYPE_SUGGEST == item.type) || (TYPE_SEARCH == item.type))
240 ? View.GONE : View.INVISIBLE);
241 view.setOnClickListener(this);
242 ic2.setOnClickListener(this);
243 }
244
245 class SuggestFilter extends Filter {
246
247 int count;
248 SuggestionResults results;
249
250 @Override
251 public CharSequence convertResultToString(Object item) {
252 if (item == null) {
253 return "";
254 }
255 SuggestItem sitem = (SuggestItem) item;
256 if (sitem.title != null) {
257 return sitem.title;
258 } else {
259 return sitem.url;
260 }
261 }
262
263 @Override
264 protected FilterResults performFiltering(CharSequence constraint) {
265 FilterResults res = new FilterResults();
266 if (TextUtils.isEmpty(constraint)) {
267 res.count = 0;
268 res.values = null;
269 return res;
270 }
271 results = new SuggestionResults();
272 count = 0;
273 if (constraint != null) {
274 for (CursorSource sc : mSources) {
275 sc.runQuery(constraint);
276 }
277 mixResults();
278 }
279 res.count = count;
280 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);
287 int n = Math.min(s.getCount(), (mLandscapeMode ? mLinesLandscape
288 : mLinesPortrait));
289 boolean more = true;
290 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 }
308
309 }
310
311 @Override
312 protected void publishResults(CharSequence constraint, FilterResults fresults) {
313 mResults = (SuggestionResults) fresults.values;
314 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();
457 ub.appendQueryParameter(BrowserContract.PARAM_LIMIT,
458 Integer.toString(mLinesPortrait));
459 mCursor =
460 mContext.getContentResolver().query(ub.build(), COMBINED_PROJECTION,
461 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) {
491 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
492 return null;
493 } else {
494 return stripUrl(url);
495 }
496 }
497
498 /**
499 * Strips the provided url of preceding "http://" and any trailing "/". Does not
500 * strip "https://". If the provided string cannot be stripped, the original string
501 * is returned.
502 *
503 * TODO: Put this in TextUtils to be used by other packages doing something similar.
504 *
505 * @param url a url to strip, like "http://www.google.com/"
506 * @return a stripped url like "www.google.com", or the original string if it could
507 * not be stripped
508 */
509 private String stripUrl(String url) {
510 if (url == null) return null;
511 Matcher m = STRIP_URL_PATTERN.matcher(url);
512 if (m.matches() && m.groupCount() == 3) {
513 return m.group(2);
514 } else {
515 return url;
516 }
517 }
518
519 }
520
521 class SearchesCursor extends CursorSource {
522
523 @Override
524 public SuggestItem getItem() {
525 if ((mCursor != null) && (!mCursor.isAfterLast())) {
526 return new SuggestItem(mCursor.getString(0), null, TYPE_SEARCH);
527 }
528 return null;
529 }
530
531 @Override
532 public void runQuery(CharSequence constraint) {
533 // constraint != null
534 if (mCursor != null) {
535 mCursor.close();
536 }
537 String like = constraint + "%";
538 String[] args = new String[] {constraint.toString()};
539 String selection = BrowserContract.Searches.SEARCH + " LIKE ?";
540 Uri.Builder ub = BrowserContract.Searches.CONTENT_URI.buildUpon();
541 ub.appendQueryParameter(BrowserContract.PARAM_LIMIT,
542 Integer.toString(mLinesPortrait));
543 mCursor =
544 mContext.getContentResolver().query(ub.build(), SEARCHES_PROJECTION,
545 selection,
546 args, BrowserContract.Searches.DATE + " DESC");
547 if (mCursor != null) {
548 mCursor.moveToFirst();
549 }
550 }
551
552 }
553
554 class SuggestCursor extends CursorSource {
555
556 @Override
557 public SuggestItem getItem() {
558 if (mCursor != null) {
559 String title = mCursor.getString(
560 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
561 String text2 = mCursor.getString(
562 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2));
563 String url = mCursor.getString(
564 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_2_URL));
565 String uri = mCursor.getString(
566 mCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA));
567 int type = (TextUtils.isEmpty(url)) ? TYPE_SUGGEST : TYPE_SUGGEST_URL;
568 return new SuggestItem(title, url, type);
569 }
570 return null;
571 }
572
573 @Override
574 public void runQuery(CharSequence constraint) {
575 if (mCursor != null) {
576 mCursor.close();
577 }
578 if (!TextUtils.isEmpty(constraint)) {
579 SearchEngine searchEngine = BrowserSettings.getInstance().getSearchEngine();
580 if (searchEngine != null && searchEngine.supportsSuggestions()) {
581 mCursor = searchEngine.getSuggestions(mContext, constraint.toString());
582 if (mCursor != null) {
583 mCursor.moveToFirst();
584 }
585 }
586 } else {
587 mCursor = null;
588 }
589 }
590
591 }
592
593}