/WebVox/src/com/marvin/webvox/BrowserProvider.java

http://eyes-free.googlecode.com/ · Java · 1006 lines · 739 code · 108 blank · 159 comment · 182 complexity · cb5829d625d624720df6fdbf1471460e MD5 · raw file

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