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;
50 import android.webkit.GeolocationPermissions;
52 import com.android.common.Patterns;
54 import com.google.android.gsf.GoogleSettingsContract.Partner;
57 import java.io.FilenameFilter;
58 import java.util.ArrayList;
59 import java.util.Date;
60 import java.util.regex.Matcher;
61 import java.util.regex.Pattern;
64 public class BrowserProvider extends ContentProvider {
66 private SQLiteOpenHelper mOpenHelper;
67 private BackupManager mBackupManager;
68 private static final String sDatabaseName = "browser.db";
69 private static final String TAG = "BrowserProvider";
70 private static final String ORDER_BY = "visits DESC, date DESC";
72 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
73 "viewer?source=androidclient";
75 private static final String[] TABLE_NAMES = new String[] {
76 "bookmarks", "searches", "geolocation"
78 private static final String[] SUGGEST_PROJECTION = new String[] {
79 "_id", "url", "title", "bookmark", "user_entered"
81 private static final String SUGGEST_SELECTION =
82 "(url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
83 + " OR title LIKE ?) AND (bookmark = 1 OR user_entered = 1)";
84 private String[] SUGGEST_ARGS = new String[5];
86 // shared suggestion array index, make sure to match COLUMNS
87 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
88 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
89 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
90 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
91 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
92 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
93 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
94 private static final int SUGGEST_COLUMN_FORMAT = 8;
95 private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
97 // shared suggestion columns
98 private static final String[] COLUMNS = new String[] {
100 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
101 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
102 SearchManager.SUGGEST_COLUMN_TEXT_1,
103 SearchManager.SUGGEST_COLUMN_TEXT_2,
104 SearchManager.SUGGEST_COLUMN_ICON_1,
105 SearchManager.SUGGEST_COLUMN_ICON_2,
106 SearchManager.SUGGEST_COLUMN_QUERY,
107 SearchManager.SUGGEST_COLUMN_FORMAT,
108 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
110 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
111 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
112 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
113 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
115 // make sure that these match the index of TABLE_NAMES
116 private static final int URI_MATCH_BOOKMARKS = 0;
117 private static final int URI_MATCH_SEARCHES = 1;
118 private static final int URI_MATCH_GEOLOCATION = 2;
119 // (id % 10) should match the table name index
120 private static final int URI_MATCH_BOOKMARKS_ID = 10;
121 private static final int URI_MATCH_SEARCHES_ID = 11;
123 private static final int URI_MATCH_SUGGEST = 20;
124 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
126 private static final UriMatcher URI_MATCHER;
129 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
130 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
131 URI_MATCH_BOOKMARKS);
132 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
133 URI_MATCH_BOOKMARKS_ID);
134 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
136 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
137 URI_MATCH_SEARCHES_ID);
138 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
140 URI_MATCHER.addURI("browser",
141 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
142 URI_MATCH_BOOKMARKS_SUGGEST);
143 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_GEOLOCATION],
144 URI_MATCH_GEOLOCATION);
147 // 1 -> 2 add cache table
148 // 2 -> 3 update history table
149 // 3 -> 4 add passwords table
150 // 4 -> 5 add settings table
153 // 7 -> 8 drop proxy table
154 // 8 -> 9 drop settings table
155 // 9 -> 10 add form_urls and form_data
156 // 10 -> 11 add searches table
157 // 11 -> 12 modify cache table
158 // 12 -> 13 modify cache table
159 // 13 -> 14 correspond with Google Bookmarks schema
160 // 14 -> 15 move couple of tables to either browser private database or webview database
161 // 15 -> 17 Set it up for the SearchManager
162 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
163 // 18 -> 19 Remove labels table
164 // 19 -> 20 Added thumbnail
165 // 20 -> 21 Added touch_icon
166 // 21 -> 22 Remove "clientid"
167 // 22 -> 23 Added user_entered
168 private static final int DATABASE_VERSION = 23;
170 // Regular expression which matches http://, followed by some stuff, followed by
171 // optionally a trailing slash, all matched as separate groups.
172 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
174 private SearchManager mSearchManager;
176 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
177 // the current theme. This is not set until/unless beautifyUrl is called, at which point
178 // this variable caches the color value.
179 private static String mSearchUrlColorId;
181 public BrowserProvider() {
185 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
186 StringBuffer sb = new StringBuffer();
189 final String client_id = Partner.getString(context.getContentResolver(),
190 Partner.CLIENT_ID, "android-google");
192 for (int i = 0; i < srcString.length(); ++i) {
193 char c = srcString.charAt(i);
195 sb.append(srcString.subSequence(lastCharLoc, i));
198 for (int j = i; j < srcString.length(); ++j) {
199 char k = srcString.charAt(j);
201 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
202 if (propertyKeyValue.equals("CLIENT_ID")) {
203 sb.append(client_id);
205 sb.append("unknown");
214 if (srcString.length() - lastCharLoc > 0) {
215 // Put on the tail, if there is one
216 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
221 private static class DatabaseHelper extends SQLiteOpenHelper {
222 private Context mContext;
224 public DatabaseHelper(Context context) {
225 super(context, sDatabaseName, null, DATABASE_VERSION);
230 public void onCreate(SQLiteDatabase db) {
231 db.execSQL("CREATE TABLE bookmarks (" +
232 "_id INTEGER PRIMARY KEY," +
238 "description TEXT," +
239 "bookmark INTEGER," +
240 "favicon BLOB DEFAULT NULL," +
241 "thumbnail BLOB DEFAULT NULL," +
242 "touch_icon BLOB DEFAULT NULL," +
243 "user_entered INTEGER" +
246 final CharSequence[] bookmarks = mContext.getResources()
247 .getTextArray(R.array.bookmarks);
248 int size = bookmarks.length;
250 for (int i = 0; i < size; i = i + 2) {
251 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
252 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
253 "date, created, bookmark)" + " VALUES('" +
254 bookmarks[i] + "', '" + bookmarkDestination +
257 } catch (ArrayIndexOutOfBoundsException e) {
260 db.execSQL("CREATE TABLE searches (" +
261 "_id INTEGER PRIMARY KEY," +
268 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
269 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
271 if (oldVersion == 18) {
272 db.execSQL("DROP TABLE IF EXISTS labels");
274 if (oldVersion <= 19) {
275 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
277 if (oldVersion < 21) {
278 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
280 if (oldVersion < 22) {
281 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
284 if (oldVersion < 23) {
285 db.execSQL("ALTER TABLE bookmarks ADD COLUMN user_entered INTEGER;");
287 db.execSQL("DROP TABLE IF EXISTS bookmarks");
288 db.execSQL("DROP TABLE IF EXISTS searches");
293 private void removeGears() {
294 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
295 public Void doInBackground(Void... unused) {
296 String browserDataDirString = mContext.getApplicationInfo().dataDir;
297 final String appPluginsDirString = "app_plugins";
298 final String gearsPrefix = "gears";
299 File appPluginsDir = new File(browserDataDirString + File.separator
300 + appPluginsDirString);
301 if (!appPluginsDir.exists()) {
304 // Delete the Gears plugin files
305 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
306 public boolean accept(File dir, String filename) {
307 return filename.startsWith(gearsPrefix);
310 for (int i = 0; i < gearsFiles.length; ++i) {
311 if (gearsFiles[i].isDirectory()) {
312 deleteDirectory(gearsFiles[i]);
314 gearsFiles[i].delete();
317 // Delete the Gears data files
318 File gearsDataDir = new File(browserDataDirString + File.separator
320 if (!gearsDataDir.exists()) {
323 deleteDirectory(gearsDataDir);
327 private void deleteDirectory(File currentDir) {
328 File[] files = currentDir.listFiles();
329 for (int i = 0; i < files.length; ++i) {
330 if (files[i].isDirectory()) {
331 deleteDirectory(files[i]);
344 public boolean onCreate() {
345 final Context context = getContext();
346 mOpenHelper = new DatabaseHelper(context);
347 mBackupManager = new BackupManager(context);
348 // we added "picasa web album" into default bookmarks for version 19.
349 // To avoid erasing the bookmark table, we added it explicitly for
350 // version 18 and 19 as in the other cases, we will erase the table.
351 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
352 SharedPreferences p = PreferenceManager
353 .getDefaultSharedPreferences(context);
354 boolean fix = p.getBoolean("fix_picasa", true);
357 Editor ed = p.edit();
358 ed.putBoolean("fix_picasa", false);
362 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
363 mShowWebSuggestionsSettingChangeObserver
364 = new ShowWebSuggestionsSettingChangeObserver();
365 context.getContentResolver().registerContentObserver(
366 Settings.System.getUriFor(
367 Settings.System.SHOW_WEB_SUGGESTIONS),
368 true, mShowWebSuggestionsSettingChangeObserver);
369 updateShowWebSuggestions();
374 * This Observer will ensure that if the user changes the system
375 * setting of whether to display web suggestions, we will
376 * change accordingly.
378 /* package */ class ShowWebSuggestionsSettingChangeObserver
379 extends ContentObserver {
380 public ShowWebSuggestionsSettingChangeObserver() {
381 super(new Handler());
385 public void onChange(boolean selfChange) {
386 updateShowWebSuggestions();
390 private ShowWebSuggestionsSettingChangeObserver
391 mShowWebSuggestionsSettingChangeObserver;
393 // If non-null, then the system is set to show web suggestions,
394 // and this is the SearchableInfo to use to get them.
395 private SearchableInfo mSearchableInfo;
398 * Check the system settings to see whether web suggestions are
399 * allowed. If so, store the SearchableInfo to grab suggestions
400 * while the user is typing.
402 private void updateShowWebSuggestions() {
403 mSearchableInfo = null;
404 Context context = getContext();
405 if (Settings.System.getInt(context.getContentResolver(),
406 Settings.System.SHOW_WEB_SUGGESTIONS,
407 1 /* default on */) == 1) {
408 ComponentName webSearchComponent = mSearchManager.getWebSearchActivity();
409 if (webSearchComponent != null) {
410 mSearchableInfo = mSearchManager.getSearchableInfo(webSearchComponent);
415 private void fixPicasaBookmark() {
416 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
417 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
418 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
420 if (!cursor.moveToFirst()) {
421 // set "created" so that it will be on the top of the list
422 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
423 "date, created, bookmark)" + " VALUES('" +
424 getContext().getString(R.string.picasa) + "', '"
425 + PICASA_URL + "', 0, 0, " + new Date().getTime()
429 if (cursor != null) {
436 * Subclass AbstractCursor so we can combine multiple Cursors and add
438 * Here are the rules.
439 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
441 * 2. If bookmark/history entries are less than
442 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
444 private class MySuggestionCursor extends AbstractCursor {
445 private Cursor mHistoryCursor;
446 private Cursor mSuggestCursor;
447 private int mHistoryCount;
448 private int mSuggestionCount;
449 private boolean mIncludeWebSearch;
450 private String mString;
451 private int mSuggestText1Id;
452 private int mSuggestText2Id;
453 private int mSuggestQueryId;
454 private int mSuggestIntentExtraDataId;
456 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
459 mHistoryCount = hc.getCount();
460 mSuggestionCount = sc != null ? sc.getCount() : 0;
461 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
462 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
465 mIncludeWebSearch = string.length() > 0;
467 // Some web suggest providers only give suggestions and have no description string for
468 // items. The order of the result columns may be different as well. So retrieve the
469 // column indices for the fields we need now and check before using below.
470 if (mSuggestCursor == null) {
471 mSuggestText1Id = -1;
472 mSuggestText2Id = -1;
473 mSuggestQueryId = -1;
474 mSuggestIntentExtraDataId = -1;
476 mSuggestText1Id = mSuggestCursor.getColumnIndex(
477 SearchManager.SUGGEST_COLUMN_TEXT_1);
478 mSuggestText2Id = mSuggestCursor.getColumnIndex(
479 SearchManager.SUGGEST_COLUMN_TEXT_2);
480 mSuggestQueryId = mSuggestCursor.getColumnIndex(
481 SearchManager.SUGGEST_COLUMN_QUERY);
482 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
483 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
488 public boolean onMove(int oldPosition, int newPosition) {
489 if (mHistoryCursor == null) {
492 if (mIncludeWebSearch) {
493 if (newPosition == 0) {
499 if (mHistoryCount > newPosition) {
500 mHistoryCursor.moveToPosition(newPosition);
502 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
508 public int getCount() {
509 if (mIncludeWebSearch) {
510 return mHistoryCount + mSuggestionCount + 1;
512 return mHistoryCount + mSuggestionCount;
517 public String[] getColumnNames() {
522 public String getString(int columnIndex) {
523 if ((mPos != -1 && mHistoryCursor != null)) {
524 int position = mIncludeWebSearch ? mPos - 1 : mPos;
525 switch(columnIndex) {
526 case SUGGEST_COLUMN_INTENT_ACTION_ID:
527 if (position >= 0 && position < mHistoryCount) {
528 return Intent.ACTION_VIEW;
530 return Intent.ACTION_SEARCH;
533 case SUGGEST_COLUMN_INTENT_DATA_ID:
534 if (position >= 0 && position < mHistoryCount) {
535 return mHistoryCursor.getString(1);
540 case SUGGEST_COLUMN_TEXT_1_ID:
543 } else if (mHistoryCount > position) {
544 return getHistoryTitle();
546 if (mSuggestText1Id == -1) return null;
547 return mSuggestCursor.getString(mSuggestText1Id);
550 case SUGGEST_COLUMN_TEXT_2_ID:
552 return getContext().getString(R.string.search_the_web);
553 } else if (mHistoryCount > position) {
554 return getHistorySubtitle();
556 if (mSuggestText2Id == -1) return null;
557 return mSuggestCursor.getString(mSuggestText2Id);
560 case SUGGEST_COLUMN_ICON_1_ID:
561 if (position >= 0 && position < mHistoryCount) {
562 if (mHistoryCursor.getInt(3) == 1) {
563 return Integer.valueOf(
564 R.drawable.ic_search_category_bookmark)
567 return Integer.valueOf(
568 R.drawable.ic_search_category_history)
572 return Integer.valueOf(
573 R.drawable.ic_search_category_suggest)
577 case SUGGEST_COLUMN_ICON_2_ID:
580 case SUGGEST_COLUMN_QUERY_ID:
583 } else if (mHistoryCount > position) {
584 // Return the url in the intent query column. This is ignored
585 // within the browser because our searchable is set to
586 // android:searchMode="queryRewriteFromData", but it is used by
587 // global search for query rewriting.
588 return mHistoryCursor.getString(1);
590 if (mSuggestQueryId == -1) return null;
591 return mSuggestCursor.getString(mSuggestQueryId);
594 case SUGGEST_COLUMN_FORMAT:
597 case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
600 } else if (mHistoryCount > position) {
603 if (mSuggestIntentExtraDataId == -1) return null;
604 return mSuggestCursor.getString(mSuggestIntentExtraDataId);
612 public double getDouble(int column) {
613 throw new UnsupportedOperationException();
617 public float getFloat(int column) {
618 throw new UnsupportedOperationException();
622 public int getInt(int column) {
623 throw new UnsupportedOperationException();
627 public long getLong(int column) {
628 if ((mPos != -1) && column == 0) {
629 return mPos; // use row# as the _Id
631 throw new UnsupportedOperationException();
635 public short getShort(int column) {
636 throw new UnsupportedOperationException();
640 public boolean isNull(int column) {
641 throw new UnsupportedOperationException();
644 // TODO Temporary change, finalize after jq's changes go in
645 public void deactivate() {
646 if (mHistoryCursor != null) {
647 mHistoryCursor.deactivate();
649 if (mSuggestCursor != null) {
650 mSuggestCursor.deactivate();
655 public boolean requery() {
656 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
657 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
660 // TODO Temporary change, finalize after jq's changes go in
661 public void close() {
663 if (mHistoryCursor != null) {
664 mHistoryCursor.close();
665 mHistoryCursor = null;
667 if (mSuggestCursor != null) {
668 mSuggestCursor.close();
669 mSuggestCursor = null;
674 * Provides the title (text line 1) for a browser suggestion, which should be the
675 * webpage title. If the webpage title is empty, returns the stripped url instead.
677 * @return the title string to use
679 private String getHistoryTitle() {
680 String title = mHistoryCursor.getString(2 /* webpage title */);
681 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
682 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
688 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
689 * webpage url. If the webpage title is empty, then the url should go in the title
690 * instead, and the subtitle should be empty, so this would return null.
692 * @return the subtitle string to use, or null if none
694 private String getHistorySubtitle() {
695 String title = mHistoryCursor.getString(2 /* webpage title */);
696 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
699 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
704 * Strips "http://" from the beginning of a url and "/" from the end,
705 * and adds html formatting to make it green.
707 private String beautifyUrl(String url) {
708 if (mSearchUrlColorId == null) {
709 // Get the color used for this purpose from the current theme.
710 TypedValue colorValue = new TypedValue();
711 getContext().getTheme().resolveAttribute(
712 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
713 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
716 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
720 private static class ResultsCursor extends AbstractCursor {
721 // Array indices for RESULTS_COLUMNS
722 private static final int RESULT_ACTION_ID = 1;
723 private static final int RESULT_DATA_ID = 2;
724 private static final int RESULT_TEXT_ID = 3;
725 private static final int RESULT_ICON_ID = 4;
726 private static final int RESULT_EXTRA_ID = 5;
728 private static final String[] RESULTS_COLUMNS = new String[] {
730 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
731 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
732 SearchManager.SUGGEST_COLUMN_TEXT_1,
733 SearchManager.SUGGEST_COLUMN_ICON_1,
734 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA
736 private final ArrayList<String> mResults;
737 public ResultsCursor(ArrayList<String> results) {
740 public int getCount() { return mResults.size(); }
742 public String[] getColumnNames() {
743 return RESULTS_COLUMNS;
746 public String getString(int column) {
748 case RESULT_ACTION_ID:
749 return RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS;
751 // The data is used when the phone is in landscape mode. We
752 // still want to show the result string.
754 return mResults.get(mPos);
755 case RESULT_EXTRA_ID:
756 // The Intent's extra data will store the index into
757 // mResults so the BrowserActivity will know which result to
759 return Integer.toString(mPos);
761 return Integer.valueOf(R.drawable.magnifying_glass)
767 public short getShort(int column) {
768 throw new UnsupportedOperationException();
770 public int getInt(int column) {
771 throw new UnsupportedOperationException();
773 public long getLong(int column) {
774 if ((mPos != -1) && column == 0) {
775 return mPos; // use row# as the _id
777 throw new UnsupportedOperationException();
779 public float getFloat(int column) {
780 throw new UnsupportedOperationException();
782 public double getDouble(int column) {
783 throw new UnsupportedOperationException();
785 public boolean isNull(int column) {
786 throw new UnsupportedOperationException();
790 private ResultsCursor mResultsCursor;
793 * Provide a set of results to be returned to query, intended to be used
794 * by the SearchDialog when the BrowserActivity is in voice search mode.
795 * @param results Strings to display in the dropdown from the SearchDialog
797 /* package */ void setQueryResults(ArrayList<String> results) {
798 if (results == null) {
799 mResultsCursor = null;
801 mResultsCursor = new ResultsCursor(results);
806 public Cursor query(Uri url, String[] projectionIn, String selection,
807 String[] selectionArgs, String sortOrder)
808 throws IllegalStateException {
809 int match = URI_MATCHER.match(url);
811 throw new IllegalArgumentException("Unknown URL");
813 if (match == URI_MATCH_GEOLOCATION) {
814 throw new UnsupportedOperationException("query() not supported for geolocation");
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;
916 case URI_MATCH_GEOLOCATION:
917 return "vnd.android.cursor.dir/geolocation";
920 throw new IllegalArgumentException("Unknown URL");
925 public Uri insert(Uri url, ContentValues initialValues) {
926 boolean isBookmarkTable = false;
927 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
929 int match = URI_MATCHER.match(url);
932 case URI_MATCH_BOOKMARKS: {
933 // Insert into the bookmarks table
934 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
937 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
940 isBookmarkTable = true;
944 case URI_MATCH_SEARCHES: {
945 // Insert into the searches table
946 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
949 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
955 case URI_MATCH_GEOLOCATION:
956 String origin = initialValues.getAsString(Browser.GeolocationColumns.ORIGIN);
957 if (TextUtils.isEmpty(origin)) {
958 throw new IllegalArgumentException("Empty origin");
960 GeolocationPermissions.getInstance().allow(origin);
961 // TODO: Should we have one URI per permission?
962 uri = Browser.GEOLOCATION_URI;
966 throw new IllegalArgumentException("Unknown URL");
970 throw new IllegalArgumentException("Unknown URL");
972 getContext().getContentResolver().notifyChange(uri, null);
974 // Back up the new bookmark set if we just inserted one.
975 // A row created when bookmarks are added from scratch will have
976 // bookmark=1 in the initial value set.
978 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
979 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
980 mBackupManager.dataChanged();
986 public int delete(Uri url, String where, String[] whereArgs) {
987 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
989 int match = URI_MATCHER.match(url);
990 if (match == -1 || match == URI_MATCH_SUGGEST) {
991 throw new IllegalArgumentException("Unknown URL");
994 if (match == URI_MATCH_GEOLOCATION) {
995 return deleteGeolocation(url, where, whereArgs);
998 // need to know whether it's the bookmarks table for a couple of reasons
999 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
1002 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
1003 StringBuilder sb = new StringBuilder();
1004 if (where != null && where.length() > 0) {
1007 sb.append(" ) AND ");
1009 id = url.getPathSegments().get(1);
1010 sb.append("_id = ");
1012 where = sb.toString();
1015 ContentResolver cr = getContext().getContentResolver();
1017 // we'lll need to back up the bookmark set if we are about to delete one
1018 if (isBookmarkTable) {
1019 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
1020 new String[] { BookmarkColumns.BOOKMARK },
1021 "_id = " + id, null, null);
1022 if (cursor.moveToNext()) {
1023 if (cursor.getInt(0) != 0) {
1024 // yep, this record is a bookmark
1025 mBackupManager.dataChanged();
1031 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
1032 cr.notifyChange(url, null);
1036 private int deleteGeolocation(Uri uri, String where, String[] whereArgs) {
1037 if (whereArgs.length != 1) {
1038 throw new IllegalArgumentException("Bad where arguments");
1040 String origin = whereArgs[0];
1041 if (TextUtils.isEmpty(origin)) {
1042 throw new IllegalArgumentException("Empty origin");
1044 GeolocationPermissions.getInstance().clear(origin);
1045 getContext().getContentResolver().notifyChange(Browser.GEOLOCATION_URI, null);
1046 return 1; // We always return 1, to avoid having to check whether anything was actually removed
1050 public int update(Uri url, ContentValues values, String where,
1051 String[] whereArgs) {
1052 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1054 int match = URI_MATCHER.match(url);
1055 if (match == -1 || match == URI_MATCH_SUGGEST) {
1056 throw new IllegalArgumentException("Unknown URL");
1060 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
1061 boolean changingBookmarks = false;
1063 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
1064 StringBuilder sb = new StringBuilder();
1065 if (where != null && where.length() > 0) {
1068 sb.append(" ) AND ");
1070 id = url.getPathSegments().get(1);
1071 sb.append("_id = ");
1073 where = sb.toString();
1076 ContentResolver cr = getContext().getContentResolver();
1078 // Not all bookmark-table updates should be backed up. Look to see
1079 // whether we changed the title, url, or "is a bookmark" state, and
1080 // request a backup if so.
1081 if (isBookmarkTable) {
1082 // Alterations to the bookmark field inherently change the bookmark
1083 // set, so we don't need to query the record; we know a priori that
1084 // we will need to back up this change.
1085 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
1086 changingBookmarks = true;
1088 // changing the title or URL of a bookmark record requires a backup,
1089 // but we don't know wether such an update is on a bookmark without
1090 // querying the record
1091 if (!changingBookmarks &&
1092 (values.containsKey(BookmarkColumns.TITLE)
1093 || values.containsKey(BookmarkColumns.URL))) {
1094 // when isBookmarkTable is true, the 'id' var was assigned above
1095 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
1096 new String[] { BookmarkColumns.BOOKMARK },
1097 "_id = " + id, null, null);
1098 if (cursor.moveToNext()) {
1099 changingBookmarks = (cursor.getInt(0) != 0);
1104 // if this *is* a bookmark row we're altering, we need to back it up.
1105 if (changingBookmarks) {
1106 mBackupManager.dataChanged();
1110 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
1111 cr.notifyChange(url, null);
1116 * Strips the provided url of preceding "http://" and any trailing "/". Does not
1117 * strip "https://". If the provided string cannot be stripped, the original string
1120 * TODO: Put this in TextUtils to be used by other packages doing something similar.
1122 * @param url a url to strip, like "http://www.google.com/"
1123 * @return a stripped url like "www.google.com", or the original string if it could
1126 private static String stripUrl(String url) {
1127 if (url == null) return null;
1128 Matcher m = STRIP_URL_PATTERN.matcher(url);
1129 if (m.matches() && m.groupCount() == 3) {