OSDN Git Service

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