OSDN Git Service

Merge change I5ee906c0 into eclair-mr2
[android-x86/packages-apps-Browser.git] / src / com / android / browser / BrowserProvider.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.browser;
18
19 import android.app.SearchManager;
20 import android.backup.BackupManager;
21 import android.content.ComponentName;
22 import android.content.ContentProvider;
23 import android.content.ContentResolver;
24 import android.content.ContentUris;
25 import android.content.ContentValues;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.content.UriMatcher;
30 import android.content.SharedPreferences.Editor;
31 import android.content.pm.PackageManager;
32 import android.content.pm.ResolveInfo;
33 import android.database.AbstractCursor;
34 import android.database.ContentObserver;
35 import android.database.Cursor;
36 import android.database.sqlite.SQLiteDatabase;
37 import android.database.sqlite.SQLiteOpenHelper;
38 import android.net.Uri;
39 import android.os.AsyncTask;
40 import android.os.Handler;
41 import android.preference.PreferenceManager;
42 import android.provider.Browser;
43 import android.provider.Settings;
44 import android.provider.Browser.BookmarkColumns;
45 import android.server.search.SearchableInfo;
46 import android.text.TextUtils;
47 import android.util.Log;
48 import android.util.TypedValue;
49
50 import com.android.common.Patterns;
51
52 import com.google.android.providers.GoogleSettings.Partner;
53
54 import java.io.File;
55 import java.io.FilenameFilter;
56 import java.util.Date;
57 import java.util.regex.Matcher;
58 import java.util.regex.Pattern;
59
60
61 public class BrowserProvider extends ContentProvider {
62
63     private SQLiteOpenHelper mOpenHelper;
64     private BackupManager mBackupManager;
65     private static final String sDatabaseName = "browser.db";
66     private static final String TAG = "BrowserProvider";
67     private static final String ORDER_BY = "visits DESC, date DESC";
68
69     private static final String PICASA_URL = "http://picasaweb.google.com/m/" +
70             "viewer?source=androidclient";
71
72     private static final String[] TABLE_NAMES = new String[] {
73         "bookmarks", "searches"
74     };
75     private static final String[] SUGGEST_PROJECTION = new String[] {
76             "_id", "url", "title", "bookmark"
77     };
78     private static final String SUGGEST_SELECTION =
79             "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
80                 + " OR title LIKE ?";
81     private String[] SUGGEST_ARGS = new String[5];
82
83     // shared suggestion array index, make sure to match COLUMNS
84     private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
85     private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
86     private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
87     private static final int SUGGEST_COLUMN_TEXT_2_ID = 4;
88     private static final int SUGGEST_COLUMN_ICON_1_ID = 5;
89     private static final int SUGGEST_COLUMN_ICON_2_ID = 6;
90     private static final int SUGGEST_COLUMN_QUERY_ID = 7;
91     private static final int SUGGEST_COLUMN_FORMAT = 8;
92     private static final int SUGGEST_COLUMN_INTENT_EXTRA_DATA = 9;
93
94     // shared suggestion columns
95     private static final String[] COLUMNS = new String[] {
96             "_id",
97             SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
98             SearchManager.SUGGEST_COLUMN_INTENT_DATA,
99             SearchManager.SUGGEST_COLUMN_TEXT_1,
100             SearchManager.SUGGEST_COLUMN_TEXT_2,
101             SearchManager.SUGGEST_COLUMN_ICON_1,
102             SearchManager.SUGGEST_COLUMN_ICON_2,
103             SearchManager.SUGGEST_COLUMN_QUERY,
104             SearchManager.SUGGEST_COLUMN_FORMAT,
105             SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA};
106
107     private static final int MAX_SUGGESTION_SHORT_ENTRIES = 3;
108     private static final int MAX_SUGGESTION_LONG_ENTRIES = 6;
109     private static final String MAX_SUGGESTION_LONG_ENTRIES_STRING =
110             Integer.valueOf(MAX_SUGGESTION_LONG_ENTRIES).toString();
111
112     // make sure that these match the index of TABLE_NAMES
113     private static final int URI_MATCH_BOOKMARKS = 0;
114     private static final int URI_MATCH_SEARCHES = 1;
115     // (id % 10) should match the table name index
116     private static final int URI_MATCH_BOOKMARKS_ID = 10;
117     private static final int URI_MATCH_SEARCHES_ID = 11;
118     //
119     private static final int URI_MATCH_SUGGEST = 20;
120     private static final int URI_MATCH_BOOKMARKS_SUGGEST = 21;
121
122     private static final UriMatcher URI_MATCHER;
123
124     static {
125         URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
126         URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS],
127                 URI_MATCH_BOOKMARKS);
128         URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/#",
129                 URI_MATCH_BOOKMARKS_ID);
130         URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES],
131                 URI_MATCH_SEARCHES);
132         URI_MATCHER.addURI("browser", TABLE_NAMES[URI_MATCH_SEARCHES] + "/#",
133                 URI_MATCH_SEARCHES_ID);
134         URI_MATCHER.addURI("browser", SearchManager.SUGGEST_URI_PATH_QUERY,
135                 URI_MATCH_SUGGEST);
136         URI_MATCHER.addURI("browser",
137                 TABLE_NAMES[URI_MATCH_BOOKMARKS] + "/" + SearchManager.SUGGEST_URI_PATH_QUERY,
138                 URI_MATCH_BOOKMARKS_SUGGEST);
139     }
140
141     // 1 -> 2 add cache table
142     // 2 -> 3 update history table
143     // 3 -> 4 add passwords table
144     // 4 -> 5 add settings table
145     // 5 -> 6 ?
146     // 6 -> 7 ?
147     // 7 -> 8 drop proxy table
148     // 8 -> 9 drop settings table
149     // 9 -> 10 add form_urls and form_data
150     // 10 -> 11 add searches table
151     // 11 -> 12 modify cache table
152     // 12 -> 13 modify cache table
153     // 13 -> 14 correspond with Google Bookmarks schema
154     // 14 -> 15 move couple of tables to either browser private database or webview database
155     // 15 -> 17 Set it up for the SearchManager
156     // 17 -> 18 Added favicon in bookmarks table for Home shortcuts
157     // 18 -> 19 Remove labels table
158     // 19 -> 20 Added thumbnail
159     // 20 -> 21 Added touch_icon
160     // 21 -> 22 Remove "clientid"
161     private static final int DATABASE_VERSION = 22;
162
163     // Regular expression which matches http://, followed by some stuff, followed by
164     // optionally a trailing slash, all matched as separate groups.
165     private static final Pattern STRIP_URL_PATTERN = Pattern.compile("^(http://)(.*?)(/$)?");
166
167     private SearchManager mSearchManager;
168
169     // The ID of the ColorStateList to be applied to urls of website suggestions, as derived from
170     // the current theme. This is not set until/unless beautifyUrl is called, at which point
171     // this variable caches the color value.
172     private static String mSearchUrlColorId;
173
174     public BrowserProvider() {
175     }
176
177
178     private static CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
179         StringBuffer sb = new StringBuffer();
180         int lastCharLoc = 0;
181
182         final String client_id = Partner.getString(context.getContentResolver(),
183                                                     Partner.CLIENT_ID, "android-google");
184
185         for (int i = 0; i < srcString.length(); ++i) {
186             char c = srcString.charAt(i);
187             if (c == '{') {
188                 sb.append(srcString.subSequence(lastCharLoc, i));
189                 lastCharLoc = i;
190           inner:
191                 for (int j = i; j < srcString.length(); ++j) {
192                     char k = srcString.charAt(j);
193                     if (k == '}') {
194                         String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
195                         if (propertyKeyValue.equals("CLIENT_ID")) {
196                             sb.append(client_id);
197                         } else {
198                             sb.append("unknown");
199                         }
200                         lastCharLoc = j + 1;
201                         i = j;
202                         break inner;
203                     }
204                 }
205             }
206         }
207         if (srcString.length() - lastCharLoc > 0) {
208             // Put on the tail, if there is one
209             sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
210         }
211         return sb;
212     }
213
214     private static class DatabaseHelper extends SQLiteOpenHelper {
215         private Context mContext;
216
217         public DatabaseHelper(Context context) {
218             super(context, sDatabaseName, null, DATABASE_VERSION);
219             mContext = context;
220         }
221
222         @Override
223         public void onCreate(SQLiteDatabase db) {
224             db.execSQL("CREATE TABLE bookmarks (" +
225                     "_id INTEGER PRIMARY KEY," +
226                     "title TEXT," +
227                     "url TEXT," +
228                     "visits INTEGER," +
229                     "date LONG," +
230                     "created LONG," +
231                     "description TEXT," +
232                     "bookmark INTEGER," +
233                     "favicon BLOB DEFAULT NULL," +
234                     "thumbnail BLOB DEFAULT NULL," +
235                     "touch_icon BLOB DEFAULT NULL" +
236                     ");");
237
238             final CharSequence[] bookmarks = mContext.getResources()
239                     .getTextArray(R.array.bookmarks);
240             int size = bookmarks.length;
241             try {
242                 for (int i = 0; i < size; i = i + 2) {
243                     CharSequence bookmarkDestination = replaceSystemPropertyInString(mContext, bookmarks[i + 1]);
244                     db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
245                             "date, created, bookmark)" + " VALUES('" +
246                             bookmarks[i] + "', '" + bookmarkDestination +
247                             "', 0, 0, 0, 1);");
248                 }
249             } catch (ArrayIndexOutOfBoundsException e) {
250             }
251
252             db.execSQL("CREATE TABLE searches (" +
253                     "_id INTEGER PRIMARY KEY," +
254                     "search TEXT," +
255                     "date LONG" +
256                     ");");
257         }
258
259         @Override
260         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
261             Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
262                     + newVersion);
263             if (oldVersion == 18) {
264                 db.execSQL("DROP TABLE IF EXISTS labels");
265             }
266             if (oldVersion <= 19) {
267                 db.execSQL("ALTER TABLE bookmarks ADD COLUMN thumbnail BLOB DEFAULT NULL;");
268             }
269             if (oldVersion < 21) {
270                 db.execSQL("ALTER TABLE bookmarks ADD COLUMN touch_icon BLOB DEFAULT NULL;");
271             }
272             if (oldVersion < 22) {
273                 db.execSQL("DELETE FROM bookmarks WHERE (bookmark = 0 AND url LIKE \"%.google.%client=ms-%\")");
274                 removeGears();
275             } else {
276                 db.execSQL("DROP TABLE IF EXISTS bookmarks");
277                 db.execSQL("DROP TABLE IF EXISTS searches");
278                 onCreate(db);
279             }
280         }
281
282         private void removeGears() {
283             AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
284                 public Void doInBackground(Void... unused) {
285                     String browserDataDirString = mContext.getApplicationInfo().dataDir;
286                     final String appPluginsDirString = "app_plugins";
287                     final String gearsPrefix = "gears";
288                     File appPluginsDir = new File(browserDataDirString + File.separator
289                             + appPluginsDirString);
290                     if (!appPluginsDir.exists()) {
291                         return null;
292                     }
293                     // Delete the Gears plugin files
294                     File[] gearsFiles = appPluginsDir.listFiles(new FilenameFilter() {
295                         public boolean accept(File dir, String filename) {
296                             return filename.startsWith(gearsPrefix);
297                         }
298                     });
299                     for (int i = 0; i < gearsFiles.length; ++i) {
300                         if (gearsFiles[i].isDirectory()) {
301                             deleteDirectory(gearsFiles[i]);
302                         } else {
303                             gearsFiles[i].delete();
304                         }
305                     }
306                     // Delete the Gears data files
307                     File gearsDataDir = new File(browserDataDirString + File.separator
308                             + gearsPrefix);
309                     if (!gearsDataDir.exists()) {
310                         return null;
311                     }
312                     deleteDirectory(gearsDataDir);
313                     return null;
314                 }
315
316                 private void deleteDirectory(File currentDir) {
317                     File[] files = currentDir.listFiles();
318                     for (int i = 0; i < files.length; ++i) {
319                         if (files[i].isDirectory()) {
320                             deleteDirectory(files[i]);
321                         }
322                         files[i].delete();
323                     }
324                     currentDir.delete();
325                 }
326             };
327
328             task.execute();
329         }
330     }
331
332     @Override
333     public boolean onCreate() {
334         final Context context = getContext();
335         mOpenHelper = new DatabaseHelper(context);
336         mBackupManager = new BackupManager(context);
337         // we added "picasa web album" into default bookmarks for version 19.
338         // To avoid erasing the bookmark table, we added it explicitly for
339         // version 18 and 19 as in the other cases, we will erase the table.
340         if (DATABASE_VERSION == 18 || DATABASE_VERSION == 19) {
341             SharedPreferences p = PreferenceManager
342                     .getDefaultSharedPreferences(context);
343             boolean fix = p.getBoolean("fix_picasa", true);
344             if (fix) {
345                 fixPicasaBookmark();
346                 Editor ed = p.edit();
347                 ed.putBoolean("fix_picasa", false);
348                 ed.commit();
349             }
350         }
351         mSearchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
352         mShowWebSuggestionsSettingChangeObserver
353             = new ShowWebSuggestionsSettingChangeObserver();
354         context.getContentResolver().registerContentObserver(
355                 Settings.System.getUriFor(
356                         Settings.System.SHOW_WEB_SUGGESTIONS),
357                 true, mShowWebSuggestionsSettingChangeObserver);
358         updateShowWebSuggestions();
359         return true;
360     }
361
362     /**
363      * This Observer will ensure that if the user changes the system
364      * setting of whether to display web suggestions, we will
365      * change accordingly.
366      */
367     /* package */ class ShowWebSuggestionsSettingChangeObserver
368             extends ContentObserver {
369         public ShowWebSuggestionsSettingChangeObserver() {
370             super(new Handler());
371         }
372
373         @Override
374         public void onChange(boolean selfChange) {
375             updateShowWebSuggestions();
376         }
377     }
378
379     private ShowWebSuggestionsSettingChangeObserver
380             mShowWebSuggestionsSettingChangeObserver;
381
382     // If non-null, then the system is set to show web suggestions,
383     // and this is the SearchableInfo to use to get them.
384     private SearchableInfo mSearchableInfo;
385
386     /**
387      * Check the system settings to see whether web suggestions are
388      * allowed.  If so, store the SearchableInfo to grab suggestions
389      * while the user is typing.
390      */
391     private void updateShowWebSuggestions() {
392         mSearchableInfo = null;
393         Context context = getContext();
394         if (Settings.System.getInt(context.getContentResolver(),
395                 Settings.System.SHOW_WEB_SUGGESTIONS,
396                 1 /* default on */) == 1) {
397             Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
398             intent.addCategory(Intent.CATEGORY_DEFAULT);
399             ResolveInfo info = context.getPackageManager().resolveActivity(
400                     intent, PackageManager.MATCH_DEFAULT_ONLY);
401             if (info != null) {
402                 ComponentName googleSearchComponent =
403                         new ComponentName(info.activityInfo.packageName,
404                                 info.activityInfo.name);
405                 mSearchableInfo = mSearchManager.getSearchableInfo(
406                         googleSearchComponent, false);
407             }
408         }
409     }
410
411     private void fixPicasaBookmark() {
412         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
413         Cursor cursor = db.rawQuery("SELECT _id FROM bookmarks WHERE " +
414                 "bookmark = 1 AND url = ?", new String[] { PICASA_URL });
415         try {
416             if (!cursor.moveToFirst()) {
417                 // set "created" so that it will be on the top of the list
418                 db.execSQL("INSERT INTO bookmarks (title, url, visits, " +
419                         "date, created, bookmark)" + " VALUES('" +
420                         getContext().getString(R.string.picasa) + "', '"
421                         + PICASA_URL + "', 0, 0, " + new Date().getTime()
422                         + ", 1);");
423             }
424         } finally {
425             if (cursor != null) {
426                 cursor.close();
427             }
428         }
429     }
430
431     /*
432      * Subclass AbstractCursor so we can combine multiple Cursors and add
433      * "Google Search".
434      * Here are the rules.
435      * 1. We only have MAX_SUGGESTION_LONG_ENTRIES in the list plus
436      *      "Google Search";
437      * 2. If bookmark/history entries are less than
438      *      (MAX_SUGGESTION_SHORT_ENTRIES -1), we include Google suggest.
439      */
440     private class MySuggestionCursor extends AbstractCursor {
441         private Cursor  mHistoryCursor;
442         private Cursor  mSuggestCursor;
443         private int     mHistoryCount;
444         private int     mSuggestionCount;
445         private boolean mBeyondCursor;
446         private String  mString;
447         private int     mSuggestText1Id;
448         private int     mSuggestText2Id;
449         private int     mSuggestQueryId;
450         private int     mSuggestIntentExtraDataId;
451
452         public MySuggestionCursor(Cursor hc, Cursor sc, String string) {
453             mHistoryCursor = hc;
454             mSuggestCursor = sc;
455             mHistoryCount = hc.getCount();
456             mSuggestionCount = sc != null ? sc.getCount() : 0;
457             if (mSuggestionCount > (MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount)) {
458                 mSuggestionCount = MAX_SUGGESTION_LONG_ENTRIES - mHistoryCount;
459             }
460             mString = string;
461             mBeyondCursor = false;
462
463             // Some web suggest providers only give suggestions and have no description string for
464             // items. The order of the result columns may be different as well. So retrieve the
465             // column indices for the fields we need now and check before using below.
466             if (mSuggestCursor == null) {
467                 mSuggestText1Id = -1;
468                 mSuggestText2Id = -1;
469                 mSuggestQueryId = -1;
470                 mSuggestIntentExtraDataId = -1;
471             } else {
472                 mSuggestText1Id = mSuggestCursor.getColumnIndex(
473                                 SearchManager.SUGGEST_COLUMN_TEXT_1);
474                 mSuggestText2Id = mSuggestCursor.getColumnIndex(
475                                 SearchManager.SUGGEST_COLUMN_TEXT_2);
476                 mSuggestQueryId = mSuggestCursor.getColumnIndex(
477                                 SearchManager.SUGGEST_COLUMN_QUERY);
478                 mSuggestIntentExtraDataId = mSuggestCursor.getColumnIndex(
479                                 SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
480             }
481         }
482
483         @Override
484         public boolean onMove(int oldPosition, int newPosition) {
485             if (mHistoryCursor == null) {
486                 return false;
487             }
488             if (mHistoryCount > newPosition) {
489                 mHistoryCursor.moveToPosition(newPosition);
490                 mBeyondCursor = false;
491             } else if (mHistoryCount + mSuggestionCount > newPosition) {
492                 mSuggestCursor.moveToPosition(newPosition - mHistoryCount);
493                 mBeyondCursor = false;
494             } else {
495                 mBeyondCursor = true;
496             }
497             return true;
498         }
499
500         @Override
501         public int getCount() {
502             if (mString.length() > 0) {
503                 return mHistoryCount + mSuggestionCount + 1;
504             } else {
505                 return mHistoryCount + mSuggestionCount;
506             }
507         }
508
509         @Override
510         public String[] getColumnNames() {
511             return COLUMNS;
512         }
513
514         @Override
515         public String getString(int columnIndex) {
516             if ((mPos != -1 && mHistoryCursor != null)) {
517                 switch(columnIndex) {
518                     case SUGGEST_COLUMN_INTENT_ACTION_ID:
519                         if (mHistoryCount > mPos) {
520                             return Intent.ACTION_VIEW;
521                         } else {
522                             return Intent.ACTION_SEARCH;
523                         }
524
525                     case SUGGEST_COLUMN_INTENT_DATA_ID:
526                         if (mHistoryCount > mPos) {
527                             return mHistoryCursor.getString(1);
528                         } else {
529                             return null;
530                         }
531
532                     case SUGGEST_COLUMN_TEXT_1_ID:
533                         if (mHistoryCount > mPos) {
534                             return getHistoryTitle();
535                         } else if (!mBeyondCursor) {
536                             if (mSuggestText1Id == -1) return null;
537                             return mSuggestCursor.getString(mSuggestText1Id);
538                         } else {
539                             return mString;
540                         }
541
542                     case SUGGEST_COLUMN_TEXT_2_ID:
543                         if (mHistoryCount > mPos) {
544                             return getHistorySubtitle();
545                         } else if (!mBeyondCursor) {
546                             if (mSuggestText2Id == -1) return null;
547                             return mSuggestCursor.getString(mSuggestText2Id);
548                         } else {
549                             return getContext().getString(R.string.search_the_web);
550                         }
551
552                     case SUGGEST_COLUMN_ICON_1_ID:
553                         if (mHistoryCount > mPos) {
554                             if (mHistoryCursor.getInt(3) == 1) {
555                                 return Integer.valueOf(
556                                         R.drawable.ic_search_category_bookmark)
557                                         .toString();
558                             } else {
559                                 return Integer.valueOf(
560                                         R.drawable.ic_search_category_history)
561                                         .toString();
562                             }
563                         } else {
564                             return Integer.valueOf(
565                                     R.drawable.ic_search_category_suggest)
566                                     .toString();
567                         }
568
569                     case SUGGEST_COLUMN_ICON_2_ID:
570                         return "0";
571
572                     case SUGGEST_COLUMN_QUERY_ID:
573                         if (mHistoryCount > mPos) {
574                             // Return the url in the intent query column. This is ignored
575                             // within the browser because our searchable is set to
576                             // android:searchMode="queryRewriteFromData", but it is used by
577                             // global search for query rewriting.
578                             return mHistoryCursor.getString(1);
579                         } else if (!mBeyondCursor) {
580                             if (mSuggestQueryId == -1) return null;
581                             return mSuggestCursor.getString(mSuggestQueryId);
582                         } else {
583                             return mString;
584                         }
585
586                     case SUGGEST_COLUMN_FORMAT:
587                         return "html";
588
589                     case SUGGEST_COLUMN_INTENT_EXTRA_DATA:
590                         if (mHistoryCount > mPos) {
591                             return null;
592                         } else if (!mBeyondCursor) {
593                             if (mSuggestIntentExtraDataId == -1) return null;
594                             return mSuggestCursor.getString(mSuggestIntentExtraDataId);
595                         } else {
596                             return null;
597                         }
598                 }
599             }
600             return null;
601         }
602
603         @Override
604         public double getDouble(int column) {
605             throw new UnsupportedOperationException();
606         }
607
608         @Override
609         public float getFloat(int column) {
610             throw new UnsupportedOperationException();
611         }
612
613         @Override
614         public int getInt(int column) {
615             throw new UnsupportedOperationException();
616         }
617
618         @Override
619         public long getLong(int column) {
620             if ((mPos != -1) && column == 0) {
621                 return mPos;        // use row# as the _Id
622             }
623             throw new UnsupportedOperationException();
624         }
625
626         @Override
627         public short getShort(int column) {
628             throw new UnsupportedOperationException();
629         }
630
631         @Override
632         public boolean isNull(int column) {
633             throw new UnsupportedOperationException();
634         }
635
636         // TODO Temporary change, finalize after jq's changes go in
637         public void deactivate() {
638             if (mHistoryCursor != null) {
639                 mHistoryCursor.deactivate();
640             }
641             if (mSuggestCursor != null) {
642                 mSuggestCursor.deactivate();
643             }
644             super.deactivate();
645         }
646
647         public boolean requery() {
648             return (mHistoryCursor != null ? mHistoryCursor.requery() : false) |
649                     (mSuggestCursor != null ? mSuggestCursor.requery() : false);
650         }
651
652         // TODO Temporary change, finalize after jq's changes go in
653         public void close() {
654             super.close();
655             if (mHistoryCursor != null) {
656                 mHistoryCursor.close();
657                 mHistoryCursor = null;
658             }
659             if (mSuggestCursor != null) {
660                 mSuggestCursor.close();
661                 mSuggestCursor = null;
662             }
663         }
664
665         /**
666          * Provides the title (text line 1) for a browser suggestion, which should be the
667          * webpage title. If the webpage title is empty, returns the stripped url instead.
668          *
669          * @return the title string to use
670          */
671         private String getHistoryTitle() {
672             String title = mHistoryCursor.getString(2 /* webpage title */);
673             if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
674                 title = beautifyUrl(mHistoryCursor.getString(1 /* url */));
675             }
676             return title;
677         }
678
679         /**
680          * Provides the subtitle (text line 2) for a browser suggestion, which should be the
681          * webpage url. If the webpage title is empty, then the url should go in the title
682          * instead, and the subtitle should be empty, so this would return null.
683          *
684          * @return the subtitle string to use, or null if none
685          */
686         private String getHistorySubtitle() {
687             String title = mHistoryCursor.getString(2 /* webpage title */);
688             if (TextUtils.isEmpty(title) || TextUtils.getTrimmedLength(title) == 0) {
689                 return null;
690             } else {
691                 return beautifyUrl(mHistoryCursor.getString(1 /* url */));
692             }
693         }
694
695         /**
696          * Strips "http://" from the beginning of a url and "/" from the end,
697          * and adds html formatting to make it green.
698          */
699         private String beautifyUrl(String url) {
700             if (mSearchUrlColorId == null) {
701                 // Get the color used for this purpose from the current theme.
702                 TypedValue colorValue = new TypedValue();
703                 getContext().getTheme().resolveAttribute(
704                         com.android.internal.R.attr.textColorSearchUrl, colorValue, true);
705                 mSearchUrlColorId = Integer.toString(colorValue.resourceId);
706             }
707
708             return "<font color=\"@" + mSearchUrlColorId + "\">" + stripUrl(url) + "</font>";
709         }
710     }
711
712     @Override
713     public Cursor query(Uri url, String[] projectionIn, String selection,
714             String[] selectionArgs, String sortOrder)
715             throws IllegalStateException {
716         SQLiteDatabase db = mOpenHelper.getReadableDatabase();
717
718         int match = URI_MATCHER.match(url);
719         if (match == -1) {
720             throw new IllegalArgumentException("Unknown URL");
721         }
722
723         if (match == URI_MATCH_SUGGEST || match == URI_MATCH_BOOKMARKS_SUGGEST) {
724             String suggestSelection;
725             String [] myArgs;
726             if (selectionArgs[0] == null || selectionArgs[0].equals("")) {
727                 suggestSelection = null;
728                 myArgs = null;
729             } else {
730                 String like = selectionArgs[0] + "%";
731                 if (selectionArgs[0].startsWith("http")
732                         || selectionArgs[0].startsWith("file")) {
733                     myArgs = new String[1];
734                     myArgs[0] = like;
735                     suggestSelection = selection;
736                 } else {
737                     SUGGEST_ARGS[0] = "http://" + like;
738                     SUGGEST_ARGS[1] = "http://www." + like;
739                     SUGGEST_ARGS[2] = "https://" + like;
740                     SUGGEST_ARGS[3] = "https://www." + like;
741                     // To match against titles.
742                     SUGGEST_ARGS[4] = like;
743                     myArgs = SUGGEST_ARGS;
744                     suggestSelection = SUGGEST_SELECTION;
745                 }
746             }
747
748             Cursor c = db.query(TABLE_NAMES[URI_MATCH_BOOKMARKS],
749                     SUGGEST_PROJECTION, suggestSelection, myArgs, null, null,
750                     ORDER_BY, MAX_SUGGESTION_LONG_ENTRIES_STRING);
751
752             if (match == URI_MATCH_BOOKMARKS_SUGGEST
753                     || Patterns.WEB_URL.matcher(selectionArgs[0]).matches()) {
754                 return new MySuggestionCursor(c, null, "");
755             } else {
756                 // get Google suggest if there is still space in the list
757                 if (myArgs != null && myArgs.length > 1
758                         && mSearchableInfo != null
759                         && c.getCount() < (MAX_SUGGESTION_SHORT_ENTRIES - 1)) {
760                     Cursor sc = mSearchManager.getSuggestions(mSearchableInfo, selectionArgs[0]);
761                     return new MySuggestionCursor(c, sc, selectionArgs[0]);
762                 }
763                 return new MySuggestionCursor(c, null, selectionArgs[0]);
764             }
765         }
766
767         String[] projection = null;
768         if (projectionIn != null && projectionIn.length > 0) {
769             projection = new String[projectionIn.length + 1];
770             System.arraycopy(projectionIn, 0, projection, 0, projectionIn.length);
771             projection[projectionIn.length] = "_id AS _id";
772         }
773
774         StringBuilder whereClause = new StringBuilder(256);
775         if (match == URI_MATCH_BOOKMARKS_ID || match == URI_MATCH_SEARCHES_ID) {
776             whereClause.append("(_id = ").append(url.getPathSegments().get(1))
777                     .append(")");
778         }
779
780         // Tack on the user's selection, if present
781         if (selection != null && selection.length() > 0) {
782             if (whereClause.length() > 0) {
783                 whereClause.append(" AND ");
784             }
785
786             whereClause.append('(');
787             whereClause.append(selection);
788             whereClause.append(')');
789         }
790         Cursor c = db.query(TABLE_NAMES[match % 10], projection,
791                 whereClause.toString(), selectionArgs, null, null, sortOrder,
792                 null);
793         c.setNotificationUri(getContext().getContentResolver(), url);
794         return c;
795     }
796
797     @Override
798     public String getType(Uri url) {
799         int match = URI_MATCHER.match(url);
800         switch (match) {
801             case URI_MATCH_BOOKMARKS:
802                 return "vnd.android.cursor.dir/bookmark";
803
804             case URI_MATCH_BOOKMARKS_ID:
805                 return "vnd.android.cursor.item/bookmark";
806
807             case URI_MATCH_SEARCHES:
808                 return "vnd.android.cursor.dir/searches";
809
810             case URI_MATCH_SEARCHES_ID:
811                 return "vnd.android.cursor.item/searches";
812
813             case URI_MATCH_SUGGEST:
814                 return SearchManager.SUGGEST_MIME_TYPE;
815
816             default:
817                 throw new IllegalArgumentException("Unknown URL");
818         }
819     }
820
821     @Override
822     public Uri insert(Uri url, ContentValues initialValues) {
823         boolean isBookmarkTable = false;
824         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
825
826         int match = URI_MATCHER.match(url);
827         Uri uri = null;
828         switch (match) {
829             case URI_MATCH_BOOKMARKS: {
830                 // Insert into the bookmarks table
831                 long rowID = db.insert(TABLE_NAMES[URI_MATCH_BOOKMARKS], "url",
832                         initialValues);
833                 if (rowID > 0) {
834                     uri = ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
835                             rowID);
836                 }
837                 isBookmarkTable = true;
838                 break;
839             }
840
841             case URI_MATCH_SEARCHES: {
842                 // Insert into the searches table
843                 long rowID = db.insert(TABLE_NAMES[URI_MATCH_SEARCHES], "url",
844                         initialValues);
845                 if (rowID > 0) {
846                     uri = ContentUris.withAppendedId(Browser.SEARCHES_URI,
847                             rowID);
848                 }
849                 break;
850             }
851
852             default:
853                 throw new IllegalArgumentException("Unknown URL");
854         }
855
856         if (uri == null) {
857             throw new IllegalArgumentException("Unknown URL");
858         }
859         getContext().getContentResolver().notifyChange(uri, null);
860
861         // Back up the new bookmark set if we just inserted one.
862         // A row created when bookmarks are added from scratch will have
863         // bookmark=1 in the initial value set.
864         if (isBookmarkTable
865                 && initialValues.containsKey(BookmarkColumns.BOOKMARK)
866                 && initialValues.getAsInteger(BookmarkColumns.BOOKMARK) != 0) {
867             mBackupManager.dataChanged();
868         }
869         return uri;
870     }
871
872     @Override
873     public int delete(Uri url, String where, String[] whereArgs) {
874         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
875
876         int match = URI_MATCHER.match(url);
877         if (match == -1 || match == URI_MATCH_SUGGEST) {
878             throw new IllegalArgumentException("Unknown URL");
879         }
880
881         // need to know whether it's the bookmarks table for a couple of reasons
882         boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
883         String id = null;
884
885         if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
886             StringBuilder sb = new StringBuilder();
887             if (where != null && where.length() > 0) {
888                 sb.append("( ");
889                 sb.append(where);
890                 sb.append(" ) AND ");
891             }
892             id = url.getPathSegments().get(1);
893             sb.append("_id = ");
894             sb.append(id);
895             where = sb.toString();
896         }
897
898         ContentResolver cr = getContext().getContentResolver();
899
900         // we'lll need to back up the bookmark set if we are about to delete one
901         if (isBookmarkTable) {
902             Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
903                     new String[] { BookmarkColumns.BOOKMARK },
904                     "_id = " + id, null, null);
905             if (cursor.moveToNext()) {
906                 if (cursor.getInt(0) != 0) {
907                     // yep, this record is a bookmark
908                     mBackupManager.dataChanged();
909                 }
910             }
911             cursor.close();
912         }
913
914         int count = db.delete(TABLE_NAMES[match % 10], where, whereArgs);
915         cr.notifyChange(url, null);
916         return count;
917     }
918
919     @Override
920     public int update(Uri url, ContentValues values, String where,
921             String[] whereArgs) {
922         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
923
924         int match = URI_MATCHER.match(url);
925         if (match == -1 || match == URI_MATCH_SUGGEST) {
926             throw new IllegalArgumentException("Unknown URL");
927         }
928
929         String id = null;
930         boolean isBookmarkTable = (match == URI_MATCH_BOOKMARKS_ID);
931         boolean changingBookmarks = false;
932
933         if (isBookmarkTable || match == URI_MATCH_SEARCHES_ID) {
934             StringBuilder sb = new StringBuilder();
935             if (where != null && where.length() > 0) {
936                 sb.append("( ");
937                 sb.append(where);
938                 sb.append(" ) AND ");
939             }
940             id = url.getPathSegments().get(1);
941             sb.append("_id = ");
942             sb.append(id);
943             where = sb.toString();
944         }
945
946         ContentResolver cr = getContext().getContentResolver();
947
948         // Not all bookmark-table updates should be backed up.  Look to see
949         // whether we changed the title, url, or "is a bookmark" state, and
950         // request a backup if so.
951         if (isBookmarkTable) {
952             // Alterations to the bookmark field inherently change the bookmark
953             // set, so we don't need to query the record; we know a priori that
954             // we will need to back up this change.
955             if (values.containsKey(BookmarkColumns.BOOKMARK)) {
956                 changingBookmarks = true;
957             }
958             // changing the title or URL of a bookmark record requires a backup,
959             // but we don't know wether such an update is on a bookmark without
960             // querying the record
961             if (!changingBookmarks &&
962                     (values.containsKey(BookmarkColumns.TITLE)
963                      || values.containsKey(BookmarkColumns.URL))) {
964                 // when isBookmarkTable is true, the 'id' var was assigned above
965                 Cursor cursor = cr.query(Browser.BOOKMARKS_URI,
966                         new String[] { BookmarkColumns.BOOKMARK },
967                         "_id = " + id, null, null);
968                 if (cursor.moveToNext()) {
969                     changingBookmarks = (cursor.getInt(0) != 0);
970                 }
971                 cursor.close();
972             }
973
974             // if this *is* a bookmark row we're altering, we need to back it up.
975             if (changingBookmarks) {
976                 mBackupManager.dataChanged();
977             }
978         }
979
980         int ret = db.update(TABLE_NAMES[match % 10], values, where, whereArgs);
981         cr.notifyChange(url, null);
982         return ret;
983     }
984
985     /**
986      * Strips the provided url of preceding "http://" and any trailing "/". Does not
987      * strip "https://". If the provided string cannot be stripped, the original string
988      * is returned.
989      *
990      * TODO: Put this in TextUtils to be used by other packages doing something similar.
991      *
992      * @param url a url to strip, like "http://www.google.com/"
993      * @return a stripped url like "www.google.com", or the original string if it could
994      *         not be stripped
995      */
996     private static String stripUrl(String url) {
997         if (url == null) return null;
998         Matcher m = STRIP_URL_PATTERN.matcher(url);
999         if (m.matches() && m.groupCount() == 3) {
1000             return m.group(2);
1001         } else {
1002             return url;
1003         }
1004     }
1005
1006 }