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 com.google.android.providers.GoogleSettings.Partner;
21 import android.app.SearchManager;
22 import android.backup.BackupManager;
23 import android.content.ComponentName;
24 import android.content.ContentProvider;
25 import android.content.ContentResolver;
26 import android.content.ContentUris;
27 import android.content.ContentValues;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.SharedPreferences;
31 import android.content.UriMatcher;
32 import android.content.SharedPreferences.Editor;
33 import android.content.pm.PackageManager;
34 import android.content.pm.ResolveInfo;
35 import android.database.AbstractCursor;
36 import android.database.ContentObserver;
37 import android.database.Cursor;
38 import android.database.sqlite.SQLiteDatabase;
39 import android.database.sqlite.SQLiteOpenHelper;
40 import android.net.Uri;
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.server.search.SearchableInfo;
47 import android.text.TextUtils;
48 import android.text.util.Regex;
49 import android.util.Log;
50 import android.util.TypedValue;
52 import java.util.Date;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
57 public class BrowserProvider extends ContentProvider {
59 private SQLiteOpenHelper mOpenHelper;
60 private BackupManager mBackupManager;
61 private static final String sDatabaseName = "browser.db";
62 private static final String TAG = "BrowserProvider";
63 private static final String ORDER_BY = "visits DESC, date DESC";
65 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
66 "viewer?source=androidclient";
68 private static final String[] TABLE_NAMES = new String[] {
69 "bookmarks", "searches"
71 private static final String[] SUGGEST_PROJECTION = new String[] {
72 "_id", "url", "title", "bookmark"
74 private static final String SUGGEST_SELECTION =
75 "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
77 private String[] SUGGEST_ARGS = new String[5];
79 // shared suggestion array index, make sure to match COLUMNS
80 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
81 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
82 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
83 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
84 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
85 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
86 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
87 private static final int SUGGEST_COLUMN_FORMAT = 8;
89 // shared suggestion columns
90 private static final String[] COLUMNS = new String[] {
92 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
93 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
94 SearchManager.SUGGEST_COLUMN_TEXT_1,
95 SearchManager.SUGGEST_COLUMN_TEXT_2,
96 SearchManager.SUGGEST_COLUMN_ICON_1,
97 SearchManager.SUGGEST_COLUMN_ICON_2,
98 SearchManager.SUGGEST_COLUMN_QUERY,
99 SearchManager.SUGGEST_COLUMN_FORMAT};
101 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
102 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
103 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
104 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
106 // make sure that these match the index of TABLE_NAMES
107 private static final int URI_MATCH_BOOKMARKS = 0;
108 private static final int URI_MATCH_SEARCHES = 1;
109 // (id % 10) should match the table name index
110 private static final int URI_MATCH_BOOKMARKS_ID = 10;
111 private static final int URI_MATCH_SEARCHES_ID = 11;
113 private static final int URI_MATCH_SUGGEST = 20;
114 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
116 private static final UriMatcher URI_MATCHER;
119 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
120 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
121 URI_MATCH_BOOKMARKS);
122 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
123 URI_MATCH_BOOKMARKS_ID);
124 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
126 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
127 URI_MATCH_SEARCHES_ID);
128 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
130 URI_MATCHER.addURI("browser",
131 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
132 URI_MATCH_BOOKMARKS_SUGGEST);
135 // 1 -> 2 add cache table
136 // 2 -> 3 update history table
137 // 3 -> 4 add passwords table
138 // 4 -> 5 add settings table
141 // 7 -> 8 drop proxy table
142 // 8 -> 9 drop settings table
143 // 9 -> 10 add form_urls and form_data
144 // 10 -> 11 add searches table
145 // 11 -> 12 modify cache table
146 // 12 -> 13 modify cache table
147 // 13 -> 14 correspond with Google Bookmarks schema
148 // 14 -> 15 move couple of tables to either browser private database or webview database
149 // 15 -> 17 Set it up for the SearchManager
150 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
151 // 18 -> 19 Remove labels table
152 // 19 -> 20 Added thumbnail
153 // 20 -> 21 Added touch_icon
154 private static final int DATABASE_VERSION = 21;
156 // Regular expression which matches http://, followed by some stuff, followed by
157 // optionally a trailing slash, all matched as separate groups.
158 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
160 private SearchManager mSearchManager;
162 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
163 // the current theme. This is not set until/unless beautifyUrl is called, at which point
164 // this variable caches the color value.
165 private static String mSearchUrlColorId;
167 public BrowserProvider() {
171 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
172 StringBuffer sb = new StringBuffer();
175 final String client_id = Partner.getString(context.getContentResolver(),
176 Partner.CLIENT_ID, "android-google");
178 for (int i = 0; i < srcString.length(); ++i) {
179 char c = srcString.charAt(i);
181 sb.append(srcString.subSequence(lastCharLoc, i));
184 for (int j = i; j < srcString.length(); ++j) {
185 char k = srcString.charAt(j);
187 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
188 if (propertyKeyValue.equals("CLIENT_ID")) {
189 sb.append(client_id);
191 sb.append("unknown");
200 if (srcString.length() - lastCharLoc > 0) {
201 // Put on the tail, if there is one
202 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
207 private static class DatabaseHelper extends SQLiteOpenHelper {
208 private Context mContext;
210 public DatabaseHelper(Context context) {
211 super(context, sDatabaseName, null, DATABASE_VERSION);
216 public void onCreate(SQLiteDatabase db) {
217 db.execSQL("CREATE TABLE bookmarks (" +
218 "_id INTEGER PRIMARY KEY," +
224 "description TEXT," +
225 "bookmark INTEGER," +
226 "favicon BLOB DEFAULT NULL," +
227 "thumbnail BLOB DEFAULT NULL," +
228 "touch_icon BLOB DEFAULT NULL" +
231 final CharSequence[] bookmarks = mContext.getResources()
232 .getTextArray(R.array.bookmarks);
233 int size = bookmarks.length;
235 for (int i = 0; i < size; i = i + 2) {
236 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
237 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
238 "date, created, bookmark)" + " VALUES('" +
239 bookmarks[i] + "', '" + bookmarkDestination +
242 } catch (ArrayIndexOutOfBoundsException e) {
245 db.execSQL("CREATE TABLE searches (" +
246 "_id INTEGER PRIMARY KEY," +
253 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
254 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
256 if (oldVersion == 18) {
257 db.execSQL("DROP TABLE IF EXISTS labels");
259 if (oldVersion <= 19) {
260 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
262 if (oldVersion < 21) {
263 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
265 db.execSQL("DROP TABLE IF EXISTS bookmarks");
266 db.execSQL("DROP TABLE IF EXISTS searches");
273 public boolean onCreate() {
274 final Context context = getContext();
275 mOpenHelper = new DatabaseHelper(context);
276 mBackupManager = new BackupManager(context);
277 // we added "picasa web album" into default bookmarks for version 19.
278 // To avoid erasing the bookmark table, we added it explicitly for
279 // version 18 and 19 as in the other cases, we will erase the table.
280 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
281 SharedPreferences p = PreferenceManager
282 .getDefaultSharedPreferences(context);
283 boolean fix = p.getBoolean("fix_picasa", true);
286 Editor ed = p.edit();
287 ed.putBoolean("fix_picasa", false);
291 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
292 mShowWebSuggestionsSettingChangeObserver
293 = new ShowWebSuggestionsSettingChangeObserver();
294 context.getContentResolver().registerContentObserver(
295 Settings.System.getUriFor(
296 Settings.System.SHOW_WEB_SUGGESTIONS),
297 true, mShowWebSuggestionsSettingChangeObserver);
298 updateShowWebSuggestions();
303 * This Observer will ensure that if the user changes the system
304 * setting of whether to display web suggestions, we will
305 * change accordingly.
307 /* package */ class ShowWebSuggestionsSettingChangeObserver
308 extends ContentObserver {
309 public ShowWebSuggestionsSettingChangeObserver() {
310 super(new Handler());
314 public void onChange(boolean selfChange) {
315 updateShowWebSuggestions();
319 private ShowWebSuggestionsSettingChangeObserver
320 mShowWebSuggestionsSettingChangeObserver;
322 // If non-null, then the system is set to show web suggestions,
323 // and this is the SearchableInfo to use to get them.
324 private SearchableInfo mSearchableInfo;
327 * Check the system settings to see whether web suggestions are
328 * allowed. If so, store the SearchableInfo to grab suggestions
329 * while the user is typing.
331 private void updateShowWebSuggestions() {
332 mSearchableInfo = null;
333 Context context = getContext();
334 if (Settings.System.getInt(context.getContentResolver(),
335 Settings.System.SHOW_WEB_SUGGESTIONS,
336 1 /* default on */) == 1) {
337 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
338 intent.addCategory(Intent.CATEGORY_DEFAULT);
339 ResolveInfo info = context.getPackageManager().resolveActivity(
340 intent, PackageManager.MATCH_DEFAULT_ONLY);
342 ComponentName googleSearchComponent =
343 new ComponentName(info.activityInfo.packageName,
344 info.activityInfo.name);
345 mSearchableInfo = mSearchManager.getSearchableInfo(
346 googleSearchComponent, false);
351 private void fixPicasaBookmark() {
352 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
353 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
354 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
356 if (!cursor.moveToFirst()) {
357 // set "created" so that it will be on the top of the list
358 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
359 "date, created, bookmark)" + " VALUES('" +
360 getContext().getString(R.string.picasa) + "', '"
361 + PICASA_URL + "', 0, 0, " + new Date().getTime()
365 if (cursor != null) {
372 * Subclass AbstractCursor so we can combine multiple Cursors and add
374 * Here are the rules.
375 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
377 * 2. If bookmark/history entries are less than
378 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
380 private class MySuggestionCursor extends AbstractCursor {
381 private Cursor mHistoryCursor;
382 private Cursor mSuggestCursor;
383 private int mHistoryCount;
384 private int mSuggestionCount;
385 private boolean mBeyondCursor;
386 private String mString;
387 private int mSuggestText1Id;
388 private int mSuggestText2Id;
389 private int mSuggestQueryId;
391 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
394 mHistoryCount = hc.getCount();
395 mSuggestionCount = sc != null ? sc.getCount() : 0;
396 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
397 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
400 mBeyondCursor = false;
402 // Some web suggest providers only give suggestions and have no description string for
403 // items. The order of the result columns may be different as well. So retrieve the
404 // column indices for the fields we need now and check before using below.
405 if (mSuggestCursor == null) {
406 mSuggestText1Id = -1;
407 mSuggestText2Id = -1;
408 mSuggestQueryId = -1;
410 mSuggestText1Id = mSuggestCursor.getColumnIndex(
411 SearchManager.SUGGEST_COLUMN_TEXT_1);
412 mSuggestText2Id = mSuggestCursor.getColumnIndex(
413 SearchManager.SUGGEST_COLUMN_TEXT_2);
414 mSuggestQueryId = mSuggestCursor.getColumnIndex(
415 SearchManager.SUGGEST_COLUMN_QUERY);
420 public boolean onMove(int oldPosition, int newPosition) {
421 if (mHistoryCursor == null) {
424 if (mHistoryCount > newPosition) {
425 mHistoryCursor.moveToPosition(newPosition);
426 mBeyondCursor = false;
427 } else if (mHistoryCount + mSuggestionCount > newPosition) {
428 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
429 mBeyondCursor = false;
431 mBeyondCursor = true;
437 public int getCount() {
438 if (mString.length() > 0) {
439 return mHistoryCount + mSuggestionCount + 1;
441 return mHistoryCount + mSuggestionCount;
446 public String[] getColumnNames() {
451 public String getString(int columnIndex) {
452 if ((mPos != -1 && mHistoryCursor != null)) {
453 switch(columnIndex) {
454 case SUGGEST_COLUMN_INTENT_ACTION_ID:
455 if (mHistoryCount > mPos) {
456 return Intent.ACTION_VIEW;
458 return Intent.ACTION_SEARCH;
461 case SUGGEST_COLUMN_INTENT_DATA_ID:
462 if (mHistoryCount > mPos) {
463 return mHistoryCursor.getString(1);
468 case SUGGEST_COLUMN_TEXT_1_ID:
469 if (mHistoryCount > mPos) {
470 return getHistoryTitle();
471 } else if (!mBeyondCursor) {
472 if (mSuggestText1Id == -1) return null;
473 return mSuggestCursor.getString(mSuggestText1Id);
478 case SUGGEST_COLUMN_TEXT_2_ID:
479 if (mHistoryCount > mPos) {
480 return getHistorySubtitle();
481 } else if (!mBeyondCursor) {
482 if (mSuggestText2Id == -1) return null;
483 return mSuggestCursor.getString(mSuggestText2Id);
485 return getContext().getString(R.string.search_the_web);
488 case SUGGEST_COLUMN_ICON_1_ID:
489 if (mHistoryCount > mPos) {
490 if (mHistoryCursor.getInt(3) == 1) {
491 return Integer.valueOf(
492 R.drawable.ic_search_category_bookmark)
495 return Integer.valueOf(
496 R.drawable.ic_search_category_history)
500 return Integer.valueOf(
501 R.drawable.ic_search_category_suggest)
505 case SUGGEST_COLUMN_ICON_2_ID:
508 case SUGGEST_COLUMN_QUERY_ID:
509 if (mHistoryCount > mPos) {
510 // Return the url in the intent query column. This is ignored
511 // within the browser because our searchable is set to
512 // android:searchMode="queryRewriteFromData", but it is used by
513 // global search for query rewriting.
514 return mHistoryCursor.getString(1);
515 } else if (!mBeyondCursor) {
516 if (mSuggestQueryId == -1) return null;
517 return mSuggestCursor.getString(mSuggestQueryId);
522 case SUGGEST_COLUMN_FORMAT:
530 public double getDouble(int column) {
531 throw new UnsupportedOperationException();
535 public float getFloat(int column) {
536 throw new UnsupportedOperationException();
540 public int getInt(int column) {
541 throw new UnsupportedOperationException();
545 public long getLong(int column) {
546 if ((mPos != -1) && column == 0) {
547 return mPos; // use row# as the _Id
549 throw new UnsupportedOperationException();
553 public short getShort(int column) {
554 throw new UnsupportedOperationException();
558 public boolean isNull(int column) {
559 throw new UnsupportedOperationException();
562 // TODO Temporary change, finalize after jq's changes go in
563 public void deactivate() {
564 if (mHistoryCursor != null) {
565 mHistoryCursor.deactivate();
567 if (mSuggestCursor != null) {
568 mSuggestCursor.deactivate();
573 public boolean requery() {
574 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
575 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
578 // TODO Temporary change, finalize after jq's changes go in
579 public void close() {
581 if (mHistoryCursor != null) {
582 mHistoryCursor.close();
583 mHistoryCursor = null;
585 if (mSuggestCursor != null) {
586 mSuggestCursor.close();
587 mSuggestCursor = null;
592 * Provides the title (text line 1) for a browser suggestion, which should be the
593 * webpage title. If the webpage title is empty, returns the stripped url instead.
595 * @return the title string to use
597 private String getHistoryTitle() {
598 String title = mHistoryCursor.getString(2 /* webpage title */);
599 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
600 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
606 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
607 * webpage url. If the webpage title is empty, then the url should go in the title
608 * instead, and the subtitle should be empty, so this would return null.
610 * @return the subtitle string to use, or null if none
612 private String getHistorySubtitle() {
613 String title = mHistoryCursor.getString(2 /* webpage title */);
614 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
617 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
622 * Strips "http://" from the beginning of a url and "/" from the end,
623 * and adds html formatting to make it green.
625 private String beautifyUrl(String url) {
626 if (mSearchUrlColorId == null) {
627 // Get the color used for this purpose from the current theme.
628 TypedValue colorValue = new TypedValue();
629 getContext().getTheme().resolveAttribute(
630 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
631 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
634 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
639 public Cursor query(Uri url, String[] projectionIn, String selection,
640 String[] selectionArgs, String sortOrder)
641 throws IllegalStateException {
642 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
644 int match = URI_MATCHER.match(url);
646 throw new IllegalArgumentException("Unknown URL");
649 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
650 String suggestSelection;
652 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
653 suggestSelection = null;
656 String like = selectionArgs[0] + "%";
657 if (selectionArgs[0].startsWith("http")
658 || selectionArgs[0].startsWith("file")) {
659 myArgs = new String[1];
661 suggestSelection = selection;
663 SUGGEST_ARGS[0] = "http://" + like;
664 SUGGEST_ARGS[1] = "http://www." + like;
665 SUGGEST_ARGS[2] = "https://" + like;
666 SUGGEST_ARGS[3] = "https://www." + like;
667 // To match against titles.
668 SUGGEST_ARGS[4] = like;
669 myArgs = SUGGEST_ARGS;
670 suggestSelection = SUGGEST_SELECTION;
674 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
675 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
676 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
678 if (match == URI_MATCH_BOOKMARKS_SUGGEST
679 || Regex.WEB_URL_PATTERN.matcher(selectionArgs[0]).matches()) {
680 return new MySuggestionCursor(c, null, "");
682 // get Google suggest if there is still space in the list
683 if (myArgs != null && myArgs.length > 1
684 && mSearchableInfo != null
685 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
686 Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
687 return new MySuggestionCursor(c, sc, selectionArgs[0]);
689 return new MySuggestionCursor(c, null, selectionArgs[0]);
693 String[] projection = null;
694 if (projectionIn != null && projectionIn.length > 0) {
695 projection = new String[projectionIn.length + 1];
696 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
697 projection[projectionIn.length] = "_id AS _id";
700 StringBuilder whereClause = new StringBuilder(256);
701 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
702 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
706 // Tack on the user's selection, if present
707 if (selection != null && selection.length() > 0) {
708 if (whereClause.length() > 0) {
709 whereClause.append(" AND ");
712 whereClause.append('(');
713 whereClause.append(selection);
714 whereClause.append(')');
716 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
717 whereClause.toString(), selectionArgs, null, null, sortOrder,
719 c.setNotificationUri(getContext().getContentResolver(), url);
724 public String getType(Uri url) {
725 int match = URI_MATCHER.match(url);
727 case URI_MATCH_BOOKMARKS:
728 return "vnd.android.cursor.dir/bookmark";
730 case URI_MATCH_BOOKMARKS_ID:
731 return "vnd.android.cursor.item/bookmark";
733 case URI_MATCH_SEARCHES:
734 return "vnd.android.cursor.dir/searches";
736 case URI_MATCH_SEARCHES_ID:
737 return "vnd.android.cursor.item/searches";
739 case URI_MATCH_SUGGEST:
740 return SearchManager.SUGGEST_MIME_TYPE;
743 throw new IllegalArgumentException("Unknown URL");
748 public Uri insert(Uri url, ContentValues initialValues) {
749 boolean isBookmarkTable = false;
750 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
752 int match = URI_MATCHER.match(url);
755 case URI_MATCH_BOOKMARKS: {
756 // Insert into the bookmarks table
757 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
760 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
763 isBookmarkTable = true;
767 case URI_MATCH_SEARCHES: {
768 // Insert into the searches table
769 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
772 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
779 throw new IllegalArgumentException("Unknown URL");
783 throw new IllegalArgumentException("Unknown URL");
785 getContext().getContentResolver().notifyChange(uri, null);
787 // Back up the new bookmark set if we just inserted one.
788 // A row created when bookmarks are added from scratch will have
789 // bookmark=1 in the initial value set.
791 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
792 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
793 mBackupManager.dataChanged();
799 public int delete(Uri url, String where, String[] whereArgs) {
800 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
802 int match = URI_MATCHER.match(url);
803 if (match == -1 || match == URI_MATCH_SUGGEST) {
804 throw new IllegalArgumentException("Unknown URL");
807 // need to know whether it's the bookmarks table for a couple of reasons
808 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
811 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
812 StringBuilder sb = new StringBuilder();
813 if (where != null && where.length() > 0) {
816 sb.append(" ) AND ");
818 id = url.getPathSegments().get(1);
821 where = sb.toString();
824 ContentResolver cr = getContext().getContentResolver();
826 // we'lll need to back up the bookmark set if we are about to delete one
827 if (isBookmarkTable) {
828 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
829 new String[] { BookmarkColumns.BOOKMARK },
830 "_id = " + id, null, null);
831 if (cursor.moveToNext()) {
832 if (cursor.getInt(0) != 0) {
833 // yep, this record is a bookmark
834 mBackupManager.dataChanged();
840 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
841 cr.notifyChange(url, null);
846 public int update(Uri url, ContentValues values, String where,
847 String[] whereArgs) {
848 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
850 int match = URI_MATCHER.match(url);
851 if (match == -1 || match == URI_MATCH_SUGGEST) {
852 throw new IllegalArgumentException("Unknown URL");
856 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
857 boolean changingBookmarks = false;
859 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
860 StringBuilder sb = new StringBuilder();
861 if (where != null && where.length() > 0) {
864 sb.append(" ) AND ");
866 id = url.getPathSegments().get(1);
869 where = sb.toString();
872 ContentResolver cr = getContext().getContentResolver();
874 // Not all bookmark-table updates should be backed up. Look to see
875 // whether we changed the title, url, or "is a bookmark" state, and
876 // request a backup if so.
877 if (isBookmarkTable) {
878 // Alterations to the bookmark field inherently change the bookmark
879 // set, so we don't need to query the record; we know a priori that
880 // we will need to back up this change.
881 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
882 changingBookmarks = true;
884 // changing the title or URL of a bookmark record requires a backup,
885 // but we don't know wether such an update is on a bookmark without
886 // querying the record
887 if (!changingBookmarks &&
888 (values.containsKey(BookmarkColumns.TITLE)
889 || values.containsKey(BookmarkColumns.URL))) {
890 // when isBookmarkTable is true, the 'id' var was assigned above
891 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
892 new String[] { BookmarkColumns.BOOKMARK },
893 "_id = " + id, null, null);
894 if (cursor.moveToNext()) {
895 changingBookmarks = (cursor.getInt(0) != 0);
900 // if this *is* a bookmark row we're altering, we need to back it up.
901 if (changingBookmarks) {
902 mBackupManager.dataChanged();
906 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
907 cr.notifyChange(url, null);
912 * Strips the provided url of preceding "http://" and any trailing "/". Does not
913 * strip "https://". If the provided string cannot be stripped, the original string
916 * TODO: Put this in TextUtils to be used by other packages doing something similar.
918 * @param url a url to strip, like "http://www.google.com/"
919 * @return a stripped url like "www.google.com", or the original string if it could
922 private static String stripUrl(String url) {
923 if (url == null) return null;
924 Matcher m = STRIP_URL_PATTERN.matcher(url);
925 if (m.matches() && m.groupCount() == 3) {