2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
20 import java.util.LinkedList;
21 import java.util.Vector;
23 import android.app.AlertDialog;
24 import android.content.ContentResolver;
25 import android.content.ContentValues;
26 import android.content.DialogInterface;
27 import android.content.DialogInterface.OnCancelListener;
28 import android.database.Cursor;
29 import android.database.sqlite.SQLiteDatabase;
30 import android.database.sqlite.SQLiteException;
31 import android.graphics.Bitmap;
32 import android.net.Uri;
33 import android.net.http.SslError;
34 import android.os.AsyncTask;
35 import android.os.Bundle;
36 import android.os.Message;
37 import android.provider.Browser;
38 import android.util.Log;
39 import android.view.KeyEvent;
40 import android.view.LayoutInflater;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.view.View.OnClickListener;
44 import android.webkit.CookieSyncManager;
45 import android.webkit.GeolocationPermissions;
46 import android.webkit.HttpAuthHandler;
47 import android.webkit.SslErrorHandler;
48 import android.webkit.URLUtil;
49 import android.webkit.ValueCallback;
50 import android.webkit.WebBackForwardList;
51 import android.webkit.WebChromeClient;
52 import android.webkit.WebHistoryItem;
53 import android.webkit.WebIconDatabase;
54 import android.webkit.WebStorage;
55 import android.webkit.WebView;
56 import android.webkit.WebViewClient;
57 import android.widget.FrameLayout;
58 import android.widget.ImageButton;
59 import android.widget.LinearLayout;
60 import android.widget.TextView;
63 * Class for maintaining Tabs with a main WebView and a subwindow.
67 private static final String LOGTAG = "Tab";
68 // The Geolocation permissions prompt
69 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
70 // Main WebView wrapper
71 private View mContainer;
73 private WebView mMainView;
74 // Subwindow container
75 private View mSubViewContainer;
77 private WebView mSubView;
78 // Saved bundle for when we are running low on memory. It contains the
79 // information needed to restore the WebView if the user goes back to the
81 private Bundle mSavedState;
82 // Data used when displaying the tab in the picker.
83 private PickerData mPickerData;
84 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
86 private Tab mParentTab;
87 // Tab that constructed by this Tab. This is used when this Tab is
88 // destroyed, it clears all mParentTab values in the children.
89 private Vector<Tab> mChildTabs;
90 // If true, the tab will be removed when back out of the first page.
91 private boolean mCloseOnExit;
92 // If true, the tab is in the foreground of the current activity.
93 private boolean mInForeground;
94 // If true, the tab is in loading state.
95 private boolean mInLoad;
96 // Application identifier used to find tabs that another application wants
98 private String mAppId;
99 // Keep the original url around to avoid killing the old WebView if the url
101 private String mOriginalUrl;
102 // Error console for the tab
103 private ErrorConsoleView mErrorConsole;
104 // the lock icon type and previous lock icon type for the tab
105 private int mLockIconType;
106 private int mPrevLockIconType;
107 // Inflation service for making subwindows.
108 private final LayoutInflater mInflateService;
109 // The BrowserActivity which owners the Tab
110 private final BrowserActivity mActivity;
112 // AsyncTask for downloading touch icons
113 DownloadTouchIcon mTouchIconLoader;
115 // Extra saved information for displaying the tab in the picker.
116 private static class PickerData {
122 // Used for saving and restoring each Tab
123 static final String WEBVIEW = "webview";
124 static final String NUMTABS = "numTabs";
125 static final String CURRTAB = "currentTab";
126 static final String CURRURL = "currentUrl";
127 static final String CURRTITLE = "currentTitle";
128 static final String CURRPICTURE = "currentPicture";
129 static final String CLOSEONEXIT = "closeonexit";
130 static final String PARENTTAB = "parentTab";
131 static final String APPID = "appid";
132 static final String ORIGINALURL = "originalUrl";
134 // -------------------------------------------------------------------------
136 // Container class for the next error dialog that needs to be displayed
137 private class ErrorDialog {
138 public final int mTitle;
139 public final String mDescription;
140 public final int mError;
141 ErrorDialog(int title, String desc, int error) {
148 private void processNextError() {
149 if (mQueuedErrors == null) {
152 // The first one is currently displayed so just remove it.
153 mQueuedErrors.removeFirst();
154 if (mQueuedErrors.size() == 0) {
155 mQueuedErrors = null;
158 showError(mQueuedErrors.getFirst());
161 private DialogInterface.OnDismissListener mDialogListener =
162 new DialogInterface.OnDismissListener() {
163 public void onDismiss(DialogInterface d) {
167 private LinkedList<ErrorDialog> mQueuedErrors;
169 private void queueError(int err, String desc) {
170 if (mQueuedErrors == null) {
171 mQueuedErrors = new LinkedList<ErrorDialog>();
173 for (ErrorDialog d : mQueuedErrors) {
174 if (d.mError == err) {
175 // Already saw a similar error, ignore the new one.
179 ErrorDialog errDialog = new ErrorDialog(
180 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
181 R.string.browserFrameFileErrorLabel :
182 R.string.browserFrameNetworkErrorLabel,
184 mQueuedErrors.addLast(errDialog);
186 // Show the dialog now if the queue was empty and it is in foreground
187 if (mQueuedErrors.size() == 1 && mInForeground) {
188 showError(errDialog);
192 private void showError(ErrorDialog errDialog) {
194 AlertDialog d = new AlertDialog.Builder(mActivity)
195 .setTitle(errDialog.mTitle)
196 .setMessage(errDialog.mDescription)
197 .setPositiveButton(R.string.ok, null)
199 d.setOnDismissListener(mDialogListener);
204 // -------------------------------------------------------------------------
205 // WebViewClient implementation for the main WebView
206 // -------------------------------------------------------------------------
208 private final WebViewClient mWebViewClient = new WebViewClient() {
210 public void onPageStarted(WebView view, String url, Bitmap favicon) {
213 // We've started to load a new page. If there was a pending message
214 // to save a screenshot then we will now take the new page and save
215 // an incorrect screenshot. Therefore, remove any pending thumbnail
216 // messages from the queue.
217 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
220 // If we start a touch icon load and then load a new page, we don't
221 // want to cancel the current touch icon loader. But, we do want to
222 // create a new one when the touch icon url is known.
223 if (mTouchIconLoader != null) {
224 mTouchIconLoader.mTab = null;
225 mTouchIconLoader = null;
228 // reset the error console
229 if (mErrorConsole != null) {
230 mErrorConsole.clearErrorMessages();
231 if (mActivity.shouldShowErrorConsole()) {
232 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
236 // update the bookmark database for favicon
237 if (favicon != null) {
238 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
239 .getContentResolver(), view.getOriginalUrl(), view
243 // reset sync timer to avoid sync starts during loading a page
244 CookieSyncManager.getInstance().resetSync();
246 if (!mActivity.isNetworkUp()) {
247 view.setNetworkAvailable(false);
250 // finally update the UI in the activity if it is in the foreground
252 mActivity.onPageStarted(view, url, favicon);
257 public void onPageFinished(WebView view, String url) {
260 if (mInForeground && !mActivity.didUserStopLoading()
262 // Only update the bookmark screenshot if the user did not
263 // cancel the load early.
264 mActivity.postMessage(
265 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
269 // finally update the UI in the activity if it is in the foreground
271 mActivity.onPageFinished(view, url);
275 // return true if want to hijack the url to let another app to handle it
277 public boolean shouldOverrideUrlLoading(WebView view, String url) {
279 return mActivity.shouldOverrideUrlLoading(view, url);
286 * Updates the lock icon. This method is called when we discover another
287 * resource to be loaded for this page (for example, javascript). While
288 * we update the icon type, we do not update the lock icon itself until
289 * we are done loading, it is slightly more secure this way.
292 public void onLoadResource(WebView view, String url) {
293 if (url != null && url.length() > 0) {
294 // It is only if the page claims to be secure that we may have
295 // to update the lock:
296 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
297 // If NOT a 'safe' url, change the lock to mixed content!
298 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
299 || URLUtil.isAboutUrl(url))) {
300 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
307 * Show the dialog if it is in the foreground, asking the user if they
308 * would like to continue after an excessive number of HTTP redirects.
309 * Cancel if it is in the background.
312 public void onTooManyRedirects(WebView view, final Message cancelMsg,
313 final Message continueMsg) {
314 if (!mInForeground) {
315 cancelMsg.sendToTarget();
318 new AlertDialog.Builder(mActivity).setTitle(
319 R.string.browserFrameRedirect).setMessage(
320 R.string.browserFrame307Post).setPositiveButton(
321 R.string.ok, new DialogInterface.OnClickListener() {
322 public void onClick(DialogInterface dialog, int which) {
323 continueMsg.sendToTarget();
325 }).setNegativeButton(R.string.cancel,
326 new DialogInterface.OnClickListener() {
327 public void onClick(DialogInterface dialog, int which) {
328 cancelMsg.sendToTarget();
330 }).setOnCancelListener(new OnCancelListener() {
331 public void onCancel(DialogInterface dialog) {
332 cancelMsg.sendToTarget();
338 * Show a dialog informing the user of the network error reported by
339 * WebCore if it is in the foreground.
342 public void onReceivedError(WebView view, int errorCode,
343 String description, String failingUrl) {
344 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
345 errorCode != WebViewClient.ERROR_CONNECT &&
346 errorCode != WebViewClient.ERROR_BAD_URL &&
347 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
348 errorCode != WebViewClient.ERROR_FILE) {
349 queueError(errorCode, description);
351 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
352 + " " + description);
354 // We need to reset the title after an error if it is in foreground.
356 mActivity.resetTitleAndRevertLockIcon();
361 * Check with the user if it is ok to resend POST data as the page they
362 * are trying to navigate to is the result of a POST.
365 public void onFormResubmission(WebView view, final Message dontResend,
366 final Message resend) {
367 if (!mInForeground) {
368 dontResend.sendToTarget();
371 new AlertDialog.Builder(mActivity).setTitle(
372 R.string.browserFrameFormResubmitLabel).setMessage(
373 R.string.browserFrameFormResubmitMessage)
374 .setPositiveButton(R.string.ok,
375 new DialogInterface.OnClickListener() {
376 public void onClick(DialogInterface dialog,
378 resend.sendToTarget();
380 }).setNegativeButton(R.string.cancel,
381 new DialogInterface.OnClickListener() {
382 public void onClick(DialogInterface dialog,
384 dontResend.sendToTarget();
386 }).setOnCancelListener(new OnCancelListener() {
387 public void onCancel(DialogInterface dialog) {
388 dontResend.sendToTarget();
394 * Insert the url into the visited history database.
395 * @param url The url to be inserted.
396 * @param isReload True if this url is being reloaded.
397 * FIXME: Not sure what to do when reloading the page.
400 public void doUpdateVisitedHistory(WebView view, String url,
402 if (url.regionMatches(true, 0, "about:", 0, 6)) {
405 // remove "client" before updating it to the history so that it wont
406 // show up in the auto-complete list.
407 int index = url.indexOf("client=ms-");
408 if (index > 0 && url.contains(".google.")) {
409 int end = url.indexOf('&', index);
411 url = url.substring(0, index)
412 .concat(url.substring(end + 1));
414 // the url.charAt(index-1) should be either '?' or '&'
415 url = url.substring(0, index-1);
418 Browser.updateVisitedHistory(mActivity.getContentResolver(), url,
420 WebIconDatabase.getInstance().retainIconForPageUrl(url);
424 * Displays SSL error(s) dialog to the user.
427 public void onReceivedSslError(final WebView view,
428 final SslErrorHandler handler, final SslError error) {
429 if (!mInForeground) {
433 if (BrowserSettings.getInstance().showSecurityWarnings()) {
434 final LayoutInflater factory =
435 LayoutInflater.from(mActivity);
436 final View warningsView =
437 factory.inflate(R.layout.ssl_warnings, null);
438 final LinearLayout placeholder =
439 (LinearLayout)warningsView.findViewById(R.id.placeholder);
441 if (error.hasError(SslError.SSL_UNTRUSTED)) {
442 LinearLayout ll = (LinearLayout)factory
443 .inflate(R.layout.ssl_warning, null);
444 ((TextView)ll.findViewById(R.id.warning))
445 .setText(R.string.ssl_untrusted);
446 placeholder.addView(ll);
449 if (error.hasError(SslError.SSL_IDMISMATCH)) {
450 LinearLayout ll = (LinearLayout)factory
451 .inflate(R.layout.ssl_warning, null);
452 ((TextView)ll.findViewById(R.id.warning))
453 .setText(R.string.ssl_mismatch);
454 placeholder.addView(ll);
457 if (error.hasError(SslError.SSL_EXPIRED)) {
458 LinearLayout ll = (LinearLayout)factory
459 .inflate(R.layout.ssl_warning, null);
460 ((TextView)ll.findViewById(R.id.warning))
461 .setText(R.string.ssl_expired);
462 placeholder.addView(ll);
465 if (error.hasError(SslError.SSL_NOTYETVALID)) {
466 LinearLayout ll = (LinearLayout)factory
467 .inflate(R.layout.ssl_warning, null);
468 ((TextView)ll.findViewById(R.id.warning))
469 .setText(R.string.ssl_not_yet_valid);
470 placeholder.addView(ll);
473 new AlertDialog.Builder(mActivity).setTitle(
474 R.string.security_warning).setIcon(
475 android.R.drawable.ic_dialog_alert).setView(
476 warningsView).setPositiveButton(R.string.ssl_continue,
477 new DialogInterface.OnClickListener() {
478 public void onClick(DialogInterface dialog,
482 }).setNeutralButton(R.string.view_certificate,
483 new DialogInterface.OnClickListener() {
484 public void onClick(DialogInterface dialog,
486 mActivity.showSSLCertificateOnError(view,
489 }).setNegativeButton(R.string.cancel,
490 new DialogInterface.OnClickListener() {
491 public void onClick(DialogInterface dialog,
494 mActivity.resetTitleAndRevertLockIcon();
496 }).setOnCancelListener(
497 new DialogInterface.OnCancelListener() {
498 public void onCancel(DialogInterface dialog) {
500 mActivity.resetTitleAndRevertLockIcon();
509 * Handles an HTTP authentication request.
511 * @param handler The authentication handler
512 * @param host The host
513 * @param realm The realm
516 public void onReceivedHttpAuthRequest(WebView view,
517 final HttpAuthHandler handler, final String host,
518 final String realm) {
519 String username = null;
520 String password = null;
522 boolean reuseHttpAuthUsernamePassword = handler
523 .useHttpAuthUsernamePassword();
525 if (reuseHttpAuthUsernamePassword && mMainView != null) {
526 String[] credentials = mMainView.getHttpAuthUsernamePassword(
528 if (credentials != null && credentials.length == 2) {
529 username = credentials[0];
530 password = credentials[1];
534 if (username != null && password != null) {
535 handler.proceed(username, password);
538 mActivity.showHttpAuthentication(handler, host, realm,
539 null, null, null, 0);
547 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
548 if (!mInForeground) {
551 if (mActivity.isMenuDown()) {
552 // only check shortcut key when MENU is held
553 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
561 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
562 if (!mInForeground) {
565 if (event.isDown()) {
566 mActivity.onKeyDown(event.getKeyCode(), event);
568 mActivity.onKeyUp(event.getKeyCode(), event);
573 // -------------------------------------------------------------------------
574 // WebChromeClient implementation for the main WebView
575 // -------------------------------------------------------------------------
577 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
578 // Helper method to create a new tab or sub window.
579 private void createWindow(final boolean dialog, final Message msg) {
580 WebView.WebViewTransport transport =
581 (WebView.WebViewTransport) msg.obj;
584 mActivity.attachSubWindow(Tab.this);
585 transport.setWebView(mSubView);
587 final Tab newTab = mActivity.openTabAndShow(
588 BrowserActivity.EMPTY_URL_DATA, false, null);
589 if (newTab != Tab.this) {
590 Tab.this.addChildTab(newTab);
592 transport.setWebView(newTab.getWebView());
598 public boolean onCreateWindow(WebView view, final boolean dialog,
599 final boolean userGesture, final Message resultMsg) {
600 // only allow new window or sub window for the foreground case
601 if (!mInForeground) {
604 // Short-circuit if we can't create any more tabs or sub windows.
605 if (dialog && mSubView != null) {
606 new AlertDialog.Builder(mActivity)
607 .setTitle(R.string.too_many_subwindows_dialog_title)
608 .setIcon(android.R.drawable.ic_dialog_alert)
609 .setMessage(R.string.too_many_subwindows_dialog_message)
610 .setPositiveButton(R.string.ok, null)
613 } else if (!mActivity.getTabControl().canCreateNewTab()) {
614 new AlertDialog.Builder(mActivity)
615 .setTitle(R.string.too_many_windows_dialog_title)
616 .setIcon(android.R.drawable.ic_dialog_alert)
617 .setMessage(R.string.too_many_windows_dialog_message)
618 .setPositiveButton(R.string.ok, null)
623 // Short-circuit if this was a user gesture.
625 createWindow(dialog, resultMsg);
629 // Allow the popup and create the appropriate window.
630 final AlertDialog.OnClickListener allowListener =
631 new AlertDialog.OnClickListener() {
632 public void onClick(DialogInterface d,
634 createWindow(dialog, resultMsg);
638 // Block the popup by returning a null WebView.
639 final AlertDialog.OnClickListener blockListener =
640 new AlertDialog.OnClickListener() {
641 public void onClick(DialogInterface d, int which) {
642 resultMsg.sendToTarget();
646 // Build a confirmation dialog to display to the user.
647 final AlertDialog d =
648 new AlertDialog.Builder(mActivity)
649 .setTitle(R.string.attention)
650 .setIcon(android.R.drawable.ic_dialog_alert)
651 .setMessage(R.string.popup_window_attempt)
652 .setPositiveButton(R.string.allow, allowListener)
653 .setNegativeButton(R.string.block, blockListener)
654 .setCancelable(false)
657 // Show the confirmation dialog.
663 public void onRequestFocus(WebView view) {
664 if (!mInForeground) {
665 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
671 public void onCloseWindow(WebView window) {
672 if (mParentTab != null) {
673 // JavaScript can only close popup window.
675 mActivity.switchToTab(mActivity.getTabControl()
676 .getTabIndex(mParentTab));
678 mActivity.closeTab(Tab.this);
683 public void onProgressChanged(WebView view, int newProgress) {
684 if (newProgress == 100) {
685 // sync cookies and cache promptly here.
686 CookieSyncManager.getInstance().sync();
689 mActivity.onProgressChanged(view, newProgress);
694 public void onReceivedTitle(WebView view, String title) {
695 String url = view.getUrl();
697 // here, if url is null, we want to reset the title
698 mActivity.setUrlTitle(url, title);
701 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
704 // See if we can find the current url in our history database and
705 // add the new title to it.
706 if (url.startsWith("http://www.")) {
707 url = url.substring(11);
708 } else if (url.startsWith("http://")) {
709 url = url.substring(4);
712 final ContentResolver cr = mActivity.getContentResolver();
714 String [] selArgs = new String[] { url };
715 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
716 + Browser.BookmarkColumns.BOOKMARK + " = 0";
717 Cursor c = cr.query(Browser.BOOKMARKS_URI,
718 Browser.HISTORY_PROJECTION, where, selArgs, null);
719 if (c.moveToFirst()) {
720 // Current implementation of database only has one entry per
722 ContentValues map = new ContentValues();
723 map.put(Browser.BookmarkColumns.TITLE, title);
724 cr.update(Browser.BOOKMARKS_URI, map, "_id = "
725 + c.getInt(0), null);
728 } catch (IllegalStateException e) {
729 Log.e(LOGTAG, "Tab onReceived title", e);
730 } catch (SQLiteException ex) {
731 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
736 public void onReceivedIcon(WebView view, Bitmap icon) {
738 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
739 .getContentResolver(), view.getOriginalUrl(), view
743 mActivity.setFavicon(icon);
748 public void onReceivedTouchIconUrl(WebView view, String url,
749 boolean precomposed) {
750 final ContentResolver cr = mActivity.getContentResolver();
751 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
752 view.getOriginalUrl(), view.getUrl(), true);
754 if (c.getCount() > 0) {
755 // Let precomposed icons take precedence over non-composed
757 if (precomposed && mTouchIconLoader != null) {
758 mTouchIconLoader.cancel(false);
759 mTouchIconLoader = null;
761 // Have only one async task at a time.
762 if (mTouchIconLoader == null) {
763 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
765 mTouchIconLoader.execute(url);
774 public void onShowCustomView(View view,
775 WebChromeClient.CustomViewCallback callback) {
776 if (mInForeground) mActivity.onShowCustomView(view, callback);
780 public void onHideCustomView() {
781 if (mInForeground) mActivity.onHideCustomView();
785 * The origin has exceeded its database quota.
786 * @param url the URL that exceeded the quota
787 * @param databaseIdentifier the identifier of the database on which the
788 * transaction that caused the quota overflow was run
789 * @param currentQuota the current quota for the origin.
790 * @param estimatedSize the estimated size of the database.
791 * @param totalUsedQuota is the sum of all origins' quota.
792 * @param quotaUpdater The callback to run when a decision to allow or
793 * deny quota has been made. Don't forget to call this!
796 public void onExceededDatabaseQuota(String url,
797 String databaseIdentifier, long currentQuota, long estimatedSize,
798 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
799 BrowserSettings.getInstance().getWebStorageSizeManager()
800 .onExceededDatabaseQuota(url, databaseIdentifier,
801 currentQuota, estimatedSize, totalUsedQuota,
806 * The Application Cache has exceeded its max size.
807 * @param spaceNeeded is the amount of disk space that would be needed
808 * in order for the last appcache operation to succeed.
809 * @param totalUsedQuota is the sum of all origins' quota.
810 * @param quotaUpdater A callback to inform the WebCore thread that a
811 * new app cache size is available. This callback must always
812 * be executed at some point to ensure that the sleeping
813 * WebCore thread is woken up.
816 public void onReachedMaxAppCacheSize(long spaceNeeded,
817 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
818 BrowserSettings.getInstance().getWebStorageSizeManager()
819 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
824 * Instructs the browser to show a prompt to ask the user to set the
825 * Geolocation permission state for the specified origin.
826 * @param origin The origin for which Geolocation permissions are
828 * @param callback The callback to call once the user has set the
829 * Geolocation permission state.
832 public void onGeolocationPermissionsShowPrompt(String origin,
833 GeolocationPermissions.Callback callback) {
835 mGeolocationPermissionsPrompt.show(origin, callback);
840 * Instructs the browser to hide the Geolocation permissions prompt.
843 public void onGeolocationPermissionsHidePrompt() {
845 mGeolocationPermissionsPrompt.hide();
849 /* Adds a JavaScript error message to the system log and if the JS
850 * console is enabled in the about:debug options, to that console
852 * @param message The error message to report.
853 * @param lineNumber The line number of the error.
854 * @param sourceID The name of the source file that caused the error.
857 public void onConsoleMessage(String message, int lineNumber,
860 // call getErrorConsole(true) so it will create one if needed
861 ErrorConsoleView errorConsole = getErrorConsole(true);
862 errorConsole.addErrorMessage(message, sourceID, lineNumber);
863 if (mActivity.shouldShowErrorConsole()
864 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
865 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
868 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":"
873 * Ask the browser for an icon to represent a <video> element.
874 * This icon will be used if the Web page did not specify a poster attribute.
875 * @return Bitmap The icon or null if no such icon is available.
878 public Bitmap getDefaultVideoPoster() {
880 return mActivity.getDefaultVideoPoster();
886 * Ask the host application for a custom progress view to show while
887 * a <video> is loading.
888 * @return View The progress view.
891 public View getVideoLoadingProgressView() {
893 return mActivity.getVideoLoadingProgressView();
899 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
901 mActivity.openFileChooser(uploadMsg);
903 uploadMsg.onReceiveValue(null);
908 * Deliver a list of already-visited URLs
911 public void getVisitedHistory(final ValueCallback<String[]> callback) {
912 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
913 public String[] doInBackground(Void... unused) {
914 return Browser.getVisitedHistory(mActivity
915 .getContentResolver());
917 public void onPostExecute(String[] result) {
918 callback.onReceiveValue(result);
925 // -------------------------------------------------------------------------
926 // WebViewClient implementation for the sub window
927 // -------------------------------------------------------------------------
929 // Subclass of WebViewClient used in subwindows to notify the main
930 // WebViewClient of certain WebView activities.
931 private static class SubWindowClient extends WebViewClient {
932 // The main WebViewClient.
933 private final WebViewClient mClient;
935 SubWindowClient(WebViewClient client) {
939 public void doUpdateVisitedHistory(WebView view, String url,
941 mClient.doUpdateVisitedHistory(view, url, isReload);
944 public boolean shouldOverrideUrlLoading(WebView view, String url) {
945 return mClient.shouldOverrideUrlLoading(view, url);
948 public void onReceivedSslError(WebView view, SslErrorHandler handler,
950 mClient.onReceivedSslError(view, handler, error);
953 public void onReceivedHttpAuthRequest(WebView view,
954 HttpAuthHandler handler, String host, String realm) {
955 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
958 public void onFormResubmission(WebView view, Message dontResend,
960 mClient.onFormResubmission(view, dontResend, resend);
963 public void onReceivedError(WebView view, int errorCode,
964 String description, String failingUrl) {
965 mClient.onReceivedError(view, errorCode, description, failingUrl);
968 public boolean shouldOverrideKeyEvent(WebView view,
969 android.view.KeyEvent event) {
970 return mClient.shouldOverrideKeyEvent(view, event);
973 public void onUnhandledKeyEvent(WebView view,
974 android.view.KeyEvent event) {
975 mClient.onUnhandledKeyEvent(view, event);
979 // -------------------------------------------------------------------------
980 // WebChromeClient implementation for the sub window
981 // -------------------------------------------------------------------------
983 private class SubWindowChromeClient extends WebChromeClient {
984 // The main WebChromeClient.
985 private final WebChromeClient mClient;
987 SubWindowChromeClient(WebChromeClient client) {
991 public void onProgressChanged(WebView view, int newProgress) {
992 mClient.onProgressChanged(view, newProgress);
995 public boolean onCreateWindow(WebView view, boolean dialog,
996 boolean userGesture, android.os.Message resultMsg) {
997 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1000 public void onCloseWindow(WebView window) {
1001 if (window != mSubView) {
1002 Log.e(LOGTAG, "Can't close the window");
1004 mActivity.dismissSubWindow(Tab.this);
1008 // -------------------------------------------------------------------------
1010 // Construct a new tab
1011 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1013 mActivity = activity;
1014 mCloseOnExit = closeOnExit;
1017 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1018 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1020 mInForeground = false;
1022 mInflateService = LayoutInflater.from(activity);
1024 // The tab consists of a container view, which contains the main
1025 // WebView, as well as any other UI elements associated with the tab.
1026 mContainer = mInflateService.inflate(R.layout.tab, null);
1028 mGeolocationPermissionsPrompt =
1029 (GeolocationPermissionsPrompt) mContainer.findViewById(
1030 R.id.geolocation_permissions_prompt);
1036 * Sets the WebView for this tab, correctly removing the old WebView from
1037 * the container view.
1039 void setWebView(WebView w) {
1040 if (mMainView == w) {
1043 // If the WebView is changing, the page will be reloaded, so any ongoing
1044 // Geolocation permission requests are void.
1045 mGeolocationPermissionsPrompt.hide();
1047 // Just remove the old one.
1048 FrameLayout wrapper =
1049 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1050 wrapper.removeView(mMainView);
1054 // attached the WebViewClient and WebChromeClient
1055 if (mMainView != null) {
1056 mMainView.setWebViewClient(mWebViewClient);
1057 mMainView.setWebChromeClient(mWebChromeClient);
1062 * Destroy the tab's main WebView and subWindow if any
1065 if (mMainView != null) {
1067 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1068 // save the WebView to call destroy() after detach it from the tab
1069 WebView webView = mMainView;
1076 * Remove the tab from the parent
1078 void removeFromTree() {
1079 // detach the children
1080 if (mChildTabs != null) {
1081 for(Tab t : mChildTabs) {
1082 t.setParentTab(null);
1085 // remove itself from the parent list
1086 if (mParentTab != null) {
1087 mParentTab.mChildTabs.remove(this);
1092 * Create a new subwindow unless a subwindow already exists.
1093 * @return True if a new subwindow was created. False if one already exists.
1095 boolean createSubWindow() {
1096 if (mSubView == null) {
1097 mSubViewContainer = mInflateService.inflate(
1098 R.layout.browser_subwindow, null);
1099 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1100 // use trackball directly
1101 mSubView.setMapTrackballToArrowKeys(false);
1102 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1103 mSubView.setWebChromeClient(new SubWindowChromeClient(
1105 mSubView.setDownloadListener(mActivity);
1106 mSubView.setOnCreateContextMenuListener(mActivity);
1107 final BrowserSettings s = BrowserSettings.getInstance();
1108 s.addObserver(mSubView.getSettings()).update(s, null);
1109 final ImageButton cancel = (ImageButton) mSubViewContainer
1110 .findViewById(R.id.subwindow_close);
1111 cancel.setOnClickListener(new OnClickListener() {
1112 public void onClick(View v) {
1113 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1122 * Dismiss the subWindow for the tab.
1124 void dismissSubWindow() {
1125 if (mSubView != null) {
1126 BrowserSettings.getInstance().deleteObserver(
1127 mSubView.getSettings());
1130 mSubViewContainer = null;
1135 * Attach the sub window to the content view.
1137 void attachSubWindow(ViewGroup content) {
1138 if (mSubView != null) {
1139 content.addView(mSubViewContainer,
1140 BrowserActivity.COVER_SCREEN_PARAMS);
1145 * Remove the sub window from the content view.
1147 void removeSubWindow(ViewGroup content) {
1148 if (mSubView != null) {
1149 content.removeView(mSubViewContainer);
1154 * This method attaches both the WebView and any sub window to the
1155 * given content view.
1157 void attachTabToContentView(ViewGroup content) {
1158 if (mMainView == null) {
1162 // Attach the WebView to the container and then attach the
1163 // container to the content view.
1164 FrameLayout wrapper =
1165 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1166 wrapper.addView(mMainView);
1167 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1168 attachSubWindow(content);
1172 * Remove the WebView and any sub window from the given content view.
1174 void removeTabFromContentView(ViewGroup content) {
1175 if (mMainView == null) {
1179 // Remove the container from the content and then remove the
1180 // WebView from the container. This will trigger a focus change
1181 // needed by WebView.
1182 FrameLayout wrapper =
1183 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1184 wrapper.removeView(mMainView);
1185 content.removeView(mContainer);
1186 removeSubWindow(content);
1190 * Set the parent tab of this tab.
1192 void setParentTab(Tab parent) {
1193 mParentTab = parent;
1194 // This tab may have been freed due to low memory. If that is the case,
1195 // the parent tab index is already saved. If we are changing that index
1196 // (most likely due to removing the parent tab) we must update the
1197 // parent tab index in the saved Bundle.
1198 if (mSavedState != null) {
1199 if (parent == null) {
1200 mSavedState.remove(PARENTTAB);
1202 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1203 .getTabIndex(parent));
1209 * When a Tab is created through the content of another Tab, then we
1210 * associate the Tabs.
1211 * @param child the Tab that was created from this Tab
1213 void addChildTab(Tab child) {
1214 if (mChildTabs == null) {
1215 mChildTabs = new Vector<Tab>();
1217 mChildTabs.add(child);
1218 child.setParentTab(this);
1221 Vector<Tab> getChildTabs() {
1226 if (mMainView != null) {
1227 mMainView.onResume();
1228 if (mSubView != null) {
1229 mSubView.onResume();
1235 if (mMainView != null) {
1236 mMainView.onPause();
1237 if (mSubView != null) {
1243 void putInForeground() {
1244 mInForeground = true;
1246 mMainView.setOnCreateContextMenuListener(mActivity);
1247 if (mSubView != null) {
1248 mSubView.setOnCreateContextMenuListener(mActivity);
1250 // Show the pending error dialog if the queue is not empty
1251 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1252 showError(mQueuedErrors.getFirst());
1256 void putInBackground() {
1257 mInForeground = false;
1259 mMainView.setOnCreateContextMenuListener(null);
1260 if (mSubView != null) {
1261 mSubView.setOnCreateContextMenuListener(null);
1266 * Return the top window of this tab; either the subwindow if it is not
1267 * null or the main window.
1268 * @return The top window of this tab.
1270 WebView getTopWindow() {
1271 if (mSubView != null) {
1278 * Return the main window of this tab. Note: if a tab is freed in the
1279 * background, this can return null. It is only guaranteed to be
1280 * non-null for the current tab.
1281 * @return The main WebView of this tab.
1283 WebView getWebView() {
1288 * Return the subwindow of this tab or null if there is no subwindow.
1289 * @return The subwindow of this tab or null.
1291 WebView getSubWebView() {
1296 * @return The geolocation permissions prompt for this tab.
1298 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1299 return mGeolocationPermissionsPrompt;
1303 * @return The application id string
1310 * Set the application id string
1313 void setAppId(String id) {
1318 * @return The original url associated with this Tab
1320 String getOriginalUrl() {
1321 return mOriginalUrl;
1325 * Set the original url associated with this tab
1327 void setOriginalUrl(String url) {
1332 * Get the url of this tab. Valid after calling populatePickerData, but
1333 * before calling wipePickerData, or if the webview has been destroyed.
1334 * @return The WebView's url or null.
1337 if (mPickerData != null) {
1338 return mPickerData.mUrl;
1344 * Get the title of this tab. Valid after calling populatePickerData, but
1345 * before calling wipePickerData, or if the webview has been destroyed. If
1346 * the url has no title, use the url instead.
1347 * @return The WebView's title (or url) or null.
1350 if (mPickerData != null) {
1351 return mPickerData.mTitle;
1357 * Get the favicon of this tab. Valid after calling populatePickerData, but
1358 * before calling wipePickerData, or if the webview has been destroyed.
1359 * @return The WebView's favicon or null.
1361 Bitmap getFavicon() {
1362 if (mPickerData != null) {
1363 return mPickerData.mFavicon;
1369 * Return the tab's error console. Creates the console if createIfNEcessary
1370 * is true and we haven't already created the console.
1371 * @param createIfNecessary Flag to indicate if the console should be
1372 * created if it has not been already.
1373 * @return The tab's error console, or null if one has not been created and
1374 * createIfNecessary is false.
1376 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1377 if (createIfNecessary && mErrorConsole == null) {
1378 mErrorConsole = new ErrorConsoleView(mActivity);
1379 mErrorConsole.setWebView(mMainView);
1381 return mErrorConsole;
1385 * If this Tab was created through another Tab, then this method returns
1387 * @return the Tab parent or null
1389 public Tab getParentTab() {
1394 * Return whether this tab should be closed when it is backing out of the
1396 * @return TRUE if this tab should be closed when exit.
1398 boolean closeOnExit() {
1399 return mCloseOnExit;
1403 * Saves the current lock-icon state before resetting the lock icon. If we
1404 * have an error, we may need to roll back to the previous state.
1406 void resetLockIcon(String url) {
1407 mPrevLockIconType = mLockIconType;
1408 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1409 if (URLUtil.isHttpsUrl(url)) {
1410 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1415 * Reverts the lock-icon state to the last saved state, for example, if we
1416 * had an error, and need to cancel the load.
1418 void revertLockIcon() {
1419 mLockIconType = mPrevLockIconType;
1423 * @return The tab's lock icon type.
1425 int getLockIconType() {
1426 return mLockIconType;
1430 * @return TRUE if onPageStarted is called while onPageFinished is not
1437 // force mInLoad to be false. This should only be called before closing the
1438 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1439 void clearInLoad() {
1443 void populatePickerData() {
1444 if (mMainView == null) {
1445 populatePickerDataFromSavedState();
1449 // FIXME: The only place we cared about subwindow was for
1450 // bookmarking (i.e. not when saving state). Was this deliberate?
1451 final WebBackForwardList list = mMainView.copyBackForwardList();
1452 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1453 populatePickerData(item);
1456 // Populate the picker data using the given history item and the current top
1458 private void populatePickerData(WebHistoryItem item) {
1459 mPickerData = new PickerData();
1461 mPickerData.mUrl = item.getUrl();
1462 mPickerData.mTitle = item.getTitle();
1463 mPickerData.mFavicon = item.getFavicon();
1464 if (mPickerData.mTitle == null) {
1465 mPickerData.mTitle = mPickerData.mUrl;
1470 // Create the PickerData and populate it using the saved state of the tab.
1471 void populatePickerDataFromSavedState() {
1472 if (mSavedState == null) {
1475 mPickerData = new PickerData();
1476 mPickerData.mUrl = mSavedState.getString(CURRURL);
1477 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1480 void clearPickerData() {
1485 * Get the saved state bundle.
1488 Bundle getSavedState() {
1493 * Set the saved state.
1495 void setSavedState(Bundle state) {
1496 mSavedState = state;
1500 * @return TRUE if succeed in saving the state.
1502 boolean saveState() {
1503 // If the WebView is null it means we ran low on memory and we already
1504 // stored the saved state in mSavedState.
1505 if (mMainView == null) {
1506 return mSavedState != null;
1509 mSavedState = new Bundle();
1510 final WebBackForwardList list = mMainView.saveState(mSavedState);
1512 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1513 mMainView.hashCode() + "_pic.save");
1514 if (mMainView.savePicture(mSavedState, f)) {
1515 mSavedState.putString(CURRPICTURE, f.getPath());
1519 // Store some extra info for displaying the tab in the picker.
1520 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1521 populatePickerData(item);
1523 if (mPickerData.mUrl != null) {
1524 mSavedState.putString(CURRURL, mPickerData.mUrl);
1526 if (mPickerData.mTitle != null) {
1527 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1529 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1530 if (mAppId != null) {
1531 mSavedState.putString(APPID, mAppId);
1533 if (mOriginalUrl != null) {
1534 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1536 // Remember the parent tab so the relationship can be restored.
1537 if (mParentTab != null) {
1538 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1545 * Restore the state of the tab.
1547 boolean restoreState(Bundle b) {
1551 // Restore the internal state even if the WebView fails to restore.
1552 // This will maintain the app id, original url and close-on-exit values.
1555 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1556 mAppId = b.getString(APPID);
1557 mOriginalUrl = b.getString(ORIGINALURL);
1559 final WebBackForwardList list = mMainView.restoreState(b);
1563 if (b.containsKey(CURRPICTURE)) {
1564 final File f = new File(b.getString(CURRPICTURE));
1565 mMainView.restorePicture(b, f);