OSDN Git Service

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