OSDN Git Service

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