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.backup.BackupManager;
21 import android.content.ComponentName;
22 import android.content.ContentProvider;
23 import android.content.ContentResolver;
24 import android.content.ContentUris;
25 import android.content.ContentValues;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.content.UriMatcher;
30 import android.content.SharedPreferences.Editor;
31 import android.content.pm.PackageManager;
32 import android.content.pm.ResolveInfo;
33 import android.database.AbstractCursor;
34 import android.database.ContentObserver;
35 import android.database.Cursor;
36 import android.database.sqlite.SQLiteDatabase;
37 import android.database.sqlite.SQLiteOpenHelper;
38 import android.net.Uri;
39 import android.os.AsyncTask;
40 import android.os.Handler;
41 import android.preference.PreferenceManager;
42 import android.provider.Browser;
43 import android.provider.Settings;
44 import android.provider.Browser.BookmarkColumns;
45 import android.server.search.SearchableInfo;
46 import android.text.TextUtils;
47 import android.util.Log;
48 import android.util.TypedValue;
50 import com.android.common.Patterns;
52 import com.google.android.providers.GoogleSettings.Partner;
55 import java.io.FilenameFilter;
56 import java.util.Date;
57 import java.util.regex.Matcher;
58 import java.util.regex.Pattern;
61 public class BrowserProvider extends ContentProvider {
63 private SQLiteOpenHelper mOpenHelper;
64 private BackupManager mBackupManager;
65 private static final String sDatabaseName = "browser.db";
66 private static final String TAG = "BrowserProvider";
67 private static final String ORDER_BY = "visits DESC, date DESC";
69 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
70 "viewer?source=androidclient";
72 private static final String[] TABLE_NAMES = new String[] {
73 "bookmarks", "searches"
75 private static final String[] SUGGEST_PROJECTION = new String[] {
76 "_id", "url", "title", "bookmark"
78 private static final String SUGGEST_SELECTION =
79 "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
81 private String[] SUGGEST_ARGS = new String[5];
83 // shared suggestion array index, make sure to match COLUMNS
84 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
85 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
86 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
87 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
88 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
89 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
90 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
91 private static final int SUGGEST_COLUMN_FORMAT = 8;
92 private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
94 // shared suggestion columns
95 private static final String[] COLUMNS = new String[] {
97 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
98 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
99 SearchManager.SUGGEST_COLUMN_TEXT_1,
100 SearchManager.SUGGEST_COLUMN_TEXT_2,
101 SearchManager.SUGGEST_COLUMN_ICON_1,
102 SearchManager.SUGGEST_COLUMN_ICON_2,
103 SearchManager.SUGGEST_COLUMN_QUERY,
104 SearchManager.SUGGEST_COLUMN_FORMAT,
105 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
107 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
108 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
109 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
110 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
112 // make sure that these match the index of TABLE_NAMES
113 private static final int URI_MATCH_BOOKMARKS = 0;
114 private static final int URI_MATCH_SEARCHES = 1;
115 // (id % 10) should match the table name index
116 private static final int URI_MATCH_BOOKMARKS_ID = 10;
117 private static final int URI_MATCH_SEARCHES_ID = 11;
119 private static final int URI_MATCH_SUGGEST = 20;
120 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
122 private static final UriMatcher URI_MATCHER;
125 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
126 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
127 URI_MATCH_BOOKMARKS);
128 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
129 URI_MATCH_BOOKMARKS_ID);
130 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
132 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
133 URI_MATCH_SEARCHES_ID);
134 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
136 URI_MATCHER.addURI("browser",
137 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
138 URI_MATCH_BOOKMARKS_SUGGEST);
141 // 1 -> 2 add cache table
142 // 2 -> 3 update history table
143 // 3 -> 4 add passwords table
144 // 4 -> 5 add settings table
147 // 7 -> 8 drop proxy table
148 // 8 -> 9 drop settings table
149 // 9 -> 10 add form_urls and form_data
150 // 10 -> 11 add searches table
151 // 11 -> 12 modify cache table
152 // 12 -> 13 modify cache table
153 // 13 -> 14 correspond with Google Bookmarks schema
154 // 14 -> 15 move couple of tables to either browser private database or webview database
155 // 15 -> 17 Set it up for the SearchManager
156 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
157 // 18 -> 19 Remove labels table
158 // 19 -> 20 Added thumbnail
159 // 20 -> 21 Added touch_icon
160 // 21 -> 22 Remove "clientid"
161 private static final int DATABASE_VERSION = 22;
163 // Regular expression which matches http://, followed by some stuff, followed by
164 // optionally a trailing slash, all matched as separate groups.
165 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
167 private SearchManager mSearchManager;
169 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
170 // the current theme. This is not set until/unless beautifyUrl is called, at which point
171 // this variable caches the color value.
172 private static String mSearchUrlColorId;
174 public BrowserProvider() {
178 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
179 StringBuffer sb = new StringBuffer();
182 final String client_id = Partner.getString(context.getContentResolver(),
183 Partner.CLIENT_ID, "android-google");
185 for (int i = 0; i < srcString.length(); ++i) {
186 char c = srcString.charAt(i);
188 sb.append(srcString.subSequence(lastCharLoc, i));
191 for (int j = i; j < srcString.length(); ++j) {
192 char k = srcString.charAt(j);
194 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
195 if (propertyKeyValue.equals("CLIENT_ID")) {
196 sb.append(client_id);
198 sb.append("unknown");
207 if (srcString.length() - lastCharLoc > 0) {
208 // Put on the tail, if there is one
209 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
214 private static class DatabaseHelper extends SQLiteOpenHelper {
215 private Context mContext;
217 public DatabaseHelper(Context context) {
218 super(context, sDatabaseName, null, DATABASE_VERSION);
223 public void onCreate(SQLiteDatabase db) {
224 db.execSQL("CREATE TABLE bookmarks (" +
225 "_id INTEGER PRIMARY KEY," +
231 "description TEXT," +
232 "bookmark INTEGER," +
233 "favicon BLOB DEFAULT NULL," +
234 "thumbnail BLOB DEFAULT NULL," +
235 "touch_icon BLOB DEFAULT NULL" +
238 final CharSequence[] bookmarks = mContext.getResources()
239 .getTextArray(R.array.bookmarks);
240 int size = bookmarks.length;
242 for (int i = 0; i < size; i = i + 2) {
243 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
244 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
245 "date, created, bookmark)" + " VALUES('" +
246 bookmarks[i] + "', '" + bookmarkDestination +
249 } catch (ArrayIndexOutOfBoundsException e) {
252 db.execSQL("CREATE TABLE searches (" +
253 "_id INTEGER PRIMARY KEY," +
260 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
261 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
263 if (oldVersion == 18) {
264 db.execSQL("DROP TABLE IF EXISTS labels");
266 if (oldVersion <= 19) {
267 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
269 if (oldVersion < 21) {
270 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
272 if (oldVersion < 22) {
273 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
276 db.execSQL("DROP TABLE IF EXISTS bookmarks");
277 db.execSQL("DROP TABLE IF EXISTS searches");
282 private void removeGears() {
283 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
284 public Void doInBackground(Void... unused) {
285 String browserDataDirString = mContext.getApplicationInfo().dataDir;
286 final String appPluginsDirString = "app_plugins";
287 final String gearsPrefix = "gears";
288 File appPluginsDir = new File(browserDataDirString + File.separator
289 + appPluginsDirString);
290 if (!appPluginsDir.exists()) {
293 // Delete the Gears plugin files
294 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
295 public boolean accept(File dir, String filename) {
296 return filename.startsWith(gearsPrefix);
299 for (int i = 0; i < gearsFiles.length; ++i) {
300 if (gearsFiles[i].isDirectory()) {
301 deleteDirectory(gearsFiles[i]);
303 gearsFiles[i].delete();
306 // Delete the Gears data files
307 File gearsDataDir = new File(browserDataDirString + File.separator
309 if (!gearsDataDir.exists()) {
312 deleteDirectory(gearsDataDir);
316 private void deleteDirectory(File currentDir) {
317 File[] files = currentDir.listFiles();
318 for (int i = 0; i < files.length; ++i) {
319 if (files[i].isDirectory()) {
320 deleteDirectory(files[i]);
333 public boolean onCreate() {
334 final Context context = getContext();
335 mOpenHelper = new DatabaseHelper(context);
336 mBackupManager = new BackupManager(context);
337 // we added "picasa web album" into default bookmarks for version 19.
338 // To avoid erasing the bookmark table, we added it explicitly for
339 // version 18 and 19 as in the other cases, we will erase the table.
340 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
341 SharedPreferences p = PreferenceManager
342 .getDefaultSharedPreferences(context);
343 boolean fix = p.getBoolean("fix_picasa", true);
346 Editor ed = p.edit();
347 ed.putBoolean("fix_picasa", false);
351 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
352 mShowWebSuggestionsSettingChangeObserver
353 = new ShowWebSuggestionsSettingChangeObserver();
354 context.getContentResolver().registerContentObserver(
355 Settings.System.getUriFor(
356 Settings.System.SHOW_WEB_SUGGESTIONS),
357 true, mShowWebSuggestionsSettingChangeObserver);
358 updateShowWebSuggestions();
363 * This Observer will ensure that if the user changes the system
364 * setting of whether to display web suggestions, we will
365 * change accordingly.
367 /* package */ class ShowWebSuggestionsSettingChangeObserver
368 extends ContentObserver {
369 public ShowWebSuggestionsSettingChangeObserver() {
370 super(new Handler());
374 public void onChange(boolean selfChange) {
375 updateShowWebSuggestions();
379 private ShowWebSuggestionsSettingChangeObserver
380 mShowWebSuggestionsSettingChangeObserver;
382 // If non-null, then the system is set to show web suggestions,
383 // and this is the SearchableInfo to use to get them.
384 private SearchableInfo mSearchableInfo;
387 * Check the system settings to see whether web suggestions are
388 * allowed. If so, store the SearchableInfo to grab suggestions
389 * while the user is typing.
391 private void updateShowWebSuggestions() {
392 mSearchableInfo = null;
393 Context context = getContext();
394 if (Settings.System.getInt(context.getContentResolver(),
395 Settings.System.SHOW_WEB_SUGGESTIONS,
396 1 /* default on */) == 1) {
397 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
398 intent.addCategory(Intent.CATEGORY_DEFAULT);
399 ResolveInfo info = context.getPackageManager().resolveActivity(
400 intent, PackageManager.MATCH_DEFAULT_ONLY);
402 ComponentName googleSearchComponent =
403 new ComponentName(info.activityInfo.packageName,
404 info.activityInfo.name);
405 mSearchableInfo = mSearchManager.getSearchableInfo(
406 googleSearchComponent, false);
411 private void fixPicasaBookmark() {
412 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
413 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
414 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
416 if (!cursor.moveToFirst()) {
417 // set "created" so that it will be on the top of the list
418 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
419 "date, created, bookmark)" + " VALUES('" +
420 getContext().getString(R.string.picasa) + "', '"
421 + PICASA_URL + "', 0, 0, " + new Date().getTime()
425 if (cursor != null) {
432 * Subclass AbstractCursor so we can combine multiple Cursors and add
434 * Here are the rules.
435 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
437 * 2. If bookmark/history entries are less than
438 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
440 private class MySuggestionCursor extends AbstractCursor {
441 private Cursor mHistoryCursor;
442 private Cursor mSuggestCursor;
443 private int mHistoryCount;
444 private int mSuggestionCount;
445 private boolean mBeyondCursor;
446 private String mString;
447 private int mSuggestText1Id;
448 private int mSuggestText2Id;
449 private int mSuggestQueryId;
450 private int mSuggestIntentExtraDataId;
452 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
455 mHistoryCount = hc.getCount();
456 mSuggestionCount = sc != null ? sc.getCount() : 0;
457 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
458 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
461 mBeyondCursor = false;
463 // Some web suggest providers only give suggestions and have no description string for
464 // items. The order of the result columns may be different as well. So retrieve the
465 // column indices for the fields we need now and check before using below.
466 if (mSuggestCursor == null) {
467 mSuggestText1Id = -1;
468 mSuggestText2Id = -1;
469 mSuggestQueryId = -1;
470 mSuggestIntentExtraDataId = -1;
472 mSuggestText1Id = mSuggestCursor.getColumnIndex(
473 SearchManager.SUGGEST_COLUMN_TEXT_1);
474 mSuggestText2Id = mSuggestCursor.getColumnIndex(
475 SearchManager.SUGGEST_COLUMN_TEXT_2);
476 mSuggestQueryId = mSuggestCursor.getColumnIndex(
477 SearchManager.SUGGEST_COLUMN_QUERY);
478 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
479 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
484 public boolean onMove(int oldPosition, int newPosition) {
485 if (mHistoryCursor == null) {
488 if (mHistoryCount > newPosition) {
489 mHistoryCursor.moveToPosition(newPosition);
490 mBeyondCursor = false;
491 } else if (mHistoryCount + mSuggestionCount > newPosition) {
492 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
493 mBeyondCursor = false;
495 mBeyondCursor = true;
501 public int getCount() {
502 if (mString.length() > 0) {
503 return mHistoryCount + mSuggestionCount + 1;
505 return mHistoryCount + mSuggestionCount;
510 public String[] getColumnNames() {
515 public String getString(int columnIndex) {
516 if ((mPos != -1 && mHistoryCursor != null)) {
517 switch(columnIndex) {
518 case SUGGEST_COLUMN_INTENT_ACTION_ID:
519 if (mHistoryCount > mPos) {
520 return Intent.ACTION_VIEW;
522 return Intent.ACTION_SEARCH;
525 case SUGGEST_COLUMN_INTENT_DATA_ID:
526 if (mHistoryCount > mPos) {
527 return mHistoryCursor.getString(1);
532 case SUGGEST_COLUMN_TEXT_1_ID:
533 if (mHistoryCount > mPos) {
534 return getHistoryTitle();
535 } else if (!mBeyondCursor) {
536 if (mSuggestText1Id == -1) return null;
537 return mSuggestCursor.getString(mSuggestText1Id);
542 case SUGGEST_COLUMN_TEXT_2_ID:
543 if (mHistoryCount > mPos) {
544 return getHistorySubtitle();
545 } else if (!mBeyondCursor) {
546 if (mSuggestText2Id == -1) return null;
547 return mSuggestCursor.getString(mSuggestText2Id);
549 return getContext().getString(R.string.search_the_web);
552 case SUGGEST_COLUMN_ICON_1_ID:
553 if (mHistoryCount > mPos) {
554 if (mHistoryCursor.getInt(3) == 1) {
555 return Integer.valueOf(
556 R.drawable.ic_search_category_bookmark)
559 return Integer.valueOf(
560 R.drawable.ic_search_category_history)
564 return Integer.valueOf(
565 R.drawable.ic_search_category_suggest)
569 case SUGGEST_COLUMN_ICON_2_ID:
572 case SUGGEST_COLUMN_QUERY_ID:
573 if (mHistoryCount > mPos) {
574 // Return the url in the intent query column. This is ignored
575 // within the browser because our searchable is set to
576 // android:searchMode="queryRewriteFromData", but it is used by
577 // global search for query rewriting.
578 return mHistoryCursor.getString(1);
579 } else if (!mBeyondCursor) {
580 if (mSuggestQueryId == -1) return null;
581 return mSuggestCursor.getString(mSuggestQueryId);
586 case SUGGEST_COLUMN_FORMAT:
589 case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
590 if (mHistoryCount > mPos) {
592 } else if (!mBeyondCursor) {
593 if (mSuggestIntentExtraDataId == -1) return null;
594 return mSuggestCursor.getString(mSuggestIntentExtraDataId);
604 public double getDouble(int column) {
605 throw new UnsupportedOperationException();
609 public float getFloat(int column) {
610 throw new UnsupportedOperationException();
614 public int getInt(int column) {
615 throw new UnsupportedOperationException();
619 public long getLong(int column) {
620 if ((mPos != -1) && column == 0) {
621 return mPos; // use row# as the _Id
623 throw new UnsupportedOperationException();
627 public short getShort(int column) {
628 throw new UnsupportedOperationException();
632 public boolean isNull(int column) {
633 throw new UnsupportedOperationException();
636 // TODO Temporary change, finalize after jq's changes go in
637 public void deactivate() {
638 if (mHistoryCursor != null) {
639 mHistoryCursor.deactivate();
641 if (mSuggestCursor != null) {
642 mSuggestCursor.deactivate();
647 public boolean requery() {
648 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
649 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
652 // TODO Temporary change, finalize after jq's changes go in
653 public void close() {
655 if (mHistoryCursor != null) {
656 mHistoryCursor.close();
657 mHistoryCursor = null;
659 if (mSuggestCursor != null) {
660 mSuggestCursor.close();
661 mSuggestCursor = null;
666 * Provides the title (text line 1) for a browser suggestion, which should be the
667 * webpage title. If the webpage title is empty, returns the stripped url instead.
669 * @return the title string to use
671 private String getHistoryTitle() {
672 String title = mHistoryCursor.getString(2 /* webpage title */);
673 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
674 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
680 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
681 * webpage url. If the webpage title is empty, then the url should go in the title
682 * instead, and the subtitle should be empty, so this would return null.
684 * @return the subtitle string to use, or null if none
686 private String getHistorySubtitle() {
687 String title = mHistoryCursor.getString(2 /* webpage title */);
688 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
691 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
696 * Strips "http://" from the beginning of a url and "/" from the end,
697 * and adds html formatting to make it green.
699 private String beautifyUrl(String url) {
700 if (mSearchUrlColorId == null) {
701 // Get the color used for this purpose from the current theme.
702 TypedValue colorValue = new TypedValue();
703 getContext().getTheme().resolveAttribute(
704 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
705 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
708 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
713 public Cursor query(Uri url, String[] projectionIn, String selection,
714 String[] selectionArgs, String sortOrder)
715 throws IllegalStateException {
716 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
718 int match = URI_MATCHER.match(url);
720 throw new IllegalArgumentException("Unknown URL");
723 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
724 String suggestSelection;
726 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
727 suggestSelection = null;
730 String like = selectionArgs[0] + "%";
731 if (selectionArgs[0].startsWith("http")
732 || selectionArgs[0].startsWith("file")) {
733 myArgs = new String[1];
735 suggestSelection = selection;
737 SUGGEST_ARGS[0] = "http://" + like;
738 SUGGEST_ARGS[1] = "http://www." + like;
739 SUGGEST_ARGS[2] = "https://" + like;
740 SUGGEST_ARGS[3] = "https://www." + like;
741 // To match against titles.
742 SUGGEST_ARGS[4] = like;
743 myArgs = SUGGEST_ARGS;
744 suggestSelection = SUGGEST_SELECTION;
748 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
749 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
750 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
752 if (match == URI_MATCH_BOOKMARKS_SUGGEST
753 || Patterns.WEB_URL.matcher(selectionArgs[0]).matches()) {
754 return new MySuggestionCursor(c, null, "");
756 // get Google suggest if there is still space in the list
757 if (myArgs != null && myArgs.length > 1
758 && mSearchableInfo != null
759 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
760 Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
761 return new MySuggestionCursor(c, sc, selectionArgs[0]);
763 return new MySuggestionCursor(c, null, selectionArgs[0]);
767 String[] projection = null;
768 if (projectionIn != null && projectionIn.length > 0) {
769 projection = new String[projectionIn.length + 1];
770 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
771 projection[projectionIn.length] = "_id AS _id";
774 StringBuilder whereClause = new StringBuilder(256);
775 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
776 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
780 // Tack on the user's selection, if present
781 if (selection != null && selection.length() > 0) {
782 if (whereClause.length() > 0) {
783 whereClause.append(" AND ");
786 whereClause.append('(');
787 whereClause.append(selection);
788 whereClause.append(')');
790 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
791 whereClause.toString(), selectionArgs, null, null, sortOrder,
793 c.setNotificationUri(getContext().getContentResolver(), url);
798 public String getType(Uri url) {
799 int match = URI_MATCHER.match(url);
801 case URI_MATCH_BOOKMARKS:
802 return "vnd.android.cursor.dir/bookmark";
804 case URI_MATCH_BOOKMARKS_ID:
805 return "vnd.android.cursor.item/bookmark";
807 case URI_MATCH_SEARCHES:
808 return "vnd.android.cursor.dir/searches";
810 case URI_MATCH_SEARCHES_ID:
811 return "vnd.android.cursor.item/searches";
813 case URI_MATCH_SUGGEST:
814 return SearchManager.SUGGEST_MIME_TYPE;
817 throw new IllegalArgumentException("Unknown URL");
822 public Uri insert(Uri url, ContentValues initialValues) {
823 boolean isBookmarkTable = false;
824 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
826 int match = URI_MATCHER.match(url);
829 case URI_MATCH_BOOKMARKS: {
830 // Insert into the bookmarks table
831 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
834 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
837 isBookmarkTable = true;
841 case URI_MATCH_SEARCHES: {
842 // Insert into the searches table
843 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
846 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
853 throw new IllegalArgumentException("Unknown URL");
857 throw new IllegalArgumentException("Unknown URL");
859 getContext().getContentResolver().notifyChange(uri, null);
861 // Back up the new bookmark set if we just inserted one.
862 // A row created when bookmarks are added from scratch will have
863 // bookmark=1 in the initial value set.
865 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
866 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
867 mBackupManager.dataChanged();
873 public int delete(Uri url, String where, String[] whereArgs) {
874 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
876 int match = URI_MATCHER.match(url);
877 if (match == -1 || match == URI_MATCH_SUGGEST) {
878 throw new IllegalArgumentException("Unknown URL");
881 // need to know whether it's the bookmarks table for a couple of reasons
882 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
885 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
886 StringBuilder sb = new StringBuilder();
887 if (where != null && where.length() > 0) {
890 sb.append(" ) AND ");
892 id = url.getPathSegments().get(1);
895 where = sb.toString();
898 ContentResolver cr = getContext().getContentResolver();
900 // we'lll need to back up the bookmark set if we are about to delete one
901 if (isBookmarkTable) {
902 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
903 new String[] { BookmarkColumns.BOOKMARK },
904 "_id = " + id, null, null);
905 if (cursor.moveToNext()) {
906 if (cursor.getInt(0) != 0) {
907 // yep, this record is a bookmark
908 mBackupManager.dataChanged();
914 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
915 cr.notifyChange(url, null);
920 public int update(Uri url, ContentValues values, String where,
921 String[] whereArgs) {
922 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
924 int match = URI_MATCHER.match(url);
925 if (match == -1 || match == URI_MATCH_SUGGEST) {
926 throw new IllegalArgumentException("Unknown URL");
930 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
931 boolean changingBookmarks = false;
933 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
934 StringBuilder sb = new StringBuilder();
935 if (where != null && where.length() > 0) {
938 sb.append(" ) AND ");
940 id = url.getPathSegments().get(1);
943 where = sb.toString();
946 ContentResolver cr = getContext().getContentResolver();
948 // Not all bookmark-table updates should be backed up. Look to see
949 // whether we changed the title, url, or "is a bookmark" state, and
950 // request a backup if so.
951 if (isBookmarkTable) {
952 // Alterations to the bookmark field inherently change the bookmark
953 // set, so we don't need to query the record; we know a priori that
954 // we will need to back up this change.
955 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
956 changingBookmarks = true;
958 // changing the title or URL of a bookmark record requires a backup,
959 // but we don't know wether such an update is on a bookmark without
960 // querying the record
961 if (!changingBookmarks &&
962 (values.containsKey(BookmarkColumns.TITLE)
963 || values.containsKey(BookmarkColumns.URL))) {
964 // when isBookmarkTable is true, the 'id' var was assigned above
965 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
966 new String[] { BookmarkColumns.BOOKMARK },
967 "_id = " + id, null, null);
968 if (cursor.moveToNext()) {
969 changingBookmarks = (cursor.getInt(0) != 0);
974 // if this *is* a bookmark row we're altering, we need to back it up.
975 if (changingBookmarks) {
976 mBackupManager.dataChanged();
980 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
981 cr.notifyChange(url, null);
986 * Strips the provided url of preceding "http://" and any trailing "/". Does not
987 * strip "https://". If the provided string cannot be stripped, the original string
990 * TODO: Put this in TextUtils to be used by other packages doing something similar.
992 * @param url a url to strip, like "http://www.google.com/"
993 * @return a stripped url like "www.google.com", or the original string if it could
996 private static String stripUrl(String url) {
997 if (url == null) return null;
998 Matcher m = STRIP_URL_PATTERN.matcher(url);
999 if (m.matches() && m.groupCount() == 3) {