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;
92 // shared suggestion columns
93 private static final String[] COLUMNS = new String[] {
95 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
96 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
97 SearchManager.SUGGEST_COLUMN_TEXT_1,
98 SearchManager.SUGGEST_COLUMN_TEXT_2,
99 SearchManager.SUGGEST_COLUMN_ICON_1,
100 SearchManager.SUGGEST_COLUMN_ICON_2,
101 SearchManager.SUGGEST_COLUMN_QUERY,
102 SearchManager.SUGGEST_COLUMN_FORMAT};
104 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
105 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
106 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
107 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
109 // make sure that these match the index of TABLE_NAMES
110 private static final int URI_MATCH_BOOKMARKS = 0;
111 private static final int URI_MATCH_SEARCHES = 1;
112 // (id % 10) should match the table name index
113 private static final int URI_MATCH_BOOKMARKS_ID = 10;
114 private static final int URI_MATCH_SEARCHES_ID = 11;
116 private static final int URI_MATCH_SUGGEST = 20;
117 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
119 private static final UriMatcher URI_MATCHER;
122 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
123 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
124 URI_MATCH_BOOKMARKS);
125 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
126 URI_MATCH_BOOKMARKS_ID);
127 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
129 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
130 URI_MATCH_SEARCHES_ID);
131 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
133 URI_MATCHER.addURI("browser",
134 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
135 URI_MATCH_BOOKMARKS_SUGGEST);
138 // 1 -> 2 add cache table
139 // 2 -> 3 update history table
140 // 3 -> 4 add passwords table
141 // 4 -> 5 add settings table
144 // 7 -> 8 drop proxy table
145 // 8 -> 9 drop settings table
146 // 9 -> 10 add form_urls and form_data
147 // 10 -> 11 add searches table
148 // 11 -> 12 modify cache table
149 // 12 -> 13 modify cache table
150 // 13 -> 14 correspond with Google Bookmarks schema
151 // 14 -> 15 move couple of tables to either browser private database or webview database
152 // 15 -> 17 Set it up for the SearchManager
153 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
154 // 18 -> 19 Remove labels table
155 // 19 -> 20 Added thumbnail
156 // 20 -> 21 Added touch_icon
157 // 21 -> 22 Remove "clientid"
158 private static final int DATABASE_VERSION = 22;
160 // Regular expression which matches http://, followed by some stuff, followed by
161 // optionally a trailing slash, all matched as separate groups.
162 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
164 private SearchManager mSearchManager;
166 // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
167 // the current theme. This is not set until/unless beautifyUrl is called, at which point
168 // this variable caches the color value.
169 private static String mSearchUrlColorId;
171 public BrowserProvider() {
175 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
176 StringBuffer sb = new StringBuffer();
179 final String client_id = Partner.getString(context.getContentResolver(),
180 Partner.CLIENT_ID, "android-google");
182 for (int i = 0; i < srcString.length(); ++i) {
183 char c = srcString.charAt(i);
185 sb.append(srcString.subSequence(lastCharLoc, i));
188 for (int j = i; j < srcString.length(); ++j) {
189 char k = srcString.charAt(j);
191 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
192 if (propertyKeyValue.equals("CLIENT_ID")) {
193 sb.append(client_id);
195 sb.append("unknown");
204 if (srcString.length() - lastCharLoc > 0) {
205 // Put on the tail, if there is one
206 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
211 private static class DatabaseHelper extends SQLiteOpenHelper {
212 private Context mContext;
214 public DatabaseHelper(Context context) {
215 super(context, sDatabaseName, null, DATABASE_VERSION);
220 public void onCreate(SQLiteDatabase db) {
221 db.execSQL("CREATE TABLE bookmarks (" +
222 "_id INTEGER PRIMARY KEY," +
228 "description TEXT," +
229 "bookmark INTEGER," +
230 "favicon BLOB DEFAULT NULL," +
231 "thumbnail BLOB DEFAULT NULL," +
232 "touch_icon BLOB DEFAULT NULL" +
235 final CharSequence[] bookmarks = mContext.getResources()
236 .getTextArray(R.array.bookmarks);
237 int size = bookmarks.length;
239 for (int i = 0; i < size; i = i + 2) {
240 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
241 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
242 "date, created, bookmark)" + " VALUES('" +
243 bookmarks[i] + "', '" + bookmarkDestination +
246 } catch (ArrayIndexOutOfBoundsException e) {
249 db.execSQL("CREATE TABLE searches (" +
250 "_id INTEGER PRIMARY KEY," +
257 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
258 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
260 if (oldVersion == 18) {
261 db.execSQL("DROP TABLE IF EXISTS labels");
263 if (oldVersion <= 19) {
264 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
266 if (oldVersion < 21) {
267 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
269 if (oldVersion < 22) {
270 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
273 db.execSQL("DROP TABLE IF EXISTS bookmarks");
274 db.execSQL("DROP TABLE IF EXISTS searches");
279 private void removeGears() {
280 AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
281 public Void doInBackground(Void... unused) {
282 String browserDataDirString = mContext.getApplicationInfo().dataDir;
283 final String appPluginsDirString = "app_plugins";
284 final String gearsPrefix = "gears";
285 File appPluginsDir = new File(browserDataDirString + File.separator
286 + appPluginsDirString);
287 if (!appPluginsDir.exists()) {
290 // Delete the Gears plugin files
291 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
292 public boolean accept(File dir, String filename) {
293 return filename.startsWith(gearsPrefix);
296 for (int i = 0; i < gearsFiles.length; ++i) {
297 if (gearsFiles[i].isDirectory()) {
298 deleteDirectory(gearsFiles[i]);
300 gearsFiles[i].delete();
303 // Delete the Gears data files
304 File gearsDataDir = new File(browserDataDirString + File.separator
306 if (!gearsDataDir.exists()) {
309 deleteDirectory(gearsDataDir);
313 private void deleteDirectory(File currentDir) {
314 File[] files = currentDir.listFiles();
315 for (int i = 0; i < files.length; ++i) {
316 if (files[i].isDirectory()) {
317 deleteDirectory(files[i]);
330 public boolean onCreate() {
331 final Context context = getContext();
332 mOpenHelper = new DatabaseHelper(context);
333 mBackupManager = new BackupManager(context);
334 // we added "picasa web album" into default bookmarks for version 19.
335 // To avoid erasing the bookmark table, we added it explicitly for
336 // version 18 and 19 as in the other cases, we will erase the table.
337 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
338 SharedPreferences p = PreferenceManager
339 .getDefaultSharedPreferences(context);
340 boolean fix = p.getBoolean("fix_picasa", true);
343 Editor ed = p.edit();
344 ed.putBoolean("fix_picasa", false);
348 mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
349 mShowWebSuggestionsSettingChangeObserver
350 = new ShowWebSuggestionsSettingChangeObserver();
351 context.getContentResolver().registerContentObserver(
352 Settings.System.getUriFor(
353 Settings.System.SHOW_WEB_SUGGESTIONS),
354 true, mShowWebSuggestionsSettingChangeObserver);
355 updateShowWebSuggestions();
360 * This Observer will ensure that if the user changes the system
361 * setting of whether to display web suggestions, we will
362 * change accordingly.
364 /* package */ class ShowWebSuggestionsSettingChangeObserver
365 extends ContentObserver {
366 public ShowWebSuggestionsSettingChangeObserver() {
367 super(new Handler());
371 public void onChange(boolean selfChange) {
372 updateShowWebSuggestions();
376 private ShowWebSuggestionsSettingChangeObserver
377 mShowWebSuggestionsSettingChangeObserver;
379 // If non-null, then the system is set to show web suggestions,
380 // and this is the SearchableInfo to use to get them.
381 private SearchableInfo mSearchableInfo;
384 * Check the system settings to see whether web suggestions are
385 * allowed. If so, store the SearchableInfo to grab suggestions
386 * while the user is typing.
388 private void updateShowWebSuggestions() {
389 mSearchableInfo = null;
390 Context context = getContext();
391 if (Settings.System.getInt(context.getContentResolver(),
392 Settings.System.SHOW_WEB_SUGGESTIONS,
393 1 /* default on */) == 1) {
394 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
395 intent.addCategory(Intent.CATEGORY_DEFAULT);
396 ResolveInfo info = context.getPackageManager().resolveActivity(
397 intent, PackageManager.MATCH_DEFAULT_ONLY);
399 ComponentName googleSearchComponent =
400 new ComponentName(info.activityInfo.packageName,
401 info.activityInfo.name);
402 mSearchableInfo = mSearchManager.getSearchableInfo(
403 googleSearchComponent, false);
408 private void fixPicasaBookmark() {
409 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
410 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
411 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
413 if (!cursor.moveToFirst()) {
414 // set "created" so that it will be on the top of the list
415 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
416 "date, created, bookmark)" + " VALUES('" +
417 getContext().getString(R.string.picasa) + "', '"
418 + PICASA_URL + "', 0, 0, " + new Date().getTime()
422 if (cursor != null) {
429 * Subclass AbstractCursor so we can combine multiple Cursors and add
431 * Here are the rules.
432 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
434 * 2. If bookmark/history entries are less than
435 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
437 private class MySuggestionCursor extends AbstractCursor {
438 private Cursor mHistoryCursor;
439 private Cursor mSuggestCursor;
440 private int mHistoryCount;
441 private int mSuggestionCount;
442 private boolean mBeyondCursor;
443 private String mString;
444 private int mSuggestText1Id;
445 private int mSuggestText2Id;
446 private int mSuggestQueryId;
448 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
451 mHistoryCount = hc.getCount();
452 mSuggestionCount = sc != null ? sc.getCount() : 0;
453 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
454 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
457 mBeyondCursor = false;
459 // Some web suggest providers only give suggestions and have no description string for
460 // items. The order of the result columns may be different as well. So retrieve the
461 // column indices for the fields we need now and check before using below.
462 if (mSuggestCursor == null) {
463 mSuggestText1Id = -1;
464 mSuggestText2Id = -1;
465 mSuggestQueryId = -1;
467 mSuggestText1Id = mSuggestCursor.getColumnIndex(
468 SearchManager.SUGGEST_COLUMN_TEXT_1);
469 mSuggestText2Id = mSuggestCursor.getColumnIndex(
470 SearchManager.SUGGEST_COLUMN_TEXT_2);
471 mSuggestQueryId = mSuggestCursor.getColumnIndex(
472 SearchManager.SUGGEST_COLUMN_QUERY);
477 public boolean onMove(int oldPosition, int newPosition) {
478 if (mHistoryCursor == null) {
481 if (mHistoryCount > newPosition) {
482 mHistoryCursor.moveToPosition(newPosition);
483 mBeyondCursor = false;
484 } else if (mHistoryCount + mSuggestionCount > newPosition) {
485 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
486 mBeyondCursor = false;
488 mBeyondCursor = true;
494 public int getCount() {
495 if (mString.length() > 0) {
496 return mHistoryCount + mSuggestionCount + 1;
498 return mHistoryCount + mSuggestionCount;
503 public String[] getColumnNames() {
508 public String getString(int columnIndex) {
509 if ((mPos != -1 && mHistoryCursor != null)) {
510 switch(columnIndex) {
511 case SUGGEST_COLUMN_INTENT_ACTION_ID:
512 if (mHistoryCount > mPos) {
513 return Intent.ACTION_VIEW;
515 return Intent.ACTION_SEARCH;
518 case SUGGEST_COLUMN_INTENT_DATA_ID:
519 if (mHistoryCount > mPos) {
520 return mHistoryCursor.getString(1);
525 case SUGGEST_COLUMN_TEXT_1_ID:
526 if (mHistoryCount > mPos) {
527 return getHistoryTitle();
528 } else if (!mBeyondCursor) {
529 if (mSuggestText1Id == -1) return null;
530 return mSuggestCursor.getString(mSuggestText1Id);
535 case SUGGEST_COLUMN_TEXT_2_ID:
536 if (mHistoryCount > mPos) {
537 return getHistorySubtitle();
538 } else if (!mBeyondCursor) {
539 if (mSuggestText2Id == -1) return null;
540 return mSuggestCursor.getString(mSuggestText2Id);
542 return getContext().getString(R.string.search_the_web);
545 case SUGGEST_COLUMN_ICON_1_ID:
546 if (mHistoryCount > mPos) {
547 if (mHistoryCursor.getInt(3) == 1) {
548 return Integer.valueOf(
549 R.drawable.ic_search_category_bookmark)
552 return Integer.valueOf(
553 R.drawable.ic_search_category_history)
557 return Integer.valueOf(
558 R.drawable.ic_search_category_suggest)
562 case SUGGEST_COLUMN_ICON_2_ID:
565 case SUGGEST_COLUMN_QUERY_ID:
566 if (mHistoryCount > mPos) {
567 // Return the url in the intent query column. This is ignored
568 // within the browser because our searchable is set to
569 // android:searchMode="queryRewriteFromData", but it is used by
570 // global search for query rewriting.
571 return mHistoryCursor.getString(1);
572 } else if (!mBeyondCursor) {
573 if (mSuggestQueryId == -1) return null;
574 return mSuggestCursor.getString(mSuggestQueryId);
579 case SUGGEST_COLUMN_FORMAT:
587 public double getDouble(int column) {
588 throw new UnsupportedOperationException();
592 public float getFloat(int column) {
593 throw new UnsupportedOperationException();
597 public int getInt(int column) {
598 throw new UnsupportedOperationException();
602 public long getLong(int column) {
603 if ((mPos != -1) && column == 0) {
604 return mPos; // use row# as the _Id
606 throw new UnsupportedOperationException();
610 public short getShort(int column) {
611 throw new UnsupportedOperationException();
615 public boolean isNull(int column) {
616 throw new UnsupportedOperationException();
619 // TODO Temporary change, finalize after jq's changes go in
620 public void deactivate() {
621 if (mHistoryCursor != null) {
622 mHistoryCursor.deactivate();
624 if (mSuggestCursor != null) {
625 mSuggestCursor.deactivate();
630 public boolean requery() {
631 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
632 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
635 // TODO Temporary change, finalize after jq's changes go in
636 public void close() {
638 if (mHistoryCursor != null) {
639 mHistoryCursor.close();
640 mHistoryCursor = null;
642 if (mSuggestCursor != null) {
643 mSuggestCursor.close();
644 mSuggestCursor = null;
649 * Provides the title (text line 1) for a browser suggestion, which should be the
650 * webpage title. If the webpage title is empty, returns the stripped url instead.
652 * @return the title string to use
654 private String getHistoryTitle() {
655 String title = mHistoryCursor.getString(2 /* webpage title */);
656 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
657 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
663 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
664 * webpage url. If the webpage title is empty, then the url should go in the title
665 * instead, and the subtitle should be empty, so this would return null.
667 * @return the subtitle string to use, or null if none
669 private String getHistorySubtitle() {
670 String title = mHistoryCursor.getString(2 /* webpage title */);
671 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
674 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
679 * Strips "http://" from the beginning of a url and "/" from the end,
680 * and adds html formatting to make it green.
682 private String beautifyUrl(String url) {
683 if (mSearchUrlColorId == null) {
684 // Get the color used for this purpose from the current theme.
685 TypedValue colorValue = new TypedValue();
686 getContext().getTheme().resolveAttribute(
687 com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
688 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
691 return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
696 public Cursor query(Uri url, String[] projectionIn, String selection,
697 String[] selectionArgs, String sortOrder)
698 throws IllegalStateException {
699 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
701 int match = URI_MATCHER.match(url);
703 throw new IllegalArgumentException("Unknown URL");
706 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
707 String suggestSelection;
709 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
710 suggestSelection = null;
713 String like = selectionArgs[0] + "%";
714 if (selectionArgs[0].startsWith("http")
715 || selectionArgs[0].startsWith("file")) {
716 myArgs = new String[1];
718 suggestSelection = selection;
720 SUGGEST_ARGS[0] = "http://" + like;
721 SUGGEST_ARGS[1] = "http://www." + like;
722 SUGGEST_ARGS[2] = "https://" + like;
723 SUGGEST_ARGS[3] = "https://www." + like;
724 // To match against titles.
725 SUGGEST_ARGS[4] = like;
726 myArgs = SUGGEST_ARGS;
727 suggestSelection = SUGGEST_SELECTION;
731 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
732 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
733 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
735 if (match == URI_MATCH_BOOKMARKS_SUGGEST
736 || Regex.WEB_URL_PATTERN.matcher(selectionArgs[0]).matches()) {
737 return new MySuggestionCursor(c, null, "");
739 // get Google suggest if there is still space in the list
740 if (myArgs != null && myArgs.length > 1
741 && mSearchableInfo != null
742 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
743 Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
744 return new MySuggestionCursor(c, sc, selectionArgs[0]);
746 return new MySuggestionCursor(c, null, selectionArgs[0]);
750 String[] projection = null;
751 if (projectionIn != null && projectionIn.length > 0) {
752 projection = new String[projectionIn.length + 1];
753 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
754 projection[projectionIn.length] = "_id AS _id";
757 StringBuilder whereClause = new StringBuilder(256);
758 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
759 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
763 // Tack on the user's selection, if present
764 if (selection != null && selection.length() > 0) {
765 if (whereClause.length() > 0) {
766 whereClause.append(" AND ");
769 whereClause.append('(');
770 whereClause.append(selection);
771 whereClause.append(')');
773 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
774 whereClause.toString(), selectionArgs, null, null, sortOrder,
776 c.setNotificationUri(getContext().getContentResolver(), url);
781 public String getType(Uri url) {
782 int match = URI_MATCHER.match(url);
784 case URI_MATCH_BOOKMARKS:
785 return "vnd.android.cursor.dir/bookmark";
787 case URI_MATCH_BOOKMARKS_ID:
788 return "vnd.android.cursor.item/bookmark";
790 case URI_MATCH_SEARCHES:
791 return "vnd.android.cursor.dir/searches";
793 case URI_MATCH_SEARCHES_ID:
794 return "vnd.android.cursor.item/searches";
796 case URI_MATCH_SUGGEST:
797 return SearchManager.SUGGEST_MIME_TYPE;
800 throw new IllegalArgumentException("Unknown URL");
805 public Uri insert(Uri url, ContentValues initialValues) {
806 boolean isBookmarkTable = false;
807 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
809 int match = URI_MATCHER.match(url);
812 case URI_MATCH_BOOKMARKS: {
813 // Insert into the bookmarks table
814 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
817 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
820 isBookmarkTable = true;
824 case URI_MATCH_SEARCHES: {
825 // Insert into the searches table
826 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
829 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
836 throw new IllegalArgumentException("Unknown URL");
840 throw new IllegalArgumentException("Unknown URL");
842 getContext().getContentResolver().notifyChange(uri, null);
844 // Back up the new bookmark set if we just inserted one.
845 // A row created when bookmarks are added from scratch will have
846 // bookmark=1 in the initial value set.
848 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
849 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
850 mBackupManager.dataChanged();
856 public int delete(Uri url, String where, String[] whereArgs) {
857 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
859 int match = URI_MATCHER.match(url);
860 if (match == -1 || match == URI_MATCH_SUGGEST) {
861 throw new IllegalArgumentException("Unknown URL");
864 // need to know whether it's the bookmarks table for a couple of reasons
865 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
868 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
869 StringBuilder sb = new StringBuilder();
870 if (where != null && where.length() > 0) {
873 sb.append(" ) AND ");
875 id = url.getPathSegments().get(1);
878 where = sb.toString();
881 ContentResolver cr = getContext().getContentResolver();
883 // we'lll need to back up the bookmark set if we are about to delete one
884 if (isBookmarkTable) {
885 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
886 new String[] { BookmarkColumns.BOOKMARK },
887 "_id = " + id, null, null);
888 if (cursor.moveToNext()) {
889 if (cursor.getInt(0) != 0) {
890 // yep, this record is a bookmark
891 mBackupManager.dataChanged();
897 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
898 cr.notifyChange(url, null);
903 public int update(Uri url, ContentValues values, String where,
904 String[] whereArgs) {
905 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
907 int match = URI_MATCHER.match(url);
908 if (match == -1 || match == URI_MATCH_SUGGEST) {
909 throw new IllegalArgumentException("Unknown URL");
913 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
914 boolean changingBookmarks = false;
916 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
917 StringBuilder sb = new StringBuilder();
918 if (where != null && where.length() > 0) {
921 sb.append(" ) AND ");
923 id = url.getPathSegments().get(1);
926 where = sb.toString();
929 ContentResolver cr = getContext().getContentResolver();
931 // Not all bookmark-table updates should be backed up. Look to see
932 // whether we changed the title, url, or "is a bookmark" state, and
933 // request a backup if so.
934 if (isBookmarkTable) {
935 // Alterations to the bookmark field inherently change the bookmark
936 // set, so we don't need to query the record; we know a priori that
937 // we will need to back up this change.
938 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
939 changingBookmarks = true;
941 // changing the title or URL of a bookmark record requires a backup,
942 // but we don't know wether such an update is on a bookmark without
943 // querying the record
944 if (!changingBookmarks &&
945 (values.containsKey(BookmarkColumns.TITLE)
946 || values.containsKey(BookmarkColumns.URL))) {
947 // when isBookmarkTable is true, the 'id' var was assigned above
948 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
949 new String[] { BookmarkColumns.BOOKMARK },
950 "_id = " + id, null, null);
951 if (cursor.moveToNext()) {
952 changingBookmarks = (cursor.getInt(0) != 0);
957 // if this *is* a bookmark row we're altering, we need to back it up.
958 if (changingBookmarks) {
959 mBackupManager.dataChanged();
963 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
964 cr.notifyChange(url, null);
969 * Strips the provided url of preceding "http://" and any trailing "/". Does not
970 * strip "https://". If the provided string cannot be stripped, the original string
973 * TODO: Put this in TextUtils to be used by other packages doing something similar.
975 * @param url a url to strip, like "http://www.google.com/"
976 * @return a stripped url like "www.google.com", or the original string if it could
979 private static String stripUrl(String url) {
980 if (url == null) return null;
981 Matcher m = STRIP_URL_PATTERN.matcher(url);
982 if (m.matches() && m.groupCount() == 3) {