Browser.java revision dcf19a8d34d85255184bac6ac5083d3d68ed5953
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
17package android.provider;
18
19import android.content.ContentResolver;
20import android.content.ContentValues;
21import android.content.Context;
22import android.content.Intent;
23import android.database.Cursor;
24import android.database.DatabaseUtils;
25import android.net.Uri;
26import android.util.Log;
27import android.webkit.WebIconDatabase;
28
29import java.util.Date;
30
31public class Browser {
32    private static final String LOGTAG = "browser";
33    public static final Uri BOOKMARKS_URI =
34        Uri.parse("content://browser/bookmarks");
35
36    /**
37     * The inline scheme to show embedded content in a browser.
38     * @hide
39     */
40    public static final Uri INLINE_URI = Uri.parse("inline:");
41
42    /**
43     * The name of extra data when starting Browser with ACTION_VIEW or
44     * ACTION_SEARCH intent.
45     * <p>
46     * The value should be an integer between 0 and 1000. If not set or set to
47     * 0, the Browser will use default. If set to 100, the Browser will start
48     * with 100%.
49     */
50    public static final String INITIAL_ZOOM_LEVEL = "browser.initialZoomLevel";
51
52    /**
53     * The name of the extra data when starting the Browser from another
54     * application.
55     * <p>
56     * The value is a unique identification string that will be used to
57     * indentify the calling application. The Browser will attempt to reuse the
58     * same window each time the application launches the Browser with the same
59     * identifier.
60     */
61    public static final String EXTRA_APPLICATION_ID =
62        "com.android.browser.application_id";
63
64    /**
65     * The content to be rendered when url's scheme is inline.
66     * @hide
67     */
68    public static final String EXTRA_INLINE_CONTENT ="com.android.browser.inline.content";
69
70    /**
71     * The encoding of the inlined content for inline scheme.
72     * @hide
73     */
74    public static final String EXTRA_INLINE_ENCODING ="com.android.browser.inline.encoding";
75
76    /**
77     * The url used when the inline content is falied to render.
78     * @hide
79     */
80    public static final String EXTRA_INLINE_FAILURL ="com.android.browser.inline.failurl";
81
82    /**
83     * The name of the extra data in the VIEW intent. The data is in boolean.
84     * <p>
85     * If the Browser is handling the intent and the setting for
86     * USE_LOCATION_FOR_SERVICES is allow, the Browser will send the location in
87     * the POST data if this extra data is presented and it is true.
88     * <p>
89     * pending api approval
90     * @hide
91     */
92    public static final String EXTRA_APPEND_LOCATION = "com.android.browser.append_location";
93
94    /**
95     * The name of the extra data in the VIEW intent. The data is in the format of
96     * a byte array.
97     * <p>
98     * Any value sent here will be passed in the http request to the provided url as post data.
99     * <p>
100     * pending api approval
101     * @hide
102     */
103    public static final String EXTRA_POST_DATA = "com.android.browser.post_data";
104
105    /* if you change column order you must also change indices
106       below */
107    public static final String[] HISTORY_PROJECTION = new String[] {
108        BookmarkColumns._ID, BookmarkColumns.URL, BookmarkColumns.VISITS,
109        BookmarkColumns.DATE, BookmarkColumns.BOOKMARK, BookmarkColumns.TITLE,
110        BookmarkColumns.FAVICON, BookmarkColumns.THUMBNAIL,
111        BookmarkColumns.TOUCH_ICON, BookmarkColumns.USER_ENTERED };
112
113    /* these indices dependent on HISTORY_PROJECTION */
114    public static final int HISTORY_PROJECTION_ID_INDEX = 0;
115    public static final int HISTORY_PROJECTION_URL_INDEX = 1;
116    public static final int HISTORY_PROJECTION_VISITS_INDEX = 2;
117    public static final int HISTORY_PROJECTION_DATE_INDEX = 3;
118    public static final int HISTORY_PROJECTION_BOOKMARK_INDEX = 4;
119    public static final int HISTORY_PROJECTION_TITLE_INDEX = 5;
120    public static final int HISTORY_PROJECTION_FAVICON_INDEX = 6;
121    /**
122     * @hide
123     */
124    public static final int HISTORY_PROJECTION_THUMBNAIL_INDEX = 7;
125    /**
126     * @hide
127     */
128    public static final int HISTORY_PROJECTION_TOUCH_ICON_INDEX = 8;
129
130    /* columns needed to determine whether to truncate history */
131    public static final String[] TRUNCATE_HISTORY_PROJECTION = new String[] {
132        BookmarkColumns._ID, BookmarkColumns.DATE, };
133    public static final int TRUNCATE_HISTORY_PROJECTION_ID_INDEX = 0;
134
135    /* truncate this many history items at a time */
136    public static final int TRUNCATE_N_OLDEST = 5;
137
138    public static final Uri SEARCHES_URI =
139        Uri.parse("content://browser/searches");
140
141    /* if you change column order you must also change indices
142       below */
143    public static final String[] SEARCHES_PROJECTION = new String[] {
144        SearchColumns._ID, SearchColumns.SEARCH, SearchColumns.DATE };
145
146    /* these indices dependent on SEARCHES_PROJECTION */
147    public static final int SEARCHES_PROJECTION_SEARCH_INDEX = 1;
148    public static final int SEARCHES_PROJECTION_DATE_INDEX = 2;
149
150    private static final String SEARCHES_WHERE_CLAUSE = "search = ?";
151
152    /* Set a cap on the count of history items in the history/bookmark
153       table, to prevent db and layout operations from dragging to a
154       crawl.  Revisit this cap when/if db/layout performance
155       improvements are made.  Note: this does not affect bookmark
156       entries -- if the user wants more bookmarks than the cap, they
157       get them. */
158    private static final int MAX_HISTORY_COUNT = 250;
159
160    /**
161     *  Open the AddBookmark activity to save a bookmark.  Launch with
162     *  and/or url, which can be edited by the user before saving.
163     *  @param c        Context used to launch the AddBookmark activity.
164     *  @param title    Title for the bookmark. Can be null or empty string.
165     *  @param url      Url for the bookmark. Can be null or empty string.
166     */
167    public static final void saveBookmark(Context c,
168                                          String title,
169                                          String url) {
170        Intent i = new Intent(Intent.ACTION_INSERT, Browser.BOOKMARKS_URI);
171        i.putExtra("title", title);
172        i.putExtra("url", url);
173        c.startActivity(i);
174    }
175
176    /**
177     * Stores a String extra in an {@link Intent} representing the title of a
178     * page to share.  When receiving an {@link Intent#ACTION_SEND} from the
179     * Browser, use this to access the title.
180     * @hide
181     */
182    public final static String EXTRA_SHARE_TITLE = "share_title";
183
184    /**
185     * Stores a Bitmap extra in an {@link Intent} representing the screenshot of
186     * a page to share.  When receiving an {@link Intent#ACTION_SEND} from the
187     * Browser, use this to access the screenshot.
188     * @hide
189     */
190    public final static String EXTRA_SHARE_SCREENSHOT = "share_screenshot";
191
192    /**
193     * Stores a Bitmap extra in an {@link Intent} representing the favicon of a
194     * page to share.  When receiving an {@link Intent#ACTION_SEND} from the
195     * Browser, use this to access the favicon.
196     * @hide
197     */
198    public final static String EXTRA_SHARE_FAVICON = "share_favicon";
199
200    public static final void sendString(Context c, String s) {
201        sendString(c, s, c.getString(com.android.internal.R.string.sendText));
202    }
203
204    /**
205     *  Find an application to handle the given string and, if found, invoke
206     *  it with the given string as a parameter.
207     *  @param c Context used to launch the new activity.
208     *  @param stringToSend The string to be handled.
209     *  @param chooserDialogTitle The title of the dialog that allows the user
210     *  to select between multiple applications that are all capable of handling
211     *  the string.
212     *  @hide pending API council approval
213     */
214    public static final void sendString(Context c,
215                                        String stringToSend,
216                                        String chooserDialogTitle) {
217        Intent send = new Intent(Intent.ACTION_SEND);
218        send.setType("text/plain");
219        send.putExtra(Intent.EXTRA_TEXT, stringToSend);
220
221        try {
222            c.startActivity(Intent.createChooser(send, chooserDialogTitle));
223        } catch(android.content.ActivityNotFoundException ex) {
224            // if no app handles it, do nothing
225        }
226    }
227
228    /**
229     *  Return a cursor pointing to a list of all the bookmarks.
230     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
231     *  @param cr   The ContentResolver used to access the database.
232     */
233    public static final Cursor getAllBookmarks(ContentResolver cr) throws
234            IllegalStateException {
235        return cr.query(BOOKMARKS_URI,
236                new String[] { BookmarkColumns.URL },
237                "bookmark = 1", null, null);
238    }
239
240    /**
241     *  Return a cursor pointing to a list of all visited site urls.
242     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
243     *  @param cr   The ContentResolver used to access the database.
244     */
245    public static final Cursor getAllVisitedUrls(ContentResolver cr) throws
246            IllegalStateException {
247        return cr.query(BOOKMARKS_URI,
248                new String[] { BookmarkColumns.URL }, null, null, null);
249    }
250
251    /**
252     *  Update the visited history to acknowledge that a site has been
253     *  visited.
254     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
255     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
256     *  @param cr   The ContentResolver used to access the database.
257     *  @param url  The site being visited.
258     *  @param real If true, this is an actual visit, and should add to the
259     *              number of visits.  If false, the user entered it manually.
260     */
261    public static final void updateVisitedHistory(ContentResolver cr,
262                                                  String url, boolean real) {
263        long now = new Date().getTime();
264        try {
265            StringBuilder sb = new StringBuilder(BookmarkColumns.URL + " = ");
266            DatabaseUtils.appendEscapedSQLString(sb, url);
267            Cursor c = cr.query(
268                    BOOKMARKS_URI,
269                    HISTORY_PROJECTION,
270                    sb.toString(),
271                    null,
272                    null);
273            /* We should only get one answer that is exactly the same. */
274            if (c.moveToFirst()) {
275                ContentValues map = new ContentValues();
276                if (real) {
277                    map.put(BookmarkColumns.VISITS, c
278                            .getInt(HISTORY_PROJECTION_VISITS_INDEX) + 1);
279                } else {
280                    map.put(BookmarkColumns.USER_ENTERED, 1);
281                }
282                map.put(BookmarkColumns.DATE, now);
283                cr.update(BOOKMARKS_URI, map, "_id = " + c.getInt(0), null);
284            } else {
285                truncateHistory(cr);
286                ContentValues map = new ContentValues();
287                int visits;
288                int user_entered;
289                if (real) {
290                    visits = 1;
291                    user_entered = 0;
292                } else {
293                    visits = 0;
294                    user_entered = 1;
295                }
296                map.put(BookmarkColumns.URL, url);
297                map.put(BookmarkColumns.VISITS, visits);
298                map.put(BookmarkColumns.DATE, now);
299                map.put(BookmarkColumns.BOOKMARK, 0);
300                map.put(BookmarkColumns.TITLE, url);
301                map.put(BookmarkColumns.CREATED, 0);
302                map.put(BookmarkColumns.USER_ENTERED, user_entered);
303                cr.insert(BOOKMARKS_URI, map);
304            }
305            c.deactivate();
306        } catch (IllegalStateException e) {
307            return;
308        }
309    }
310
311    /**
312     *  Returns all the URLs in the history.
313     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
314     *  @param cr   The ContentResolver used to access the database.
315     *  @hide pending API council approval
316     */
317    public static final String[] getVisitedHistory(ContentResolver cr) {
318        try {
319            String[] projection = new String[] {
320                "url"
321            };
322            Cursor c = cr.query(BOOKMARKS_URI, projection, "visits > 0", null,
323                    null);
324            String[] str = new String[c.getCount()];
325            int i = 0;
326            while (c.moveToNext()) {
327                str[i] = c.getString(0);
328                i++;
329            }
330            c.deactivate();
331            return str;
332        } catch (IllegalStateException e) {
333            return new String[0];
334        }
335    }
336
337    /**
338     * If there are more than MAX_HISTORY_COUNT non-bookmark history
339     * items in the bookmark/history table, delete TRUNCATE_N_OLDEST
340     * of them.  This is used to keep our history table to a
341     * reasonable size.  Note: it does not prune bookmarks.  If the
342     * user wants 1000 bookmarks, the user gets 1000 bookmarks.
343     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
344     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
345     *
346     * @param cr The ContentResolver used to access the database.
347     */
348    public static final void truncateHistory(ContentResolver cr) {
349        try {
350            // Select non-bookmark history, ordered by date
351            Cursor c = cr.query(
352                    BOOKMARKS_URI,
353                    TRUNCATE_HISTORY_PROJECTION,
354                    "bookmark = 0",
355                    null,
356                    BookmarkColumns.DATE);
357            // Log.v(LOGTAG, "history count " + c.count());
358            if (c.moveToFirst() && c.getCount() >= MAX_HISTORY_COUNT) {
359                /* eliminate oldest history items */
360                for (int i = 0; i < TRUNCATE_N_OLDEST; i++) {
361                    // Log.v(LOGTAG, "truncate history " +
362                    // c.getInt(TRUNCATE_HISTORY_PROJECTION_ID_INDEX));
363                    deleteHistoryWhere(
364                            cr, "_id = " +
365                            c.getInt(TRUNCATE_HISTORY_PROJECTION_ID_INDEX));
366                    if (!c.moveToNext()) break;
367                }
368            }
369            c.deactivate();
370        } catch (IllegalStateException e) {
371            Log.e(LOGTAG, "truncateHistory", e);
372            return;
373        }
374    }
375
376    /**
377     * Returns whether there is any history to clear.
378     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
379     * @param cr   The ContentResolver used to access the database.
380     * @return boolean  True if the history can be cleared.
381     */
382    public static final boolean canClearHistory(ContentResolver cr) {
383        try {
384            Cursor c = cr.query(
385                BOOKMARKS_URI,
386                new String [] { BookmarkColumns._ID,
387                                BookmarkColumns.BOOKMARK,
388                                BookmarkColumns.VISITS },
389                "bookmark = 0 OR visits > 0",
390                null,
391                null
392                );
393            boolean ret = c.moveToFirst();
394            c.deactivate();
395            return ret;
396        } catch (IllegalStateException e) {
397            return false;
398        }
399    }
400
401    /**
402     *  Delete all entries from the bookmarks/history table which are
403     *  not bookmarks.  Also set all visited bookmarks to unvisited.
404     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
405     *  @param cr   The ContentResolver used to access the database.
406     */
407    public static final void clearHistory(ContentResolver cr) {
408        deleteHistoryWhere(cr, null);
409    }
410
411    /**
412     * Helper function to delete all history items and revert all
413     * bookmarks to zero visits which meet the criteria provided.
414     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
415     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
416     * @param cr   The ContentResolver used to access the database.
417     * @param whereClause   String to limit the items affected.
418     *                      null means all items.
419     */
420    private static final void deleteHistoryWhere(ContentResolver cr,
421            String whereClause) {
422        try {
423            Cursor c = cr.query(BOOKMARKS_URI,
424                HISTORY_PROJECTION,
425                whereClause,
426                null,
427                null);
428            if (!c.moveToFirst()) {
429                c.deactivate();
430                return;
431            }
432
433            final WebIconDatabase iconDb = WebIconDatabase.getInstance();
434            /* Delete favicons, and revert bookmarks which have been visited
435             * to simply bookmarks.
436             */
437            StringBuffer sb = new StringBuffer();
438            boolean firstTime = true;
439            do {
440                String url = c.getString(HISTORY_PROJECTION_URL_INDEX);
441                boolean isBookmark =
442                    c.getInt(HISTORY_PROJECTION_BOOKMARK_INDEX) == 1;
443                if (isBookmark) {
444                    if (firstTime) {
445                        firstTime = false;
446                    } else {
447                        sb.append(" OR ");
448                    }
449                    sb.append("( _id = ");
450                    sb.append(c.getInt(0));
451                    sb.append(" )");
452                } else {
453                    iconDb.releaseIconForPageUrl(url);
454                }
455            } while (c.moveToNext());
456            c.deactivate();
457
458            if (!firstTime) {
459                ContentValues map = new ContentValues();
460                map.put(BookmarkColumns.VISITS, 0);
461                map.put(BookmarkColumns.DATE, 0);
462                /* FIXME: Should I also remove the title? */
463                cr.update(BOOKMARKS_URI, map, sb.toString(), null);
464            }
465
466            String deleteWhereClause = BookmarkColumns.BOOKMARK + " = 0";
467            if (whereClause != null) {
468                deleteWhereClause += " AND " + whereClause;
469            }
470            cr.delete(BOOKMARKS_URI, deleteWhereClause, null);
471        } catch (IllegalStateException e) {
472            return;
473        }
474    }
475
476    /**
477     * Delete all history items from begin to end.
478     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
479     * @param cr    The ContentResolver used to access the database.
480     * @param begin First date to remove.  If -1, all dates before end.
481     *              Inclusive.
482     * @param end   Last date to remove. If -1, all dates after begin.
483     *              Non-inclusive.
484     */
485    public static final void deleteHistoryTimeFrame(ContentResolver cr,
486            long begin, long end) {
487        String whereClause;
488        String date = BookmarkColumns.DATE;
489        if (-1 == begin) {
490            if (-1 == end) {
491                clearHistory(cr);
492                return;
493            }
494            whereClause = date + " < " + Long.toString(end);
495        } else if (-1 == end) {
496            whereClause = date + " >= " + Long.toString(begin);
497        } else {
498            whereClause = date + " >= " + Long.toString(begin) + " AND " + date
499                    + " < " + Long.toString(end);
500        }
501        deleteHistoryWhere(cr, whereClause);
502    }
503
504    /**
505     * Remove a specific url from the history database.
506     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
507     * @param cr    The ContentResolver used to access the database.
508     * @param url   url to remove.
509     */
510    public static final void deleteFromHistory(ContentResolver cr,
511                                               String url) {
512        StringBuilder sb = new StringBuilder(BookmarkColumns.URL + " = ");
513        DatabaseUtils.appendEscapedSQLString(sb, url);
514        String matchesUrl = sb.toString();
515        deleteHistoryWhere(cr, matchesUrl);
516    }
517
518    /**
519     * Add a search string to the searches database.
520     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
521     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
522     * @param cr   The ContentResolver used to access the database.
523     * @param search    The string to add to the searches database.
524     */
525    public static final void addSearchUrl(ContentResolver cr, String search) {
526        long now = new Date().getTime();
527        try {
528            Cursor c = cr.query(
529                SEARCHES_URI,
530                SEARCHES_PROJECTION,
531                SEARCHES_WHERE_CLAUSE,
532                new String [] { search },
533                null);
534            ContentValues map = new ContentValues();
535            map.put(SearchColumns.SEARCH, search);
536            map.put(SearchColumns.DATE, now);
537            /* We should only get one answer that is exactly the same. */
538            if (c.moveToFirst()) {
539                cr.update(SEARCHES_URI, map, "_id = " + c.getInt(0), null);
540            } else {
541                cr.insert(SEARCHES_URI, map);
542            }
543            c.deactivate();
544        } catch (IllegalStateException e) {
545            Log.e(LOGTAG, "addSearchUrl", e);
546            return;
547        }
548    }
549    /**
550     * Remove all searches from the search database.
551     *  Requires {@link android.Manifest.permission#WRITE_HISTORY_BOOKMARKS}
552     * @param cr   The ContentResolver used to access the database.
553     */
554    public static final void clearSearches(ContentResolver cr) {
555        // FIXME: Should this clear the urls to which these searches lead?
556        // (i.e. remove google.com/query= blah blah blah)
557        try {
558            cr.delete(SEARCHES_URI, null, null);
559        } catch (IllegalStateException e) {
560            Log.e(LOGTAG, "clearSearches", e);
561        }
562    }
563
564    /**
565     *  Request all icons from the database.
566     *  Requires {@link android.Manifest.permission#READ_HISTORY_BOOKMARKS}
567     *  @param  cr The ContentResolver used to access the database.
568     *  @param  where Clause to be used to limit the query from the database.
569     *          Must be an allowable string to be passed into a database query.
570     *  @param  listener IconListener that gets the icons once they are
571     *          retrieved.
572     */
573    public static final void requestAllIcons(ContentResolver cr, String where,
574            WebIconDatabase.IconListener listener) {
575        try {
576            final Cursor c = cr.query(
577                    BOOKMARKS_URI,
578                    HISTORY_PROJECTION,
579                    where, null, null);
580            if (c.moveToFirst()) {
581                final WebIconDatabase db = WebIconDatabase.getInstance();
582                do {
583                    db.requestIconForPageUrl(
584                            c.getString(HISTORY_PROJECTION_URL_INDEX),
585                            listener);
586                } while (c.moveToNext());
587            }
588            c.deactivate();
589        } catch (IllegalStateException e) {
590            Log.e(LOGTAG, "requestAllIcons", e);
591        }
592    }
593
594    public static class BookmarkColumns implements BaseColumns {
595        public static final String URL = "url";
596        public static final String VISITS = "visits";
597        public static final String DATE = "date";
598        public static final String BOOKMARK = "bookmark";
599        public static final String TITLE = "title";
600        public static final String CREATED = "created";
601        public static final String FAVICON = "favicon";
602        /**
603         * @hide
604         */
605        public static final String THUMBNAIL = "thumbnail";
606        /**
607         * @hide
608         */
609        public static final String TOUCH_ICON = "touch_icon";
610        /**
611         * @hide
612         */
613        public static final String USER_ENTERED = "user_entered";
614    }
615
616    public static class SearchColumns implements BaseColumns {
617        public static final String URL = "url";
618        public static final String SEARCH = "search";
619        public static final String DATE = "date";
620    }
621}
622