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.AsyncTask;
42 import android.os.Handler;
43 import android.preference.PreferenceManager;
44 import android.provider.Browser;
45 import android.provider.Settings;
46 import android.provider.Browser.BookmarkColumns;
47 import android.server.search.SearchableInfo;
48 import android.text.TextUtils;
49 import android.text.util.Regex;
50 import android.util.Log;
51 import android.util.TypedValue;
54 import java.io.FilenameFilter;
55 import java.util.Date;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
60 public class BrowserProvider extends ContentProvider {
62 private SQLiteOpenHelper mOpenHelper;
63 private BackupManager mBackupManager;
64 private static final String sDatabaseName = "browser.db";
65 private static final String TAG = "BrowserProvider";
66 private static final String ORDER_BY = "visits DESC, date DESC";
68 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
69 "viewer?source=androidclient";
71 private static final String[] TABLE_NAMES = new String[] {
72 "bookmarks", "searches"
74 private static final String[] SUGGEST_PROJECTION = new String[] {
75 "_id", "url", "title", "bookmark"
77 private static final String SUGGEST_SELECTION =
78 "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
80 private String[] SUGGEST_ARGS = new String[5];
82 // shared suggestion array index, make sure to match COLUMNS
83 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
84 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
85 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
86 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
87 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
88 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
89 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
90 private static final int SUGGEST_COLUMN_FORMAT = 8;
91 private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
93 // shared suggestion columns
94 private static final String[] COLUMNS = new String[] {
96 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
97 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
98 SearchManager.SUGGEST_COLUMN_TEXT_1,
99 SearchManager.SUGGEST_COLUMN_TEXT_2,
100 SearchManager.SUGGEST_COLUMN_ICON_1,
101 SearchManager.SUGGEST_COLUMN_ICON_2,
102 SearchManager.SUGGEST_COLUMN_QUERY,
103 SearchManager.SUGGEST_COLUMN_FORMAT,
104 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
106 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
107 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
108 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
109 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
111 // make sure that these match the index of TABLE_NAMES
112 private static final int URI_MATCH_BOOKMARKS = 0;
113 private static final int URI_MATCH_SEARCHES = 1;
114 // (id % 10) should match the table name index
115 private static final int URI_MATCH_BOOKMARKS_ID = 10;
116 private static final int URI_MATCH_SEARCHES_ID = 11;
118 private static final int URI_MATCH_SUGGEST = 20;
119 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
121 private static final UriMatcher URI_MATCHER;
124 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
125 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
126 URI_MATCH_BOOKMARKS);
127 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
128 URI_MATCH_BOOKMARKS_ID);
129 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
131 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
132 URI_MATCH_SEARCHES_ID);
133 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
135 URI_MATCHER.addURI("browser",
136 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
137 URI_MATCH_BOOKMARKS_SUGGEST);
140 // 1 -> 2 add cache table
141 // 2 -> 3 update history table
142 // 3 -> 4 add passwords table
143 // 4 -> 5 add settings table
146 // 7 -> 8 drop proxy table
147 // 8 -> 9 drop settings table
148 // 9 -> 10 add form_urls and form_data
149 // 10 -> 11 add searches table
150 // 11 -> 12 modify cache table
151 // 12 -> 13 modify cache table
152 // 13 -> 14 correspond with Google Bookmarks schema
153 // 14 -> 15 move couple of tables to either browser private database or webview database
154 // 15 -> 17 Set it up for the SearchManager
155 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
156 // 18 -> 19 Remove labels table
157 // 19 -> 20 Added thumbnail
158 // 20 -> 21 Added touch_icon
159 // 21 -> 22 Remove "clientid"
160 private static final int DATABASE_VERSION = 22;
162 // Regular expression which matches http://, followed by some stuff, followed by
163 // optionally a trailing slash, all matched as separate groups.
164 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
166 private SearchManager mSearchManager;
168 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
169 // the current theme. This is not set until/unless beautifyUrl is called, at which point
170 // this variable caches the color value.
171 private static String mSearchUrlColorId;
173 public BrowserProvider() {
177 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
178 StringBuffer sb = new StringBuffer();
181 final String client_id = Partner.getString(context.getContentResolver(),
182 Partner.CLIENT_ID, "android-google");
184 for (int i = 0; i < srcString.length(); ++i) {
185 char c = srcString.charAt(i);
187 sb.append(srcString.subSequence(lastCharLoc, i));
190 for (int j = i; j < srcString.length(); ++j) {
191 char k = srcString.charAt(j);
193 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
194 if (propertyKeyValue.equals("CLIENT_ID")) {
195 sb.append(client_id);
197 sb.append("unknown");
206 if (srcString.length() - lastCharLoc > 0) {
207 // Put on the tail, if there is one
208 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
213 private static class DatabaseHelper extends SQLiteOpenHelper {
214 private Context mContext;
216 public DatabaseHelper(Context context) {
217 super(context, sDatabaseName, null, DATABASE_VERSION);
222 public void onCreate(SQLiteDatabase db) {
223 db.execSQL("CREATE TABLE bookmarks (" +
224 "_id INTEGER PRIMARY KEY," +
230 "description TEXT," +
231 "bookmark INTEGER," +
232 "favicon BLOB DEFAULT NULL," +
233 "thumbnail BLOB DEFAULT NULL," +
234 "touch_icon BLOB DEFAULT NULL" +
237 final CharSequence[] bookmarks = mContext.getResources()
238 .getTextArray(R.array.bookmarks);
239 int size = bookmarks.length;
241 for (int i = 0; i < size; i = i + 2) {
242 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
243 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
244 "date, created, bookmark)" + " VALUES('" +
245 bookmarks[i] + "', '" + bookmarkDestination +
248 } catch (ArrayIndexOutOfBoundsException e) {
251 db.execSQL("CREATE TABLE searches (" +
252 "_id INTEGER PRIMARY KEY," +
259 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
260 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
262 if (oldVersion == 18) {
263 db.execSQL("DROP TABLE IF EXISTS labels");
265 if (oldVersion <= 19) {
266 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
268 if (oldVersion < 21) {
269 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
271 if (oldVersion < 22) {
272 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
275 db.execSQL("DROP TABLE IF EXISTS bookmarks");
276 db.execSQL("DROP TABLE IF EXISTS searches");
281 private void removeGears() {
282 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
283 public Void doInBackground(Void... unused) {
284 String browserDataDirString = mContext.getApplicationInfo().dataDir;
285 final String appPluginsDirString = "app_plugins";
286 final String gearsPrefix = "gears";
287 File appPluginsDir = new File(browserDataDirString + File.separator
288 + appPluginsDirString);
289 if (!appPluginsDir.exists()) {
292 // Delete the Gears plugin files
293 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
294 public boolean accept(File dir, String filename) {
295 return filename.startsWith(gearsPrefix);
298 for (int i = 0; i < gearsFiles.length; ++i) {
299 if (gearsFiles[i].isDirectory()) {
300 deleteDirectory(gearsFiles[i]);
302 gearsFiles[i].delete();
305 // Delete the Gears data files
306 File gearsDataDir = new File(browserDataDirString + File.separator
308 if (!gearsDataDir.exists()) {
311 deleteDirectory(gearsDataDir);
315 private void deleteDirectory(File currentDir) {
316 File[] files = currentDir.listFiles();
317 for (int i = 0; i < files.length; ++i) {
318 if (files[i].isDirectory()) {
319 deleteDirectory(files[i]);
332 public boolean onCreate() {
333 final Context context = getContext();
334 mOpenHelper = new DatabaseHelper(context);
335 mBackupManager = new BackupManager(context);
336 // we added "picasa web album" into default bookmarks for version 19.
337 // To avoid erasing the bookmark table, we added it explicitly for
338 // version 18 and 19 as in the other cases, we will erase the table.
339 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
340 SharedPreferences p = PreferenceManager
341 .getDefaultSharedPreferences(context);
342 boolean fix = p.getBoolean("fix_picasa", true);
345 Editor ed = p.edit();
346 ed.putBoolean("fix_picasa", false);
350 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
351 mShowWebSuggestionsSettingChangeObserver
352 = new ShowWebSuggestionsSettingChangeObserver();
353 context.getContentResolver().registerContentObserver(
354 Settings.System.getUriFor(
355 Settings.System.SHOW_WEB_SUGGESTIONS),
356 true, mShowWebSuggestionsSettingChangeObserver);
357 updateShowWebSuggestions();
362 * This Observer will ensure that if the user changes the system
363 * setting of whether to display web suggestions, we will
364 * change accordingly.
366 /* package */ class ShowWebSuggestionsSettingChangeObserver
367 extends ContentObserver {
368 public ShowWebSuggestionsSettingChangeObserver() {
369 super(new Handler());
373 public void onChange(boolean selfChange) {
374 updateShowWebSuggestions();
378 private ShowWebSuggestionsSettingChangeObserver
379 mShowWebSuggestionsSettingChangeObserver;
381 // If non-null, then the system is set to show web suggestions,
382 // and this is the SearchableInfo to use to get them.
383 private SearchableInfo mSearchableInfo;
386 * Check the system settings to see whether web suggestions are
387 * allowed. If so, store the SearchableInfo to grab suggestions
388 * while the user is typing.
390 private void updateShowWebSuggestions() {
391 mSearchableInfo = null;
392 Context context = getContext();
393 if (Settings.System.getInt(context.getContentResolver(),
394 Settings.System.SHOW_WEB_SUGGESTIONS,
395 1 /* default on */) == 1) {
396 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
397 intent.addCategory(Intent.CATEGORY_DEFAULT);
398 ResolveInfo info = context.getPackageManager().resolveActivity(
399 intent, PackageManager.MATCH_DEFAULT_ONLY);
401 ComponentName googleSearchComponent =
402 new ComponentName(info.activityInfo.packageName,
403 info.activityInfo.name);
404 mSearchableInfo = mSearchManager.getSearchableInfo(
405 googleSearchComponent, false);
410 private void fixPicasaBookmark() {
411 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
412 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
413 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
415 if (!cursor.moveToFirst()) {
416 // set "created" so that it will be on the top of the list
417 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
418 "date, created, bookmark)" + " VALUES('" +
419 getContext().getString(R.string.picasa) + "', '"
420 + PICASA_URL + "', 0, 0, " + new Date().getTime()
424 if (cursor != null) {
431 * Subclass AbstractCursor so we can combine multiple Cursors and add
433 * Here are the rules.
434 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
436 * 2. If bookmark/history entries are less than
437 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
439 private class MySuggestionCursor extends AbstractCursor {
440 private Cursor mHistoryCursor;
441 private Cursor mSuggestCursor;
442 private int mHistoryCount;
443 private int mSuggestionCount;
444 private boolean mBeyondCursor;
445 private String mString;
446 private int mSuggestText1Id;
447 private int mSuggestText2Id;
448 private int mSuggestQueryId;
449 private int mSuggestIntentExtraDataId;
451 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
454 mHistoryCount = hc.getCount();
455 mSuggestionCount = sc != null ? sc.getCount() : 0;
456 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
457 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
460 mBeyondCursor = false;
462 // Some web suggest providers only give suggestions and have no description string for
463 // items. The order of the result columns may be different as well. So retrieve the
464 // column indices for the fields we need now and check before using below.
465 if (mSuggestCursor == null) {
466 mSuggestText1Id = -1;
467 mSuggestText2Id = -1;
468 mSuggestQueryId = -1;
469 mSuggestIntentExtraDataId = -1;
471 mSuggestText1Id = mSuggestCursor.getColumnIndex(
472 SearchManager.SUGGEST_COLUMN_TEXT_1);
473 mSuggestText2Id = mSuggestCursor.getColumnIndex(
474 SearchManager.SUGGEST_COLUMN_TEXT_2);
475 mSuggestQueryId = mSuggestCursor.getColumnIndex(
476 SearchManager.SUGGEST_COLUMN_QUERY);
477 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
478 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
483 public boolean onMove(int oldPosition, int newPosition) {
484 if (mHistoryCursor == null) {
487 if (mHistoryCount > newPosition) {
488 mHistoryCursor.moveToPosition(newPosition);
489 mBeyondCursor = false;
490 } else if (mHistoryCount + mSuggestionCount > newPosition) {
491 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
492 mBeyondCursor = false;
494 mBeyondCursor = true;
500 public int getCount() {
501 if (mString.length() > 0) {
502 return mHistoryCount + mSuggestionCount + 1;
504 return mHistoryCount + mSuggestionCount;
509 public String[] getColumnNames() {
514 public String getString(int columnIndex) {
515 if ((mPos != -1 && mHistoryCursor != null)) {
516 switch(columnIndex) {
517 case SUGGEST_COLUMN_INTENT_ACTION_ID:
518 if (mHistoryCount > mPos) {
519 return Intent.ACTION_VIEW;
521 return Intent.ACTION_SEARCH;
524 case SUGGEST_COLUMN_INTENT_DATA_ID:
525 if (mHistoryCount > mPos) {
526 return mHistoryCursor.getString(1);
531 case SUGGEST_COLUMN_TEXT_1_ID:
532 if (mHistoryCount > mPos) {
533 return getHistoryTitle();
534 } else if (!mBeyondCursor) {
535 if (mSuggestText1Id == -1) return null;
536 return mSuggestCursor.getString(mSuggestText1Id);
541 case SUGGEST_COLUMN_TEXT_2_ID:
542 if (mHistoryCount > mPos) {
543 return getHistorySubtitle();
544 } else if (!mBeyondCursor) {
545 if (mSuggestText2Id == -1) return null;
546 return mSuggestCursor.getString(mSuggestText2Id);
548 return getContext().getString(R.string.search_the_web);
551 case SUGGEST_COLUMN_ICON_1_ID:
552 if (mHistoryCount > mPos) {
553 if (mHistoryCursor.getInt(3) == 1) {
554 return Integer.valueOf(
555 R.drawable.ic_search_category_bookmark)
558 return Integer.valueOf(
559 R.drawable.ic_search_category_history)
563 return Integer.valueOf(
564 R.drawable.ic_search_category_suggest)
568 case SUGGEST_COLUMN_ICON_2_ID:
571 case SUGGEST_COLUMN_QUERY_ID:
572 if (mHistoryCount > mPos) {
573 // Return the url in the intent query column. This is ignored
574 // within the browser because our searchable is set to
575 // android:searchMode="queryRewriteFromData", but it is used by
576 // global search for query rewriting.
577 return mHistoryCursor.getString(1);
578 } else if (!mBeyondCursor) {
579 if (mSuggestQueryId == -1) return null;
580 return mSuggestCursor.getString(mSuggestQueryId);
585 case SUGGEST_COLUMN_FORMAT:
588 case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
589 if (mHistoryCount > mPos) {
591 } else if (!mBeyondCursor) {
592 if (mSuggestIntentExtraDataId == -1) return null;
593 return mSuggestCursor.getString(mSuggestIntentExtraDataId);
603 public double getDouble(int column) {
604 throw new UnsupportedOperationException();
608 public float getFloat(int column) {
609 throw new UnsupportedOperationException();
613 public int getInt(int column) {
614 throw new UnsupportedOperationException();
618 public long getLong(int column) {
619 if ((mPos != -1) && column == 0) {
620 return mPos; // use row# as the _Id
622 throw new UnsupportedOperationException();
626 public short getShort(int column) {
627 throw new UnsupportedOperationException();
631 public boolean isNull(int column) {
632 throw new UnsupportedOperationException();
635 // TODO Temporary change, finalize after jq's changes go in
636 public void deactivate() {
637 if (mHistoryCursor != null) {
638 mHistoryCursor.deactivate();
640 if (mSuggestCursor != null) {
641 mSuggestCursor.deactivate();
646 public boolean requery() {
647 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
648 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
651 // TODO Temporary change, finalize after jq's changes go in
652 public void close() {
654 if (mHistoryCursor != null) {
655 mHistoryCursor.close();
656 mHistoryCursor = null;
658 if (mSuggestCursor != null) {
659 mSuggestCursor.close();
660 mSuggestCursor = null;
665 * Provides the title (text line 1) for a browser suggestion, which should be the
666 * webpage title. If the webpage title is empty, returns the stripped url instead.
668 * @return the title string to use
670 private String getHistoryTitle() {
671 String title = mHistoryCursor.getString(2 /* webpage title */);
672 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
673 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
679 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
680 * webpage url. If the webpage title is empty, then the url should go in the title
681 * instead, and the subtitle should be empty, so this would return null.
683 * @return the subtitle string to use, or null if none
685 private String getHistorySubtitle() {
686 String title = mHistoryCursor.getString(2 /* webpage title */);
687 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
690 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
695 * Strips "http://" from the beginning of a url and "/" from the end,
696 * and adds html formatting to make it green.
698 private String beautifyUrl(String url) {
699 if (mSearchUrlColorId == null) {
700 // Get the color used for this purpose from the current theme.
701 TypedValue colorValue = new TypedValue();
702 getContext().getTheme().resolveAttribute(
703 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
704 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
707 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
712 public Cursor query(Uri url, String[] projectionIn, String selection,
713 String[] selectionArgs, String sortOrder)
714 throws IllegalStateException {
715 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
717 int match = URI_MATCHER.match(url);
719 throw new IllegalArgumentException("Unknown URL");
722 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
723 String suggestSelection;
725 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
726 suggestSelection = null;
729 String like = selectionArgs[0] + "%";
730 if (selectionArgs[0].startsWith("http")
731 || selectionArgs[0].startsWith("file")) {
732 myArgs = new String[1];
734 suggestSelection = selection;
736 SUGGEST_ARGS[0] = "http://" + like;
737 SUGGEST_ARGS[1] = "http://www." + like;
738 SUGGEST_ARGS[2] = "https://" + like;
739 SUGGEST_ARGS[3] = "https://www." + like;
740 // To match against titles.
741 SUGGEST_ARGS[4] = like;
742 myArgs = SUGGEST_ARGS;
743 suggestSelection = SUGGEST_SELECTION;
747 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
748 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
749 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
751 if (match == URI_MATCH_BOOKMARKS_SUGGEST
752 || Regex.WEB_URL_PATTERN.matcher(selectionArgs[0]).matches()) {
753 return new MySuggestionCursor(c, null, "");
755 // get Google suggest if there is still space in the list
756 if (myArgs != null && myArgs.length > 1
757 && mSearchableInfo != null
758 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
759 Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
760 return new MySuggestionCursor(c, sc, selectionArgs[0]);
762 return new MySuggestionCursor(c, null, selectionArgs[0]);
766 String[] projection = null;
767 if (projectionIn != null && projectionIn.length > 0) {
768 projection = new String[projectionIn.length + 1];
769 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
770 projection[projectionIn.length] = "_id AS _id";
773 StringBuilder whereClause = new StringBuilder(256);
774 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
775 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
779 // Tack on the user's selection, if present
780 if (selection != null && selection.length() > 0) {
781 if (whereClause.length() > 0) {
782 whereClause.append(" AND ");
785 whereClause.append('(');
786 whereClause.append(selection);
787 whereClause.append(')');
789 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
790 whereClause.toString(), selectionArgs, null, null, sortOrder,
792 c.setNotificationUri(getContext().getContentResolver(), url);
797 public String getType(Uri url) {
798 int match = URI_MATCHER.match(url);
800 case URI_MATCH_BOOKMARKS:
801 return "vnd.android.cursor.dir/bookmark";
803 case URI_MATCH_BOOKMARKS_ID:
804 return "vnd.android.cursor.item/bookmark";
806 case URI_MATCH_SEARCHES:
807 return "vnd.android.cursor.dir/searches";
809 case URI_MATCH_SEARCHES_ID:
810 return "vnd.android.cursor.item/searches";
812 case URI_MATCH_SUGGEST:
813 return SearchManager.SUGGEST_MIME_TYPE;
816 throw new IllegalArgumentException("Unknown URL");
821 public Uri insert(Uri url, ContentValues initialValues) {
822 boolean isBookmarkTable = false;
823 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
825 int match = URI_MATCHER.match(url);
828 case URI_MATCH_BOOKMARKS: {
829 // Insert into the bookmarks table
830 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
833 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
836 isBookmarkTable = true;
840 case URI_MATCH_SEARCHES: {
841 // Insert into the searches table
842 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
845 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
852 throw new IllegalArgumentException("Unknown URL");
856 throw new IllegalArgumentException("Unknown URL");
858 getContext().getContentResolver().notifyChange(uri, null);
860 // Back up the new bookmark set if we just inserted one.
861 // A row created when bookmarks are added from scratch will have
862 // bookmark=1 in the initial value set.
864 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
865 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
866 mBackupManager.dataChanged();
872 public int delete(Uri url, String where, String[] whereArgs) {
873 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
875 int match = URI_MATCHER.match(url);
876 if (match == -1 || match == URI_MATCH_SUGGEST) {
877 throw new IllegalArgumentException("Unknown URL");
880 // need to know whether it's the bookmarks table for a couple of reasons
881 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
884 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
885 StringBuilder sb = new StringBuilder();
886 if (where != null && where.length() > 0) {
889 sb.append(" ) AND ");
891 id = url.getPathSegments().get(1);
894 where = sb.toString();
897 ContentResolver cr = getContext().getContentResolver();
899 // we'lll need to back up the bookmark set if we are about to delete one
900 if (isBookmarkTable) {
901 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
902 new String[] { BookmarkColumns.BOOKMARK },
903 "_id = " + id, null, null);
904 if (cursor.moveToNext()) {
905 if (cursor.getInt(0) != 0) {
906 // yep, this record is a bookmark
907 mBackupManager.dataChanged();
913 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
914 cr.notifyChange(url, null);
919 public int update(Uri url, ContentValues values, String where,
920 String[] whereArgs) {
921 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
923 int match = URI_MATCHER.match(url);
924 if (match == -1 || match == URI_MATCH_SUGGEST) {
925 throw new IllegalArgumentException("Unknown URL");
929 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
930 boolean changingBookmarks = false;
932 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
933 StringBuilder sb = new StringBuilder();
934 if (where != null && where.length() > 0) {
937 sb.append(" ) AND ");
939 id = url.getPathSegments().get(1);
942 where = sb.toString();
945 ContentResolver cr = getContext().getContentResolver();
947 // Not all bookmark-table updates should be backed up. Look to see
948 // whether we changed the title, url, or "is a bookmark" state, and
949 // request a backup if so.
950 if (isBookmarkTable) {
951 // Alterations to the bookmark field inherently change the bookmark
952 // set, so we don't need to query the record; we know a priori that
953 // we will need to back up this change.
954 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
955 changingBookmarks = true;
957 // changing the title or URL of a bookmark record requires a backup,
958 // but we don't know wether such an update is on a bookmark without
959 // querying the record
960 if (!changingBookmarks &&
961 (values.containsKey(BookmarkColumns.TITLE)
962 || values.containsKey(BookmarkColumns.URL))) {
963 // when isBookmarkTable is true, the 'id' var was assigned above
964 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
965 new String[] { BookmarkColumns.BOOKMARK },
966 "_id = " + id, null, null);
967 if (cursor.moveToNext()) {
968 changingBookmarks = (cursor.getInt(0) != 0);
973 // if this *is* a bookmark row we're altering, we need to back it up.
974 if (changingBookmarks) {
975 mBackupManager.dataChanged();
979 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
980 cr.notifyChange(url, null);
985 * Strips the provided url of preceding "http://" and any trailing "/". Does not
986 * strip "https://". If the provided string cannot be stripped, the original string
989 * TODO: Put this in TextUtils to be used by other packages doing something similar.
991 * @param url a url to strip, like "http://www.google.com/"
992 * @return a stripped url like "www.google.com", or the original string if it could
995 private static String stripUrl(String url) {
996 if (url == null) return null;
997 Matcher m = STRIP_URL_PATTERN.matcher(url);
998 if (m.matches() && m.groupCount() == 3) {