2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
19 import android.app.SearchManager;
20 import android.app.SearchableInfo;
21 import android.backup.BackupManager;
22 import android.content.ComponentName;
23 import android.content.ContentProvider;
24 import android.content.ContentResolver;
25 import android.content.ContentUris;
26 import android.content.ContentValues;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.UriMatcher;
31 import android.content.SharedPreferences.Editor;
32 import android.content.pm.PackageManager;
33 import android.content.pm.ResolveInfo;
34 import android.database.AbstractCursor;
35 import android.database.ContentObserver;
36 import android.database.Cursor;
37 import android.database.sqlite.SQLiteDatabase;
38 import android.database.sqlite.SQLiteOpenHelper;
39 import android.net.Uri;
40 import android.os.AsyncTask;
41 import android.os.Handler;
42 import android.preference.PreferenceManager;
43 import android.provider.Browser;
44 import android.provider.Settings;
45 import android.provider.Browser.BookmarkColumns;
46 import android.speech.RecognizerResultsIntent;
47 import android.text.TextUtils;
48 import android.util.Log;
49 import android.util.TypedValue;
51 import com.android.common.Patterns;
53 import com.google.android.providers.GoogleSettings.Partner;
56 import java.io.FilenameFilter;
57 import java.util.ArrayList;
58 import java.util.Date;
59 import java.util.regex.Matcher;
60 import java.util.regex.Pattern;
63 public class BrowserProvider extends ContentProvider {
65 private SQLiteOpenHelper mOpenHelper;
66 private BackupManager mBackupManager;
67 private static final String sDatabaseName = "browser.db";
68 private static final String TAG = "BrowserProvider";
69 private static final String ORDER_BY = "visits DESC, date DESC";
71 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
72 "viewer?source=androidclient";
74 private static final String[] TABLE_NAMES = new String[] {
75 "bookmarks", "searches"
77 private static final String[] SUGGEST_PROJECTION = new String[] {
78 "_id", "url", "title", "bookmark", "user_entered"
80 private static final String SUGGEST_SELECTION =
81 "(url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
82 + " OR title LIKE ?) AND (bookmark = 1 OR user_entered = 1)";
83 private String[] SUGGEST_ARGS = new String[5];
85 // shared suggestion array index, make sure to match COLUMNS
86 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
87 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
88 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
89 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
90 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
91 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
92 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
93 private static final int SUGGEST_COLUMN_FORMAT = 8;
94 private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
96 // shared suggestion columns
97 private static final String[] COLUMNS = new String[] {
99 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
100 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
101 SearchManager.SUGGEST_COLUMN_TEXT_1,
102 SearchManager.SUGGEST_COLUMN_TEXT_2,
103 SearchManager.SUGGEST_COLUMN_ICON_1,
104 SearchManager.SUGGEST_COLUMN_ICON_2,
105 SearchManager.SUGGEST_COLUMN_QUERY,
106 SearchManager.SUGGEST_COLUMN_FORMAT,
107 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
109 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
110 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
111 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
112 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
114 // make sure that these match the index of TABLE_NAMES
115 private static final int URI_MATCH_BOOKMARKS = 0;
116 private static final int URI_MATCH_SEARCHES = 1;
117 // (id % 10) should match the table name index
118 private static final int URI_MATCH_BOOKMARKS_ID = 10;
119 private static final int URI_MATCH_SEARCHES_ID = 11;
121 private static final int URI_MATCH_SUGGEST = 20;
122 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
124 private static final UriMatcher URI_MATCHER;
127 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
128 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
129 URI_MATCH_BOOKMARKS);
130 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
131 URI_MATCH_BOOKMARKS_ID);
132 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
134 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
135 URI_MATCH_SEARCHES_ID);
136 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
138 URI_MATCHER.addURI("browser",
139 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
140 URI_MATCH_BOOKMARKS_SUGGEST);
143 // 1 -> 2 add cache table
144 // 2 -> 3 update history table
145 // 3 -> 4 add passwords table
146 // 4 -> 5 add settings table
149 // 7 -> 8 drop proxy table
150 // 8 -> 9 drop settings table
151 // 9 -> 10 add form_urls and form_data
152 // 10 -> 11 add searches table
153 // 11 -> 12 modify cache table
154 // 12 -> 13 modify cache table
155 // 13 -> 14 correspond with Google Bookmarks schema
156 // 14 -> 15 move couple of tables to either browser private database or webview database
157 // 15 -> 17 Set it up for the SearchManager
158 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
159 // 18 -> 19 Remove labels table
160 // 19 -> 20 Added thumbnail
161 // 20 -> 21 Added touch_icon
162 // 21 -> 22 Remove "clientid"
163 // 22 -> 23 Added user_entered
164 private static final int DATABASE_VERSION = 23;
166 // Regular expression which matches http://, followed by some stuff, followed by
167 // optionally a trailing slash, all matched as separate groups.
168 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
170 private SearchManager mSearchManager;
172 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
173 // the current theme. This is not set until/unless beautifyUrl is called, at which point
174 // this variable caches the color value.
175 private static String mSearchUrlColorId;
177 public BrowserProvider() {
181 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
182 StringBuffer sb = new StringBuffer();
185 final String client_id = Partner.getString(context.getContentResolver(),
186 Partner.CLIENT_ID, "android-google");
188 for (int i = 0; i < srcString.length(); ++i) {
189 char c = srcString.charAt(i);
191 sb.append(srcString.subSequence(lastCharLoc, i));
194 for (int j = i; j < srcString.length(); ++j) {
195 char k = srcString.charAt(j);
197 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
198 if (propertyKeyValue.equals("CLIENT_ID")) {
199 sb.append(client_id);
201 sb.append("unknown");
210 if (srcString.length() - lastCharLoc > 0) {
211 // Put on the tail, if there is one
212 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
217 private static class DatabaseHelper extends SQLiteOpenHelper {
218 private Context mContext;
220 public DatabaseHelper(Context context) {
221 super(context, sDatabaseName, null, DATABASE_VERSION);
226 public void onCreate(SQLiteDatabase db) {
227 db.execSQL("CREATE TABLE bookmarks (" +
228 "_id INTEGER PRIMARY KEY," +
234 "description TEXT," +
235 "bookmark INTEGER," +
236 "favicon BLOB DEFAULT NULL," +
237 "thumbnail BLOB DEFAULT NULL," +
238 "touch_icon BLOB DEFAULT NULL," +
239 "user_entered INTEGER" +
242 final CharSequence[] bookmarks = mContext.getResources()
243 .getTextArray(R.array.bookmarks);
244 int size = bookmarks.length;
246 for (int i = 0; i < size; i = i + 2) {
247 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
248 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
249 "date, created, bookmark)" + " VALUES('" +
250 bookmarks[i] + "', '" + bookmarkDestination +
253 } catch (ArrayIndexOutOfBoundsException e) {
256 db.execSQL("CREATE TABLE searches (" +
257 "_id INTEGER PRIMARY KEY," +
264 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
265 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
267 if (oldVersion == 18) {
268 db.execSQL("DROP TABLE IF EXISTS labels");
270 if (oldVersion <= 19) {
271 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
273 if (oldVersion < 21) {
274 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
276 if (oldVersion < 22) {
277 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
280 if (oldVersion < 23) {
281 db.execSQL("ALTER TABLE bookmarks ADD COLUMN user_entered INTEGER;");
283 db.execSQL("DROP TABLE IF EXISTS bookmarks");
284 db.execSQL("DROP TABLE IF EXISTS searches");
289 private void removeGears() {
290 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
291 public Void doInBackground(Void... unused) {
292 String browserDataDirString = mContext.getApplicationInfo().dataDir;
293 final String appPluginsDirString = "app_plugins";
294 final String gearsPrefix = "gears";
295 File appPluginsDir = new File(browserDataDirString + File.separator
296 + appPluginsDirString);
297 if (!appPluginsDir.exists()) {
300 // Delete the Gears plugin files
301 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
302 public boolean accept(File dir, String filename) {
303 return filename.startsWith(gearsPrefix);
306 for (int i = 0; i < gearsFiles.length; ++i) {
307 if (gearsFiles[i].isDirectory()) {
308 deleteDirectory(gearsFiles[i]);
310 gearsFiles[i].delete();
313 // Delete the Gears data files
314 File gearsDataDir = new File(browserDataDirString + File.separator
316 if (!gearsDataDir.exists()) {
319 deleteDirectory(gearsDataDir);
323 private void deleteDirectory(File currentDir) {
324 File[] files = currentDir.listFiles();
325 for (int i = 0; i < files.length; ++i) {
326 if (files[i].isDirectory()) {
327 deleteDirectory(files[i]);
340 public boolean onCreate() {
341 final Context context = getContext();
342 mOpenHelper = new DatabaseHelper(context);
343 mBackupManager = new BackupManager(context);
344 // we added "picasa web album" into default bookmarks for version 19.
345 // To avoid erasing the bookmark table, we added it explicitly for
346 // version 18 and 19 as in the other cases, we will erase the table.
347 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
348 SharedPreferences p = PreferenceManager
349 .getDefaultSharedPreferences(context);
350 boolean fix = p.getBoolean("fix_picasa", true);
353 Editor ed = p.edit();
354 ed.putBoolean("fix_picasa", false);
358 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
359 mShowWebSuggestionsSettingChangeObserver
360 = new ShowWebSuggestionsSettingChangeObserver();
361 context.getContentResolver().registerContentObserver(
362 Settings.System.getUriFor(
363 Settings.System.SHOW_WEB_SUGGESTIONS),
364 true, mShowWebSuggestionsSettingChangeObserver);
365 updateShowWebSuggestions();
370 * This Observer will ensure that if the user changes the system
371 * setting of whether to display web suggestions, we will
372 * change accordingly.
374 /* package */ class ShowWebSuggestionsSettingChangeObserver
375 extends ContentObserver {
376 public ShowWebSuggestionsSettingChangeObserver() {
377 super(new Handler());
381 public void onChange(boolean selfChange) {
382 updateShowWebSuggestions();
386 private ShowWebSuggestionsSettingChangeObserver
387 mShowWebSuggestionsSettingChangeObserver;
389 // If non-null, then the system is set to show web suggestions,
390 // and this is the SearchableInfo to use to get them.
391 private SearchableInfo mSearchableInfo;
394 * Check the system settings to see whether web suggestions are
395 * allowed. If so, store the SearchableInfo to grab suggestions
396 * while the user is typing.
398 private void updateShowWebSuggestions() {
399 mSearchableInfo = null;
400 Context context = getContext();
401 if (Settings.System.getInt(context.getContentResolver(),
402 Settings.System.SHOW_WEB_SUGGESTIONS,
403 1 /* default on */) == 1) {
404 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
405 intent.addCategory(Intent.CATEGORY_DEFAULT);
406 ResolveInfo info = context.getPackageManager().resolveActivity(
407 intent, PackageManager.MATCH_DEFAULT_ONLY);
409 ComponentName googleSearchComponent =
410 new ComponentName(info.activityInfo.packageName,
411 info.activityInfo.name);
412 mSearchableInfo = mSearchManager.getSearchableInfo(
413 googleSearchComponent, false);
418 private void fixPicasaBookmark() {
419 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
420 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
421 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
423 if (!cursor.moveToFirst()) {
424 // set "created" so that it will be on the top of the list
425 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
426 "date, created, bookmark)" + " VALUES('" +
427 getContext().getString(R.string.picasa) + "', '"
428 + PICASA_URL + "', 0, 0, " + new Date().getTime()
432 if (cursor != null) {
439 * Subclass AbstractCursor so we can combine multiple Cursors and add
441 * Here are the rules.
442 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
444 * 2. If bookmark/history entries are less than
445 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
447 private class MySuggestionCursor extends AbstractCursor {
448 private Cursor mHistoryCursor;
449 private Cursor mSuggestCursor;
450 private int mHistoryCount;
451 private int mSuggestionCount;
452 private boolean mIncludeWebSearch;
453 private String mString;
454 private int mSuggestText1Id;
455 private int mSuggestText2Id;
456 private int mSuggestQueryId;
457 private int mSuggestIntentExtraDataId;
459 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
462 mHistoryCount = hc.getCount();
463 mSuggestionCount = sc != null ? sc.getCount() : 0;
464 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
465 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
468 mIncludeWebSearch = string.length() > 0;
470 // Some web suggest providers only give suggestions and have no description string for
471 // items. The order of the result columns may be different as well. So retrieve the
472 // column indices for the fields we need now and check before using below.
473 if (mSuggestCursor == null) {
474 mSuggestText1Id = -1;
475 mSuggestText2Id = -1;
476 mSuggestQueryId = -1;
477 mSuggestIntentExtraDataId = -1;
479 mSuggestText1Id = mSuggestCursor.getColumnIndex(
480 SearchManager.SUGGEST_COLUMN_TEXT_1);
481 mSuggestText2Id = mSuggestCursor.getColumnIndex(
482 SearchManager.SUGGEST_COLUMN_TEXT_2);
483 mSuggestQueryId = mSuggestCursor.getColumnIndex(
484 SearchManager.SUGGEST_COLUMN_QUERY);
485 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
486 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
491 public boolean onMove(int oldPosition, int newPosition) {
492 if (mHistoryCursor == null) {
495 if (mIncludeWebSearch) {
496 if (newPosition == 0) {
502 if (mHistoryCount > newPosition) {
503 mHistoryCursor.moveToPosition(newPosition);
505 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
511 public int getCount() {
512 if (mIncludeWebSearch) {
513 return mHistoryCount + mSuggestionCount + 1;
515 return mHistoryCount + mSuggestionCount;
520 public String[] getColumnNames() {
525 public String getString(int columnIndex) {
526 if ((mPos != -1 && mHistoryCursor != null)) {
527 int position = mIncludeWebSearch ? mPos - 1 : mPos;
528 switch(columnIndex) {
529 case SUGGEST_COLUMN_INTENT_ACTION_ID:
530 if (position >= 0 && position < mHistoryCount) {
531 return Intent.ACTION_VIEW;
533 return Intent.ACTION_SEARCH;
536 case SUGGEST_COLUMN_INTENT_DATA_ID:
537 if (position >= 0 && position < mHistoryCount) {
538 return mHistoryCursor.getString(1);
543 case SUGGEST_COLUMN_TEXT_1_ID:
546 } else if (mHistoryCount > position) {
547 return getHistoryTitle();
549 if (mSuggestText1Id == -1) return null;
550 return mSuggestCursor.getString(mSuggestText1Id);
553 case SUGGEST_COLUMN_TEXT_2_ID:
555 return getContext().getString(R.string.search_the_web);
556 } else if (mHistoryCount > position) {
557 return getHistorySubtitle();
559 if (mSuggestText2Id == -1) return null;
560 return mSuggestCursor.getString(mSuggestText2Id);
563 case SUGGEST_COLUMN_ICON_1_ID:
564 if (position >= 0 && position < mHistoryCount) {
565 if (mHistoryCursor.getInt(3) == 1) {
566 return Integer.valueOf(
567 R.drawable.ic_search_category_bookmark)
570 return Integer.valueOf(
571 R.drawable.ic_search_category_history)
575 return Integer.valueOf(
576 R.drawable.ic_search_category_suggest)
580 case SUGGEST_COLUMN_ICON_2_ID:
583 case SUGGEST_COLUMN_QUERY_ID:
586 } else if (mHistoryCount > position) {
587 // Return the url in the intent query column. This is ignored
588 // within the browser because our searchable is set to
589 // android:searchMode="queryRewriteFromData", but it is used by
590 // global search for query rewriting.
591 return mHistoryCursor.getString(1);
593 if (mSuggestQueryId == -1) return null;
594 return mSuggestCursor.getString(mSuggestQueryId);
597 case SUGGEST_COLUMN_FORMAT:
600 case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
603 } else if (mHistoryCount > position) {
606 if (mSuggestIntentExtraDataId == -1) return null;
607 return mSuggestCursor.getString(mSuggestIntentExtraDataId);
615 public double getDouble(int column) {
616 throw new UnsupportedOperationException();
620 public float getFloat(int column) {
621 throw new UnsupportedOperationException();
625 public int getInt(int column) {
626 throw new UnsupportedOperationException();
630 public long getLong(int column) {
631 if ((mPos != -1) && column == 0) {
632 return mPos; // use row# as the _Id
634 throw new UnsupportedOperationException();
638 public short getShort(int column) {
639 throw new UnsupportedOperationException();
643 public boolean isNull(int column) {
644 throw new UnsupportedOperationException();
647 // TODO Temporary change, finalize after jq's changes go in
648 public void deactivate() {
649 if (mHistoryCursor != null) {
650 mHistoryCursor.deactivate();
652 if (mSuggestCursor != null) {
653 mSuggestCursor.deactivate();
658 public boolean requery() {
659 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
660 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
663 // TODO Temporary change, finalize after jq's changes go in
664 public void close() {
666 if (mHistoryCursor != null) {
667 mHistoryCursor.close();
668 mHistoryCursor = null;
670 if (mSuggestCursor != null) {
671 mSuggestCursor.close();
672 mSuggestCursor = null;
677 * Provides the title (text line 1) for a browser suggestion, which should be the
678 * webpage title. If the webpage title is empty, returns the stripped url instead.
680 * @return the title string to use
682 private String getHistoryTitle() {
683 String title = mHistoryCursor.getString(2 /* webpage title */);
684 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
685 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
691 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
692 * webpage url. If the webpage title is empty, then the url should go in the title
693 * instead, and the subtitle should be empty, so this would return null.
695 * @return the subtitle string to use, or null if none
697 private String getHistorySubtitle() {
698 String title = mHistoryCursor.getString(2 /* webpage title */);
699 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
702 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
707 * Strips "http://" from the beginning of a url and "/" from the end,
708 * and adds html formatting to make it green.
710 private String beautifyUrl(String url) {
711 if (mSearchUrlColorId == null) {
712 // Get the color used for this purpose from the current theme.
713 TypedValue colorValue = new TypedValue();
714 getContext().getTheme().resolveAttribute(
715 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
716 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
719 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
723 private static class ResultsCursor extends AbstractCursor {
724 // Array indices for RESULTS_COLUMNS
725 private static final int RESULT_ACTION_ID = 1;
726 private static final int RESULT_DATA_ID = 2;
727 private static final int RESULT_TEXT_ID = 3;
728 private static final int RESULT_ICON_ID = 4;
729 private static final int RESULT_EXTRA_ID = 5;
731 private static final String[] RESULTS_COLUMNS = new String[] {
733 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
734 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
735 SearchManager.SUGGEST_COLUMN_TEXT_1,
736 SearchManager.SUGGEST_COLUMN_ICON_1,
737 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA
739 private final ArrayList<String> mResults;
740 public ResultsCursor(ArrayList<String> results) {
743 public int getCount() { return mResults.size(); }
745 public String[] getColumnNames() {
746 return RESULTS_COLUMNS;
749 public String getString(int column) {
751 case RESULT_ACTION_ID:
752 return RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS;
754 // The data is used when the phone is in landscape mode. We
755 // still want to show the result string.
757 return mResults.get(mPos);
758 case RESULT_EXTRA_ID:
759 // The Intent's extra data will store the index into
760 // mResults so the BrowserActivity will know which result to
762 return Integer.toString(mPos);
764 return Integer.valueOf(R.drawable.magnifying_glass)
770 public short getShort(int column) {
771 throw new UnsupportedOperationException();
773 public int getInt(int column) {
774 throw new UnsupportedOperationException();
776 public long getLong(int column) {
777 if ((mPos != -1) && column == 0) {
778 return mPos; // use row# as the _id
780 throw new UnsupportedOperationException();
782 public float getFloat(int column) {
783 throw new UnsupportedOperationException();
785 public double getDouble(int column) {
786 throw new UnsupportedOperationException();
788 public boolean isNull(int column) {
789 throw new UnsupportedOperationException();
793 private ResultsCursor mResultsCursor;
796 * Provide a set of results to be returned to query, intended to be used
797 * by the SearchDialog when the BrowserActivity is in voice search mode.
798 * @param results Strings to display in the dropdown from the SearchDialog
800 /* package */ void setQueryResults(ArrayList<String> results) {
801 if (results == null) {
802 mResultsCursor = null;
804 mResultsCursor = new ResultsCursor(results);
809 public Cursor query(Uri url, String[] projectionIn, String selection,
810 String[] selectionArgs, String sortOrder)
811 throws IllegalStateException {
812 int match = URI_MATCHER.match(url);
814 throw new IllegalArgumentException("Unknown URL");
816 if (match == URI_MATCH_SUGGEST && mResultsCursor != null) {
817 Cursor results = mResultsCursor;
818 mResultsCursor = null;
821 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
823 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
824 String suggestSelection;
826 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
827 suggestSelection = null;
830 String like = selectionArgs[0] + "%";
831 if (selectionArgs[0].startsWith("http")
832 || selectionArgs[0].startsWith("file")) {
833 myArgs = new String[1];
835 suggestSelection = selection;
837 SUGGEST_ARGS[0] = "http://" + like;
838 SUGGEST_ARGS[1] = "http://www." + like;
839 SUGGEST_ARGS[2] = "https://" + like;
840 SUGGEST_ARGS[3] = "https://www." + like;
841 // To match against titles.
842 SUGGEST_ARGS[4] = like;
843 myArgs = SUGGEST_ARGS;
844 suggestSelection = SUGGEST_SELECTION;
848 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
849 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
850 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
852 if (match == URI_MATCH_BOOKMARKS_SUGGEST
853 || Patterns.WEB_URL.matcher(selectionArgs[0]).matches()) {
854 return new MySuggestionCursor(c, null, "");
856 // get Google suggest if there is still space in the list
857 if (myArgs != null && myArgs.length > 1
858 && mSearchableInfo != null
859 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
860 Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
861 return new MySuggestionCursor(c, sc, selectionArgs[0]);
863 return new MySuggestionCursor(c, null, selectionArgs[0]);
867 String[] projection = null;
868 if (projectionIn != null && projectionIn.length > 0) {
869 projection = new String[projectionIn.length + 1];
870 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
871 projection[projectionIn.length] = "_id AS _id";
874 StringBuilder whereClause = new StringBuilder(256);
875 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
876 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
880 // Tack on the user's selection, if present
881 if (selection != null && selection.length() > 0) {
882 if (whereClause.length() > 0) {
883 whereClause.append(" AND ");
886 whereClause.append('(');
887 whereClause.append(selection);
888 whereClause.append(')');
890 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
891 whereClause.toString(), selectionArgs, null, null, sortOrder,
893 c.setNotificationUri(getContext().getContentResolver(), url);
898 public String getType(Uri url) {
899 int match = URI_MATCHER.match(url);
901 case URI_MATCH_BOOKMARKS:
902 return "vnd.android.cursor.dir/bookmark";
904 case URI_MATCH_BOOKMARKS_ID:
905 return "vnd.android.cursor.item/bookmark";
907 case URI_MATCH_SEARCHES:
908 return "vnd.android.cursor.dir/searches";
910 case URI_MATCH_SEARCHES_ID:
911 return "vnd.android.cursor.item/searches";
913 case URI_MATCH_SUGGEST:
914 return SearchManager.SUGGEST_MIME_TYPE;
917 throw new IllegalArgumentException("Unknown URL");
922 public Uri insert(Uri url, ContentValues initialValues) {
923 boolean isBookmarkTable = false;
924 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
926 int match = URI_MATCHER.match(url);
929 case URI_MATCH_BOOKMARKS: {
930 // Insert into the bookmarks table
931 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
934 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
937 isBookmarkTable = true;
941 case URI_MATCH_SEARCHES: {
942 // Insert into the searches table
943 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
946 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
953 throw new IllegalArgumentException("Unknown URL");
957 throw new IllegalArgumentException("Unknown URL");
959 getContext().getContentResolver().notifyChange(uri, null);
961 // Back up the new bookmark set if we just inserted one.
962 // A row created when bookmarks are added from scratch will have
963 // bookmark=1 in the initial value set.
965 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
966 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
967 mBackupManager.dataChanged();
973 public int delete(Uri url, String where, String[] whereArgs) {
974 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
976 int match = URI_MATCHER.match(url);
977 if (match == -1 || match == URI_MATCH_SUGGEST) {
978 throw new IllegalArgumentException("Unknown URL");
981 // need to know whether it's the bookmarks table for a couple of reasons
982 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
985 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
986 StringBuilder sb = new StringBuilder();
987 if (where != null && where.length() > 0) {
990 sb.append(" ) AND ");
992 id = url.getPathSegments().get(1);
995 where = sb.toString();
998 ContentResolver cr = getContext().getContentResolver();
1000 // we'lll need to back up the bookmark set if we are about to delete one
1001 if (isBookmarkTable) {
1002 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
1003 new String[] { BookmarkColumns.BOOKMARK },
1004 "_id = " + id, null, null);
1005 if (cursor.moveToNext()) {
1006 if (cursor.getInt(0) != 0) {
1007 // yep, this record is a bookmark
1008 mBackupManager.dataChanged();
1014 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
1015 cr.notifyChange(url, null);
1020 public int update(Uri url, ContentValues values, String where,
1021 String[] whereArgs) {
1022 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1024 int match = URI_MATCHER.match(url);
1025 if (match == -1 || match == URI_MATCH_SUGGEST) {
1026 throw new IllegalArgumentException("Unknown URL");
1030 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
1031 boolean changingBookmarks = false;
1033 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
1034 StringBuilder sb = new StringBuilder();
1035 if (where != null && where.length() > 0) {
1038 sb.append(" ) AND ");
1040 id = url.getPathSegments().get(1);
1041 sb.append("_id = ");
1043 where = sb.toString();
1046 ContentResolver cr = getContext().getContentResolver();
1048 // Not all bookmark-table updates should be backed up. Look to see
1049 // whether we changed the title, url, or "is a bookmark" state, and
1050 // request a backup if so.
1051 if (isBookmarkTable) {
1052 // Alterations to the bookmark field inherently change the bookmark
1053 // set, so we don't need to query the record; we know a priori that
1054 // we will need to back up this change.
1055 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
1056 changingBookmarks = true;
1058 // changing the title or URL of a bookmark record requires a backup,
1059 // but we don't know wether such an update is on a bookmark without
1060 // querying the record
1061 if (!changingBookmarks &&
1062 (values.containsKey(BookmarkColumns.TITLE)
1063 || values.containsKey(BookmarkColumns.URL))) {
1064 // when isBookmarkTable is true, the 'id' var was assigned above
1065 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
1066 new String[] { BookmarkColumns.BOOKMARK },
1067 "_id = " + id, null, null);
1068 if (cursor.moveToNext()) {
1069 changingBookmarks = (cursor.getInt(0) != 0);
1074 // if this *is* a bookmark row we're altering, we need to back it up.
1075 if (changingBookmarks) {
1076 mBackupManager.dataChanged();
1080 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
1081 cr.notifyChange(url, null);
1086 * Strips the provided url of preceding "http://" and any trailing "/". Does not
1087 * strip "https://". If the provided string cannot be stripped, the original string
1090 * TODO: Put this in TextUtils to be used by other packages doing something similar.
1092 * @param url a url to strip, like "http://www.google.com/"
1093 * @return a stripped url like "www.google.com", or the original string if it could
1096 private static String stripUrl(String url) {
1097 if (url == null) return null;
1098 Matcher m = STRIP_URL_PATTERN.matcher(url);
1099 if (m.matches() && m.groupCount() == 3) {