OSDN Git Service

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