OSDN Git Service

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