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