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.content.ComponentName;
23 import android.content.ContentProvider;
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.database.AbstractCursor;
32 import android.database.Cursor;
33 import android.database.sqlite.SQLiteDatabase;
34 import android.database.sqlite.SQLiteOpenHelper;
35 import android.net.Uri;
36 import android.preference.PreferenceManager;
37 import android.provider.Browser;
38 import android.server.search.SearchableInfo;
39 import android.text.util.Regex;
40 import android.util.Log;
42 import java.util.Date;
45 public class BrowserProvider extends ContentProvider {
47 private SQLiteOpenHelper mOpenHelper;
48 private static final String sDatabaseName = "browser.db";
49 private static final String TAG = "BrowserProvider";
50 private static final String ORDER_BY = "visits DESC, date DESC";
52 private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
53 "viewer?source=androidclient";
55 private static final String[] TABLE_NAMES = new String[] {
56 "bookmarks", "searches"
58 private static final String[] SUGGEST_PROJECTION = new String[] {
59 "_id", "url", "title", "bookmark"
61 private static final String SUGGEST_SELECTION =
62 "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?";
63 private String[] SUGGEST_ARGS = new String[4];
65 // shared suggestion array index, make sure to match COLUMNS
66 private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
67 private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
68 private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
69 private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
70 private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
71 private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
72 private static final int SUGGEST_COLUMN_QUERY_ID = 7;
74 // shared suggestion columns
75 private static final String[] COLUMNS = new String[] {
77 SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
78 SearchManager.SUGGEST_COLUMN_INTENT_DATA,
79 SearchManager.SUGGEST_COLUMN_TEXT_1,
80 SearchManager.SUGGEST_COLUMN_TEXT_2,
81 SearchManager.SUGGEST_COLUMN_ICON_1,
82 SearchManager.SUGGEST_COLUMN_ICON_2,
83 SearchManager.SUGGEST_COLUMN_QUERY};
85 private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
86 private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
88 // make sure that these match the index of TABLE_NAMES
89 private static final int URI_MATCH_BOOKMARKS = 0;
90 private static final int URI_MATCH_SEARCHES = 1;
91 // (id % 10) should match the table name index
92 private static final int URI_MATCH_BOOKMARKS_ID = 10;
93 private static final int URI_MATCH_SEARCHES_ID = 11;
95 private static final int URI_MATCH_SUGGEST = 20;
96 private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
98 private static final UriMatcher URI_MATCHER;
101 URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
102 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
103 URI_MATCH_BOOKMARKS);
104 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
105 URI_MATCH_BOOKMARKS_ID);
106 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
108 URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
109 URI_MATCH_SEARCHES_ID);
110 URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
112 URI_MATCHER.addURI("browser",
113 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
114 URI_MATCH_BOOKMARKS_SUGGEST);
117 // 1 -> 2 add cache table
118 // 2 -> 3 update history table
119 // 3 -> 4 add passwords table
120 // 4 -> 5 add settings table
123 // 7 -> 8 drop proxy table
124 // 8 -> 9 drop settings table
125 // 9 -> 10 add form_urls and form_data
126 // 10 -> 11 add searches table
127 // 11 -> 12 modify cache table
128 // 12 -> 13 modify cache table
129 // 13 -> 14 correspond with Google Bookmarks schema
130 // 14 -> 15 move couple of tables to either browser private database or webview database
131 // 15 -> 17 Set it up for the SearchManager
132 // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
133 // 18 -> 19 Remove labels table
134 private static final int DATABASE_VERSION = 19;
136 public BrowserProvider() {
140 private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
141 StringBuffer sb = new StringBuffer();
144 final String client_id = Partner.getString(context.getContentResolver(), Partner.CLIENT_ID);
146 for (int i = 0; i < srcString.length(); ++i) {
147 char c = srcString.charAt(i);
149 sb.append(srcString.subSequence(lastCharLoc, i));
152 for (int j = i; j < srcString.length(); ++j) {
153 char k = srcString.charAt(j);
155 String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
156 if (propertyKeyValue.equals("CLIENT_ID")) {
157 sb.append(client_id);
159 sb.append("unknown");
168 if (srcString.length() - lastCharLoc > 0) {
169 // Put on the tail, if there is one
170 sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
175 private static class DatabaseHelper extends SQLiteOpenHelper {
176 private Context mContext;
178 public DatabaseHelper(Context context) {
179 super(context, sDatabaseName, null, DATABASE_VERSION);
184 public void onCreate(SQLiteDatabase db) {
185 db.execSQL("CREATE TABLE bookmarks (" +
186 "_id INTEGER PRIMARY KEY," +
192 "description TEXT," +
193 "bookmark INTEGER," +
194 "favicon BLOB DEFAULT NULL" +
197 final CharSequence[] bookmarks = mContext.getResources()
198 .getTextArray(R.array.bookmarks);
199 int size = bookmarks.length;
201 for (int i = 0; i < size; i = i + 2) {
202 CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
203 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
204 "date, created, bookmark)" + " VALUES('" +
205 bookmarks[i] + "', '" + bookmarkDestination +
208 } catch (ArrayIndexOutOfBoundsException e) {
211 db.execSQL("CREATE TABLE searches (" +
212 "_id INTEGER PRIMARY KEY," +
219 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
220 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
221 + newVersion + ", which will destroy all old data");
222 if (oldVersion == 18) {
223 db.execSQL("DROP TABLE IF EXISTS labels");
225 db.execSQL("DROP TABLE IF EXISTS bookmarks");
226 db.execSQL("DROP TABLE IF EXISTS searches");
233 public boolean onCreate() {
234 final Context context = getContext();
235 mOpenHelper = new DatabaseHelper(context);
236 // we added "picasa web album" into default bookmarks for version 19.
237 // To avoid erasing the bookmark table, we added it explicitly for
238 // version 18 and 19 as in the other cases, we will erase the table.
239 if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
240 SharedPreferences p = PreferenceManager
241 .getDefaultSharedPreferences(context);
242 boolean fix = p.getBoolean("fix_picasa", true);
245 Editor ed = p.edit();
246 ed.putBoolean("fix_picasa", false);
253 private void fixPicasaBookmark() {
254 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
255 Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
256 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
258 if (!cursor.moveToFirst()) {
259 // set "created" so that it will be on the top of the list
260 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
261 "date, created, bookmark)" + " VALUES('" +
262 getContext().getString(R.string.picasa) + "', '"
263 + PICASA_URL + "', 0, 0, " + new Date().getTime()
267 if (cursor != null) {
274 * Subclass AbstractCursor so we can combine multiple Cursors and add
276 * Here are the rules.
277 * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
279 * 2. If bookmark/history entries are less than
280 * (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
282 private class MySuggestionCursor extends AbstractCursor {
283 private Cursor mHistoryCursor;
284 private Cursor mSuggestCursor;
285 private int mHistoryCount;
286 private int mSuggestionCount;
287 private boolean mBeyondCursor;
288 private String mString;
290 public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
293 mHistoryCount = hc.getCount();
294 mSuggestionCount = sc != null ? sc.getCount() : 0;
295 if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
296 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
299 mBeyondCursor = false;
303 public boolean onMove(int oldPosition, int newPosition) {
304 if (mHistoryCursor == null) {
307 if (mHistoryCount > newPosition) {
308 mHistoryCursor.moveToPosition(newPosition);
309 mBeyondCursor = false;
310 } else if (mHistoryCount + mSuggestionCount > newPosition) {
311 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
312 mBeyondCursor = false;
314 mBeyondCursor = true;
320 public int getCount() {
321 if (mString.length() > 0) {
322 return mHistoryCount + mSuggestionCount + 1;
324 return mHistoryCount + mSuggestionCount;
329 public String[] getColumnNames() {
334 public String getString(int columnIndex) {
335 if ((mPos != -1 && mHistoryCursor != null)) {
336 switch(columnIndex) {
337 case SUGGEST_COLUMN_INTENT_ACTION_ID:
338 if (mHistoryCount > mPos) {
339 return Intent.ACTION_VIEW;
341 return Intent.ACTION_SEARCH;
344 case SUGGEST_COLUMN_INTENT_DATA_ID:
345 if (mHistoryCount > mPos) {
346 return mHistoryCursor.getString(1);
351 case SUGGEST_COLUMN_TEXT_1_ID:
352 if (mHistoryCount > mPos) {
353 return mHistoryCursor.getString(1);
354 } else if (!mBeyondCursor) {
355 return mSuggestCursor.getString(1);
360 case SUGGEST_COLUMN_TEXT_2_ID:
361 if (mHistoryCount > mPos) {
362 return mHistoryCursor.getString(2);
363 } else if (!mBeyondCursor) {
364 return mSuggestCursor.getString(2);
366 return getContext().getString(R.string.search_google);
369 case SUGGEST_COLUMN_ICON_1_ID:
370 if (mHistoryCount > mPos) {
371 if (mHistoryCursor.getInt(3) == 1) {
373 R.drawable.ic_search_category_bookmark)
377 R.drawable.ic_search_category_history)
382 R.drawable.ic_search_category_suggest)
386 case SUGGEST_COLUMN_ICON_2_ID:
387 return new String("0");
389 case SUGGEST_COLUMN_QUERY_ID:
390 if (mHistoryCount > mPos) {
392 } else if (!mBeyondCursor) {
393 return mSuggestCursor.getString(3);
403 public double getDouble(int column) {
404 throw new UnsupportedOperationException();
408 public float getFloat(int column) {
409 throw new UnsupportedOperationException();
413 public int getInt(int column) {
414 throw new UnsupportedOperationException();
418 public long getLong(int column) {
419 if ((mPos != -1) && column == 0) {
420 return mPos; // use row# as the _Id
422 throw new UnsupportedOperationException();
426 public short getShort(int column) {
427 throw new UnsupportedOperationException();
431 public boolean isNull(int column) {
432 throw new UnsupportedOperationException();
435 // TODO Temporary change, finalize after jq's changes go in
436 public void deactivate() {
437 if (mHistoryCursor != null) {
438 mHistoryCursor.deactivate();
440 if (mSuggestCursor != null) {
441 mSuggestCursor.deactivate();
446 public boolean requery() {
447 return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
448 (mSuggestCursor != null ? mSuggestCursor.requery() : false);
451 // TODO Temporary change, finalize after jq's changes go in
452 public void close() {
454 if (mHistoryCursor != null) {
455 mHistoryCursor.close();
456 mHistoryCursor = null;
458 if (mSuggestCursor != null) {
459 mSuggestCursor.close();
460 mSuggestCursor = null;
466 public Cursor query(Uri url, String[] projectionIn, String selection,
467 String[] selectionArgs, String sortOrder)
468 throws IllegalStateException {
469 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
471 int match = URI_MATCHER.match(url);
473 throw new IllegalArgumentException("Unknown URL");
476 if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
477 String suggestSelection;
479 if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
480 suggestSelection = null;
483 String like = selectionArgs[0] + "%";
484 if (selectionArgs[0].startsWith("http")
485 || selectionArgs[0].startsWith("file")) {
486 myArgs = new String[1];
488 suggestSelection = selection;
490 SUGGEST_ARGS[0] = "http://" + like;
491 SUGGEST_ARGS[1] = "http://www." + like;
492 SUGGEST_ARGS[2] = "https://" + like;
493 SUGGEST_ARGS[3] = "https://www." + like;
494 myArgs = SUGGEST_ARGS;
495 suggestSelection = SUGGEST_SELECTION;
499 Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
500 SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
502 (new Integer(MAX_SUGGESTION_LONG_ENTRIES)).toString());
504 if (match == URI_MATCH_BOOKMARKS_SUGGEST
505 || Regex.WEB_URL_PATTERN.matcher(selectionArgs[0]).matches()) {
506 return new MySuggestionCursor(c, null, "");
508 // get Google suggest if there is still space in the list
509 if (myArgs != null && myArgs.length > 1
510 && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
511 // TODO: This shouldn't be hard-coded. Instead, it should use the
512 // default web search provider. But the API for that is not implemented yet.
513 ComponentName googleSearchComponent =
514 new ComponentName("com.android.googlesearch",
515 "com.android.googlesearch.GoogleSearch");
517 SearchManager.getSearchableInfo(googleSearchComponent, false);
518 Cursor sc = SearchManager.getSuggestions(getContext(), si, selectionArgs[0]);
519 return new MySuggestionCursor(c, sc, selectionArgs[0]);
521 return new MySuggestionCursor(c, null, selectionArgs[0]);
525 String[] projection = null;
526 if (projectionIn != null && projectionIn.length > 0) {
527 projection = new String[projectionIn.length + 1];
528 System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
529 projection[projectionIn.length] = "_id AS _id";
532 StringBuilder whereClause = new StringBuilder(256);
533 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
534 whereClause.append("(_id = ").append(url.getPathSegments().get(1))
538 // Tack on the user's selection, if present
539 if (selection != null && selection.length() > 0) {
540 if (whereClause.length() > 0) {
541 whereClause.append(" AND ");
544 whereClause.append('(');
545 whereClause.append(selection);
546 whereClause.append(')');
548 Cursor c = db.query(TABLE_NAMES[match % 10], projection,
549 whereClause.toString(), selectionArgs, null, null, sortOrder,
551 c.setNotificationUri(getContext().getContentResolver(), url);
556 public String getType(Uri url) {
557 int match = URI_MATCHER.match(url);
559 case URI_MATCH_BOOKMARKS:
560 return "vnd.android.cursor.dir/bookmark";
562 case URI_MATCH_BOOKMARKS_ID:
563 return "vnd.android.cursor.item/bookmark";
565 case URI_MATCH_SEARCHES:
566 return "vnd.android.cursor.dir/searches";
568 case URI_MATCH_SEARCHES_ID:
569 return "vnd.android.cursor.item/searches";
571 case URI_MATCH_SUGGEST:
572 return SearchManager.SUGGEST_MIME_TYPE;
575 throw new IllegalArgumentException("Unknown URL");
580 public Uri insert(Uri url, ContentValues initialValues) {
581 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
583 int match = URI_MATCHER.match(url);
586 case URI_MATCH_BOOKMARKS: {
587 // Insert into the bookmarks table
588 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
591 uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
597 case URI_MATCH_SEARCHES: {
598 // Insert into the searches table
599 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
602 uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
609 throw new IllegalArgumentException("Unknown URL");
613 throw new IllegalArgumentException("Unknown URL");
615 getContext().getContentResolver().notifyChange(uri, null);
620 public int delete(Uri url, String where, String[] whereArgs) {
621 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
623 int match = URI_MATCHER.match(url);
624 if (match == -1 || match == URI_MATCH_SUGGEST) {
625 throw new IllegalArgumentException("Unknown URL");
628 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
629 StringBuilder sb = new StringBuilder();
630 if (where != null && where.length() > 0) {
633 sb.append(" ) AND ");
636 sb.append(url.getPathSegments().get(1));
637 where = sb.toString();
640 int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
641 getContext().getContentResolver().notifyChange(url, null);
646 public int update(Uri url, ContentValues values, String where,
647 String[] whereArgs) {
648 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
650 int match = URI_MATCHER.match(url);
651 if (match == -1 || match == URI_MATCH_SUGGEST) {
652 throw new IllegalArgumentException("Unknown URL");
655 if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
656 StringBuilder sb = new StringBuilder();
657 if (where != null && where.length() > 0) {
660 sb.append(" ) AND ");
663 sb.append(url.getPathSegments().get(1));
664 where = sb.toString();
667 int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
668 getContext().getContentResolver().notifyChange(url, null);