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.android.browser.search.SearchEngine;
21 import android.app.SearchManager;
22 import android.app.backup.BackupManager;
23 import android.content.ContentProvider;
24 import android.content.ContentResolver;
25 import android.content.ContentUris;
26 import android.content.ContentValues;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.SharedPreferences.Editor;
31 import android.content.UriMatcher;
32 import android.database.AbstractCursor;
33 import android.database.Cursor;
34 import android.database.sqlite.SQLiteDatabase;
35 import android.database.sqlite.SQLiteOpenHelper;
36 import android.net.Uri;
37 import android.os.Process;
38 import android.preference.PreferenceManager;
39 import android.provider.Browser;
40 import android.provider.Browser.BookmarkColumns;
41 import android.speech.RecognizerResultsIntent;
42 import android.text.TextUtils;
43 import android.util.Log;
44 import android.util.Patterns;
47 import java.io.FilenameFilter;
48 import java.util.ArrayList;
49 import java.util.Date;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
54 public class BrowserProvider extends ContentProvider {
56 private SQLiteOpenHelper mOpenHelper;
57 private BackupManager mBackupManager;
58 private static final String sDatabaseName = "browser.db";
59 private static final String TAG = "BrowserProvider";
60 private static final String ORDER_BY = "visits DESC, date DESC";
62 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
63 "viewer?source=androidclient";
65 private static final String[] TABLE_NAMES = new String[] {
66 "bookmarks", "searches"
68 private static final String[] SUGGEST_PROJECTION = new String[] {
69 "_id", "url", "title", "bookmark", "user_entered"
71 private static final String SUGGEST_SELECTION =
72 "(url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
73 + " OR title LIKE ?) AND (bookmark = 1 OR user_entered = 1)";
74 private String[] SUGGEST_ARGS = new String[5];
76 // shared suggestion array index, make sure to match COLUMNS
77 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
78 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
79 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
80 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
81 private static final int SUGGEST_COLUMN_TEXT_2_URL_ID = 5;
82 private static final int SUGGEST_COLUMN_ICON_1_ID = 6;
83 private static final int SUGGEST_COLUMN_ICON_2_ID = 7;
84 private static final int SUGGEST_COLUMN_QUERY_ID = 8;
85 private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
87 // shared suggestion columns
88 private static final String[] COLUMNS = new String[] {
90 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
91 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
92 SearchManager.SUGGEST_COLUMN_TEXT_1,
93 SearchManager.SUGGEST_COLUMN_TEXT_2,
94 SearchManager.SUGGEST_COLUMN_TEXT_2_URL,
95 SearchManager.SUGGEST_COLUMN_ICON_1,
96 SearchManager.SUGGEST_COLUMN_ICON_2,
97 SearchManager.SUGGEST_COLUMN_QUERY,
98 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
100 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
101 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
102 private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
103 Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
105 // make sure that these match the index of TABLE_NAMES
106 private static final int URI_MATCH_BOOKMARKS = 0;
107 private static final int URI_MATCH_SEARCHES = 1;
108 // (id % 10) should match the table name index
109 private static final int URI_MATCH_BOOKMARKS_ID = 10;
110 private static final int URI_MATCH_SEARCHES_ID = 11;
112 private static final int URI_MATCH_SUGGEST = 20;
113 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
115 private static final UriMatcher URI_MATCHER;
118 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
119 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
120 URI_MATCH_BOOKMARKS);
121 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
122 URI_MATCH_BOOKMARKS_ID);
123 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
125 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
126 URI_MATCH_SEARCHES_ID);
127 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
129 URI_MATCHER.addURI("browser",
130 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
131 URI_MATCH_BOOKMARKS_SUGGEST);
134 // 1 -> 2 add cache table
135 // 2 -> 3 update history table
136 // 3 -> 4 add passwords table
137 // 4 -> 5 add settings table
140 // 7 -> 8 drop proxy table
141 // 8 -> 9 drop settings table
142 // 9 -> 10 add form_urls and form_data
143 // 10 -> 11 add searches table
144 // 11 -> 12 modify cache table
145 // 12 -> 13 modify cache table
146 // 13 -> 14 correspond with Google Bookmarks schema
147 // 14 -> 15 move couple of tables to either browser private database or webview database
148 // 15 -> 17 Set it up for the SearchManager
149 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
150 // 18 -> 19 Remove labels table
151 // 19 -> 20 Added thumbnail
152 // 20 -> 21 Added touch_icon
153 // 21 -> 22 Remove "clientid"
154 // 22 -> 23 Added user_entered
155 private static final int DATABASE_VERSION = 23;
157 // Regular expression which matches http://, followed by some stuff, followed by
158 // optionally a trailing slash, all matched as separate groups.
159 private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
161 private BrowserSettings mSettings;
163 public BrowserProvider() {
166 // XXX: This is a major hack to remove our dependency on gsf constants and
167 // its content provider. http://b/issue?id=2425179
168 static String getClientId(ContentResolver cr) {
169 String ret = "android-google";
172 c = cr.query(Uri.parse("content://com.google.settings/partner"),
173 new String[] { "value" }, "name='client_id'", null, null);
174 if (c != null && c.moveToNext()) {
175 ret = c.getString(0);
177 } catch (RuntimeException ex) {
178 // fall through to return the default
187 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
188 StringBuffer sb = new StringBuffer();
191 final String client_id = getClientId(context.getContentResolver());
193 for (int i = 0; i < srcString.length(); ++i) {
194 char c = srcString.charAt(i);
196 sb.append(srcString.subSequence(lastCharLoc, i));
199 for (int j = i; j < srcString.length(); ++j) {
200 char k = srcString.charAt(j);
202 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
203 if (propertyKeyValue.equals("CLIENT_ID")) {
204 sb.append(client_id);
206 sb.append("unknown");
215 if (srcString.length() - lastCharLoc > 0) {
216 // Put on the tail, if there is one
217 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
222 private static class DatabaseHelper extends SQLiteOpenHelper {
223 private Context mContext;
225 public DatabaseHelper(Context context) {
226 super(context, sDatabaseName, null, DATABASE_VERSION);
231 public void onCreate(SQLiteDatabase db) {
232 db.execSQL("CREATE TABLE bookmarks (" +
233 "_id INTEGER PRIMARY KEY," +
239 "description TEXT," +
240 "bookmark INTEGER," +
241 "favicon BLOB DEFAULT NULL," +
242 "thumbnail BLOB DEFAULT NULL," +
243 "touch_icon BLOB DEFAULT NULL," +
244 "user_entered INTEGER" +
247 final CharSequence[] bookmarks = mContext.getResources()
248 .getTextArray(R.array.bookmarks);
249 int size = bookmarks.length;
251 for (int i = 0; i < size; i = i + 2) {
252 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
253 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
254 "date, created, bookmark)" + " VALUES('" +
255 bookmarks[i] + "', '" + bookmarkDestination +
258 } catch (ArrayIndexOutOfBoundsException e) {
261 db.execSQL("CREATE TABLE searches (" +
262 "_id INTEGER PRIMARY KEY," +
269 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
270 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
272 if (oldVersion == 18) {
273 db.execSQL("DROP TABLE IF EXISTS labels");
275 if (oldVersion <= 19) {
276 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
278 if (oldVersion < 21) {
279 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
281 if (oldVersion < 22) {
282 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
285 if (oldVersion < 23) {
286 db.execSQL("ALTER TABLE bookmarks ADD COLUMN user_entered INTEGER;");
288 db.execSQL("DROP TABLE IF EXISTS bookmarks");
289 db.execSQL("DROP TABLE IF EXISTS searches");
294 private void removeGears() {
298 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
299 String browserDataDirString = mContext.getApplicationInfo().dataDir;
300 final String appPluginsDirString = "app_plugins";
301 final String gearsPrefix = "gears";
302 File appPluginsDir = new File(browserDataDirString + File.separator
303 + appPluginsDirString);
304 if (!appPluginsDir.exists()) {
307 // Delete the Gears plugin files
308 File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
309 public boolean accept(File dir, String filename) {
310 return filename.startsWith(gearsPrefix);
313 for (int i = 0; i < gearsFiles.length; ++i) {
314 if (gearsFiles[i].isDirectory()) {
315 deleteDirectory(gearsFiles[i]);
317 gearsFiles[i].delete();
320 // Delete the Gears data files
321 File gearsDataDir = new File(browserDataDirString + File.separator
323 if (!gearsDataDir.exists()) {
326 deleteDirectory(gearsDataDir);
329 private void deleteDirectory(File currentDir) {
330 File[] files = currentDir.listFiles();
331 for (int i = 0; i < files.length; ++i) {
332 if (files[i].isDirectory()) {
333 deleteDirectory(files[i]);
344 public boolean onCreate() {
345 final Context context = getContext();
346 mOpenHelper = new DatabaseHelper(context);
347 mBackupManager = new BackupManager(context);
348 // we added "picasa web album" into default bookmarks for version 19.
349 // To avoid erasing the bookmark table, we added it explicitly for
350 // version 18 and 19 as in the other cases, we will erase the table.
351 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
352 SharedPreferences p = PreferenceManager
353 .getDefaultSharedPreferences(context);
354 boolean fix = p.getBoolean("fix_picasa", true);
357 Editor ed = p.edit();
358 ed.putBoolean("fix_picasa", false);
362 mSettings = BrowserSettings.getInstance();
366 private void fixPicasaBookmark() {
367 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
368 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
369 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
371 if (!cursor.moveToFirst()) {
372 // set "created" so that it will be on the top of the list
373 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
374 "date, created, bookmark)" + " VALUES('" +
375 getContext().getString(R.string.picasa) + "', '"
376 + PICASA_URL + "', 0, 0, " + new Date().getTime()
380 if (cursor != null) {
387 * Subclass AbstractCursor so we can combine multiple Cursors and add
389 * Here are the rules.
390 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
392 * 2. If bookmark/history entries has a match, "Search the web" shows up at
393 * the second place. Otherwise, "Search the web" shows up at the first
396 private class MySuggestionCursor extends AbstractCursor {
397 private Cursor mHistoryCursor;
398 private Cursor mSuggestCursor;
399 private int mHistoryCount;
400 private int mSuggestionCount;
401 private boolean mIncludeWebSearch;
402 private String mString;
403 private int mSuggestText1Id;
404 private int mSuggestText2Id;
405 private int mSuggestText2UrlId;
406 private int mSuggestQueryId;
407 private int mSuggestIntentExtraDataId;
409 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
412 mHistoryCount = hc.getCount();
413 mSuggestionCount = sc != null ? sc.getCount() : 0;
414 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
415 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
418 mIncludeWebSearch = string.length() > 0;
420 // Some web suggest providers only give suggestions and have no description string for
421 // items. The order of the result columns may be different as well. So retrieve the
422 // column indices for the fields we need now and check before using below.
423 if (mSuggestCursor == null) {
424 mSuggestText1Id = -1;
425 mSuggestText2Id = -1;
426 mSuggestText2UrlId = -1;
427 mSuggestQueryId = -1;
428 mSuggestIntentExtraDataId = -1;
430 mSuggestText1Id = mSuggestCursor.getColumnIndex(
431 SearchManager.SUGGEST_COLUMN_TEXT_1);
432 mSuggestText2Id = mSuggestCursor.getColumnIndex(
433 SearchManager.SUGGEST_COLUMN_TEXT_2);
434 mSuggestText2UrlId = mSuggestCursor.getColumnIndex(
435 SearchManager.SUGGEST_COLUMN_TEXT_2_URL);
436 mSuggestQueryId = mSuggestCursor.getColumnIndex(
437 SearchManager.SUGGEST_COLUMN_QUERY);
438 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
439 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
444 public boolean onMove(int oldPosition, int newPosition) {
445 if (mHistoryCursor == null) {
448 if (mIncludeWebSearch) {
449 if (mHistoryCount == 0 && newPosition == 0) {
451 } else if (mHistoryCount > 0) {
452 if (newPosition == 0) {
453 mHistoryCursor.moveToPosition(0);
455 } else if (newPosition == 1) {
461 if (mHistoryCount > newPosition) {
462 mHistoryCursor.moveToPosition(newPosition);
464 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
470 public int getCount() {
471 if (mIncludeWebSearch) {
472 return mHistoryCount + mSuggestionCount + 1;
474 return mHistoryCount + mSuggestionCount;
479 public String[] getColumnNames() {
484 public String getString(int columnIndex) {
485 if ((mPos != -1 && mHistoryCursor != null)) {
486 int type = -1; // 0: web search; 1: history; 2: suggestion
487 if (mIncludeWebSearch) {
488 if (mHistoryCount == 0 && mPos == 0) {
490 } else if (mHistoryCount > 0) {
493 } else if (mPos == 1) {
497 if (type == -1) type = (mPos - 1) < mHistoryCount ? 1 : 2;
499 type = mPos < mHistoryCount ? 1 : 2;
502 switch(columnIndex) {
503 case SUGGEST_COLUMN_INTENT_ACTION_ID:
505 return Intent.ACTION_VIEW;
507 return Intent.ACTION_SEARCH;
510 case SUGGEST_COLUMN_INTENT_DATA_ID:
512 return mHistoryCursor.getString(1);
517 case SUGGEST_COLUMN_TEXT_1_ID:
520 } else if (type == 1) {
521 return getHistoryTitle();
523 if (mSuggestText1Id == -1) return null;
524 return mSuggestCursor.getString(mSuggestText1Id);
527 case SUGGEST_COLUMN_TEXT_2_ID:
529 return getContext().getString(R.string.search_the_web);
530 } else if (type == 1) {
531 return null; // Use TEXT_2_URL instead
533 if (mSuggestText2Id == -1) return null;
534 return mSuggestCursor.getString(mSuggestText2Id);
537 case SUGGEST_COLUMN_TEXT_2_URL_ID:
540 } else if (type == 1) {
541 return getHistoryUrl();
543 if (mSuggestText2UrlId == -1) return null;
544 return mSuggestCursor.getString(mSuggestText2UrlId);
547 case SUGGEST_COLUMN_ICON_1_ID:
549 if (mHistoryCursor.getInt(3) == 1) {
550 return Integer.valueOf(
551 R.drawable.ic_search_category_bookmark)
554 return Integer.valueOf(
555 R.drawable.ic_search_category_history)
559 return Integer.valueOf(
560 R.drawable.ic_search_category_suggest)
564 case SUGGEST_COLUMN_ICON_2_ID:
567 case SUGGEST_COLUMN_QUERY_ID:
570 } else if (type == 1) {
571 // Return the url in the intent query column. This is ignored
572 // within the browser because our searchable is set to
573 // android:searchMode="queryRewriteFromData", but it is used by
574 // global search for query rewriting.
575 return mHistoryCursor.getString(1);
577 if (mSuggestQueryId == -1) return null;
578 return mSuggestCursor.getString(mSuggestQueryId);
581 case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
584 } else if (type == 1) {
587 if (mSuggestIntentExtraDataId == -1) return null;
588 return mSuggestCursor.getString(mSuggestIntentExtraDataId);
596 public double getDouble(int column) {
597 throw new UnsupportedOperationException();
601 public float getFloat(int column) {
602 throw new UnsupportedOperationException();
606 public int getInt(int column) {
607 throw new UnsupportedOperationException();
611 public long getLong(int column) {
612 if ((mPos != -1) && column == 0) {
613 return mPos; // use row# as the _Id
615 throw new UnsupportedOperationException();
619 public short getShort(int column) {
620 throw new UnsupportedOperationException();
624 public boolean isNull(int column) {
625 throw new UnsupportedOperationException();
628 // TODO Temporary change, finalize after jq's changes go in
629 public void deactivate() {
630 if (mHistoryCursor != null) {
631 mHistoryCursor.deactivate();
633 if (mSuggestCursor != null) {
634 mSuggestCursor.deactivate();
639 public boolean requery() {
640 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
641 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
644 // TODO Temporary change, finalize after jq's changes go in
645 public void close() {
647 if (mHistoryCursor != null) {
648 mHistoryCursor.close();
649 mHistoryCursor = null;
651 if (mSuggestCursor != null) {
652 mSuggestCursor.close();
653 mSuggestCursor = null;
658 * Provides the title (text line 1) for a browser suggestion, which should be the
659 * webpage title. If the webpage title is empty, returns the stripped url instead.
661 * @return the title string to use
663 private String getHistoryTitle() {
664 String title = mHistoryCursor.getString(2 /* webpage title */);
665 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
666 title = stripUrl(mHistoryCursor.getString(1 /* url */));
672 * Provides the subtitle (text line 2) for a browser suggestion, which should be the
673 * webpage url. If the webpage title is empty, then the url should go in the title
674 * instead, and the subtitle should be empty, so this would return null.
676 * @return the subtitle string to use, or null if none
678 private String getHistoryUrl() {
679 String title = mHistoryCursor.getString(2 /* webpage title */);
680 if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
683 return stripUrl(mHistoryCursor.getString(1 /* url */));
689 private static class ResultsCursor extends AbstractCursor {
690 // Array indices for RESULTS_COLUMNS
691 private static final int RESULT_ACTION_ID = 1;
692 private static final int RESULT_DATA_ID = 2;
693 private static final int RESULT_TEXT_ID = 3;
694 private static final int RESULT_ICON_ID = 4;
695 private static final int RESULT_EXTRA_ID = 5;
697 private static final String[] RESULTS_COLUMNS = new String[] {
699 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
700 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
701 SearchManager.SUGGEST_COLUMN_TEXT_1,
702 SearchManager.SUGGEST_COLUMN_ICON_1,
703 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA
705 private final ArrayList<String> mResults;
706 public ResultsCursor(ArrayList<String> results) {
709 public int getCount() { return mResults.size(); }
711 public String[] getColumnNames() {
712 return RESULTS_COLUMNS;
715 public String getString(int column) {
717 case RESULT_ACTION_ID:
718 return RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS;
720 // The data is used when the phone is in landscape mode. We
721 // still want to show the result string.
723 return mResults.get(mPos);
724 case RESULT_EXTRA_ID:
725 // The Intent's extra data will store the index into
726 // mResults so the BrowserActivity will know which result to
728 return Integer.toString(mPos);
730 return Integer.valueOf(R.drawable.magnifying_glass)
736 public short getShort(int column) {
737 throw new UnsupportedOperationException();
739 public int getInt(int column) {
740 throw new UnsupportedOperationException();
742 public long getLong(int column) {
743 if ((mPos != -1) && column == 0) {
744 return mPos; // use row# as the _id
746 throw new UnsupportedOperationException();
748 public float getFloat(int column) {
749 throw new UnsupportedOperationException();
751 public double getDouble(int column) {
752 throw new UnsupportedOperationException();
754 public boolean isNull(int column) {
755 throw new UnsupportedOperationException();
759 private ResultsCursor mResultsCursor;
762 * Provide a set of results to be returned to query, intended to be used
763 * by the SearchDialog when the BrowserActivity is in voice search mode.
764 * @param results Strings to display in the dropdown from the SearchDialog
766 /* package */ void setQueryResults(ArrayList<String> results) {
767 if (results == null) {
768 mResultsCursor = null;
770 mResultsCursor = new ResultsCursor(results);
775 public Cursor query(Uri url, String[] projectionIn, String selection,
776 String[] selectionArgs, String sortOrder)
777 throws IllegalStateException {
778 int match = URI_MATCHER.match(url);
780 throw new IllegalArgumentException("Unknown URL");
782 if (match == URI_MATCH_SUGGEST && mResultsCursor != null) {
783 Cursor results = mResultsCursor;
784 mResultsCursor = null;
787 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
789 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
790 String suggestSelection;
792 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
793 suggestSelection = null;
796 String like = selectionArgs[0] + "%";
797 if (selectionArgs[0].startsWith("http")
798 || selectionArgs[0].startsWith("file")) {
799 myArgs = new String[1];
801 suggestSelection = selection;
803 SUGGEST_ARGS[0] = "http://" + like;
804 SUGGEST_ARGS[1] = "http://www." + like;
805 SUGGEST_ARGS[2] = "https://" + like;
806 SUGGEST_ARGS[3] = "https://www." + like;
807 // To match against titles.
808 SUGGEST_ARGS[4] = like;
809 myArgs = SUGGEST_ARGS;
810 suggestSelection = SUGGEST_SELECTION;
814 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
815 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
816 ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
818 if (match == URI_MATCH_BOOKMARKS_SUGGEST
819 || Patterns.WEB_URL.matcher(selectionArgs[0]).matches()) {
820 return new MySuggestionCursor(c, null, "");
822 // get search suggestions if there is still space in the list
823 if (myArgs != null && myArgs.length > 1
824 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
825 SearchEngine searchEngine = mSettings.getSearchEngine();
826 if (searchEngine != null && searchEngine.supportsSuggestions()) {
827 Cursor sc = searchEngine.getSuggestions(getContext(), selectionArgs[0]);
828 return new MySuggestionCursor(c, sc, selectionArgs[0]);
831 return new MySuggestionCursor(c, null, selectionArgs[0]);
835 String[] projection = null;
836 if (projectionIn != null && projectionIn.length > 0) {
837 projection = new String[projectionIn.length + 1];
838 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
839 projection[projectionIn.length] = "_id AS _id";
842 StringBuilder whereClause = new StringBuilder(256);
843 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
844 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
848 // Tack on the user's selection, if present
849 if (selection != null && selection.length() > 0) {
850 if (whereClause.length() > 0) {
851 whereClause.append(" AND ");
854 whereClause.append('(');
855 whereClause.append(selection);
856 whereClause.append(')');
858 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
859 whereClause.toString(), selectionArgs, null, null, sortOrder,
861 c.setNotificationUri(getContext().getContentResolver(), url);
866 public String getType(Uri url) {
867 int match = URI_MATCHER.match(url);
869 case URI_MATCH_BOOKMARKS:
870 return "vnd.android.cursor.dir/bookmark";
872 case URI_MATCH_BOOKMARKS_ID:
873 return "vnd.android.cursor.item/bookmark";
875 case URI_MATCH_SEARCHES:
876 return "vnd.android.cursor.dir/searches";
878 case URI_MATCH_SEARCHES_ID:
879 return "vnd.android.cursor.item/searches";
881 case URI_MATCH_SUGGEST:
882 return SearchManager.SUGGEST_MIME_TYPE;
885 throw new IllegalArgumentException("Unknown URL");
890 public Uri insert(Uri url, ContentValues initialValues) {
891 boolean isBookmarkTable = false;
892 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
894 int match = URI_MATCHER.match(url);
897 case URI_MATCH_BOOKMARKS: {
898 // Insert into the bookmarks table
899 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
902 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
905 isBookmarkTable = true;
909 case URI_MATCH_SEARCHES: {
910 // Insert into the searches table
911 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
914 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
921 throw new IllegalArgumentException("Unknown URL");
925 throw new IllegalArgumentException("Unknown URL");
927 getContext().getContentResolver().notifyChange(uri, null);
929 // Back up the new bookmark set if we just inserted one.
930 // A row created when bookmarks are added from scratch will have
931 // bookmark=1 in the initial value set.
933 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
934 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
935 mBackupManager.dataChanged();
941 public int delete(Uri url, String where, String[] whereArgs) {
942 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
944 int match = URI_MATCHER.match(url);
945 if (match == -1 || match == URI_MATCH_SUGGEST) {
946 throw new IllegalArgumentException("Unknown URL");
949 // need to know whether it's the bookmarks table for a couple of reasons
950 boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
953 if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
954 StringBuilder sb = new StringBuilder();
955 if (where != null && where.length() > 0) {
958 sb.append(" ) AND ");
960 id = url.getPathSegments().get(1);
963 where = sb.toString();
966 ContentResolver cr = getContext().getContentResolver();
968 // we'lll need to back up the bookmark set if we are about to delete one
969 if (isBookmarkTable) {
970 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
971 new String[] { BookmarkColumns.BOOKMARK },
972 "_id = " + id, null, null);
973 if (cursor.moveToNext()) {
974 if (cursor.getInt(0) != 0) {
975 // yep, this record is a bookmark
976 mBackupManager.dataChanged();
982 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
983 cr.notifyChange(url, null);
988 public int update(Uri url, ContentValues values, String where,
989 String[] whereArgs) {
990 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
992 int match = URI_MATCHER.match(url);
993 if (match == -1 || match == URI_MATCH_SUGGEST) {
994 throw new IllegalArgumentException("Unknown URL");
997 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
998 StringBuilder sb = new StringBuilder();
999 if (where != null && where.length() > 0) {
1002 sb.append(" ) AND ");
1004 String id = url.getPathSegments().get(1);
1005 sb.append("_id = ");
1007 where = sb.toString();
1010 ContentResolver cr = getContext().getContentResolver();
1012 // Not all bookmark-table updates should be backed up. Look to see
1013 // whether we changed the title, url, or "is a bookmark" state, and
1014 // request a backup if so.
1015 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_BOOKMARKS) {
1016 boolean changingBookmarks = false;
1017 // Alterations to the bookmark field inherently change the bookmark
1018 // set, so we don't need to query the record; we know a priori that
1019 // we will need to back up this change.
1020 if (values.containsKey(BookmarkColumns.BOOKMARK)) {
1021 changingBookmarks = true;
1022 } else if ((values.containsKey(BookmarkColumns.TITLE)
1023 || values.containsKey(BookmarkColumns.URL))
1024 && values.containsKey(BookmarkColumns._ID)) {
1025 // If a title or URL has been changed, check to see if it is to
1026 // a bookmark. The ID should have been included in the update,
1028 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
1029 new String[] { BookmarkColumns.BOOKMARK },
1030 BookmarkColumns._ID + " = "
1031 + values.getAsString(BookmarkColumns._ID), null, null);
1032 if (cursor.moveToNext()) {
1033 changingBookmarks = (cursor.getInt(0) != 0);
1038 // if this *is* a bookmark row we're altering, we need to back it up.
1039 if (changingBookmarks) {
1040 mBackupManager.dataChanged();
1044 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
1045 cr.notifyChange(url, null);
1050 * Strips the provided url of preceding "http://" and any trailing "/". Does not
1051 * strip "https://". If the provided string cannot be stripped, the original string
1054 * TODO: Put this in TextUtils to be used by other packages doing something similar.
1056 * @param url a url to strip, like "http://www.google.com/"
1057 * @return a stripped url like "www.google.com", or the original string if it could
1060 private static String stripUrl(String url) {
1061 if (url == null) return null;
1062 Matcher m = STRIP_URL_PATTERN.matcher(url);
1063 if (m.matches() && m.groupCount() == 3) {