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.
850 * @param message The error message to report.
851 * @param lineNumber The line number of the error.
852 * @param sourceID The name of the source file that caused the error.
855 public void addMessageToConsole(String message, int lineNumber,
858 // call getErrorConsole(true) so it will create one if needed
859 ErrorConsoleView errorConsole = getErrorConsole(true);
860 errorConsole.addErrorMessage(message, sourceID, lineNumber);
861 if (mActivity.shouldShowErrorConsole()
862 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
863 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
866 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":"
871 * Ask the browser for an icon to represent a <video> element.
872 * This icon will be used if the Web page did not specify a poster attribute.
873 * @return Bitmap The icon or null if no such icon is available.
876 public Bitmap getDefaultVideoPoster() {
878 return mActivity.getDefaultVideoPoster();
884 * Ask the host application for a custom progress view to show while
885 * a <video> is loading.
886 * @return View The progress view.
889 public View getVideoLoadingProgressView() {
891 return mActivity.getVideoLoadingProgressView();
897 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
899 mActivity.openFileChooser(uploadMsg);
901 uploadMsg.onReceiveValue(null);
906 * Deliver a list of already-visited URLs
909 public void getVisitedHistory(final ValueCallback<String[]> callback) {
910 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
911 public String[] doInBackground(Void... unused) {
912 return Browser.getVisitedHistory(mActivity
913 .getContentResolver());
915 public void onPostExecute(String[] result) {
916 callback.onReceiveValue(result);
923 // -------------------------------------------------------------------------
924 // WebViewClient implementation for the sub window
925 // -------------------------------------------------------------------------
927 // Subclass of WebViewClient used in subwindows to notify the main
928 // WebViewClient of certain WebView activities.
929 private static class SubWindowClient extends WebViewClient {
930 // The main WebViewClient.
931 private final WebViewClient mClient;
933 SubWindowClient(WebViewClient client) {
937 public void doUpdateVisitedHistory(WebView view, String url,
939 mClient.doUpdateVisitedHistory(view, url, isReload);
942 public boolean shouldOverrideUrlLoading(WebView view, String url) {
943 return mClient.shouldOverrideUrlLoading(view, url);
946 public void onReceivedSslError(WebView view, SslErrorHandler handler,
948 mClient.onReceivedSslError(view, handler, error);
951 public void onReceivedHttpAuthRequest(WebView view,
952 HttpAuthHandler handler, String host, String realm) {
953 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
956 public void onFormResubmission(WebView view, Message dontResend,
958 mClient.onFormResubmission(view, dontResend, resend);
961 public void onReceivedError(WebView view, int errorCode,
962 String description, String failingUrl) {
963 mClient.onReceivedError(view, errorCode, description, failingUrl);
966 public boolean shouldOverrideKeyEvent(WebView view,
967 android.view.KeyEvent event) {
968 return mClient.shouldOverrideKeyEvent(view, event);
971 public void onUnhandledKeyEvent(WebView view,
972 android.view.KeyEvent event) {
973 mClient.onUnhandledKeyEvent(view, event);
977 // -------------------------------------------------------------------------
978 // WebChromeClient implementation for the sub window
979 // -------------------------------------------------------------------------
981 private class SubWindowChromeClient extends WebChromeClient {
982 // The main WebChromeClient.
983 private final WebChromeClient mClient;
985 SubWindowChromeClient(WebChromeClient client) {
989 public void onProgressChanged(WebView view, int newProgress) {
990 mClient.onProgressChanged(view, newProgress);
993 public boolean onCreateWindow(WebView view, boolean dialog,
994 boolean userGesture, android.os.Message resultMsg) {
995 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
998 public void onCloseWindow(WebView window) {
999 if (window != mSubView) {
1000 Log.e(LOGTAG, "Can't close the window");
1002 mActivity.dismissSubWindow(Tab.this);
1006 // -------------------------------------------------------------------------
1008 // Construct a new tab
1009 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1011 mActivity = activity;
1012 mCloseOnExit = closeOnExit;
1015 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1016 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1018 mInForeground = false;
1020 mInflateService = LayoutInflater.from(activity);
1022 // The tab consists of a container view, which contains the main
1023 // WebView, as well as any other UI elements associated with the tab.
1024 mContainer = mInflateService.inflate(R.layout.tab, null);
1026 mGeolocationPermissionsPrompt =
1027 (GeolocationPermissionsPrompt) mContainer.findViewById(
1028 R.id.geolocation_permissions_prompt);
1034 * Sets the WebView for this tab, correctly removing the old WebView from
1035 * the container view.
1037 void setWebView(WebView w) {
1038 if (mMainView == w) {
1041 // If the WebView is changing, the page will be reloaded, so any ongoing
1042 // Geolocation permission requests are void.
1043 mGeolocationPermissionsPrompt.hide();
1045 // Just remove the old one.
1046 FrameLayout wrapper =
1047 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1048 wrapper.removeView(mMainView);
1052 // attached the WebViewClient and WebChromeClient
1053 if (mMainView != null) {
1054 mMainView.setWebViewClient(mWebViewClient);
1055 mMainView.setWebChromeClient(mWebChromeClient);
1060 * Destroy the tab's main WebView and subWindow if any
1063 if (mMainView != null) {
1065 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1066 // save the WebView to call destroy() after detach it from the tab
1067 WebView webView = mMainView;
1074 * Remove the tab from the parent
1076 void removeFromTree() {
1077 // detach the children
1078 if (mChildTabs != null) {
1079 for(Tab t : mChildTabs) {
1080 t.setParentTab(null);
1083 // remove itself from the parent list
1084 if (mParentTab != null) {
1085 mParentTab.mChildTabs.remove(this);
1090 * Create a new subwindow unless a subwindow already exists.
1091 * @return True if a new subwindow was created. False if one already exists.
1093 boolean createSubWindow() {
1094 if (mSubView == null) {
1095 mSubViewContainer = mInflateService.inflate(
1096 R.layout.browser_subwindow, null);
1097 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1098 // use trackball directly
1099 mSubView.setMapTrackballToArrowKeys(false);
1100 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1101 mSubView.setWebChromeClient(new SubWindowChromeClient(
1103 mSubView.setDownloadListener(mActivity);
1104 mSubView.setOnCreateContextMenuListener(mActivity);
1105 final BrowserSettings s = BrowserSettings.getInstance();
1106 s.addObserver(mSubView.getSettings()).update(s, null);
1107 final ImageButton cancel = (ImageButton) mSubViewContainer
1108 .findViewById(R.id.subwindow_close);
1109 cancel.setOnClickListener(new OnClickListener() {
1110 public void onClick(View v) {
1111 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1120 * Dismiss the subWindow for the tab.
1122 void dismissSubWindow() {
1123 if (mSubView != null) {
1124 BrowserSettings.getInstance().deleteObserver(
1125 mSubView.getSettings());
1128 mSubViewContainer = null;
1133 * Attach the sub window to the content view.
1135 void attachSubWindow(ViewGroup content) {
1136 if (mSubView != null) {
1137 content.addView(mSubViewContainer,
1138 BrowserActivity.COVER_SCREEN_PARAMS);
1143 * Remove the sub window from the content view.
1145 void removeSubWindow(ViewGroup content) {
1146 if (mSubView != null) {
1147 content.removeView(mSubViewContainer);
1152 * This method attaches both the WebView and any sub window to the
1153 * given content view.
1155 void attachTabToContentView(ViewGroup content) {
1156 if (mMainView == null) {
1160 // Attach the WebView to the container and then attach the
1161 // container to the content view.
1162 FrameLayout wrapper =
1163 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1164 wrapper.addView(mMainView);
1165 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1166 attachSubWindow(content);
1170 * Remove the WebView and any sub window from the given content view.
1172 void removeTabFromContentView(ViewGroup content) {
1173 if (mMainView == null) {
1177 // Remove the container from the content and then remove the
1178 // WebView from the container. This will trigger a focus change
1179 // needed by WebView.
1180 FrameLayout wrapper =
1181 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1182 wrapper.removeView(mMainView);
1183 content.removeView(mContainer);
1184 removeSubWindow(content);
1188 * Set the parent tab of this tab.
1190 void setParentTab(Tab parent) {
1191 mParentTab = parent;
1192 // This tab may have been freed due to low memory. If that is the case,
1193 // the parent tab index is already saved. If we are changing that index
1194 // (most likely due to removing the parent tab) we must update the
1195 // parent tab index in the saved Bundle.
1196 if (mSavedState != null) {
1197 if (parent == null) {
1198 mSavedState.remove(PARENTTAB);
1200 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1201 .getTabIndex(parent));
1207 * When a Tab is created through the content of another Tab, then we
1208 * associate the Tabs.
1209 * @param child the Tab that was created from this Tab
1211 void addChildTab(Tab child) {
1212 if (mChildTabs == null) {
1213 mChildTabs = new Vector<Tab>();
1215 mChildTabs.add(child);
1216 child.setParentTab(this);
1219 Vector<Tab> getChildTabs() {
1224 if (mMainView != null) {
1225 mMainView.onResume();
1226 if (mSubView != null) {
1227 mSubView.onResume();
1233 if (mMainView != null) {
1234 mMainView.onPause();
1235 if (mSubView != null) {
1241 void putInForeground() {
1242 mInForeground = true;
1244 mMainView.setOnCreateContextMenuListener(mActivity);
1245 if (mSubView != null) {
1246 mSubView.setOnCreateContextMenuListener(mActivity);
1248 // Show the pending error dialog if the queue is not empty
1249 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1250 showError(mQueuedErrors.getFirst());
1254 void putInBackground() {
1255 mInForeground = false;
1257 mMainView.setOnCreateContextMenuListener(null);
1258 if (mSubView != null) {
1259 mSubView.setOnCreateContextMenuListener(null);
1264 * Return the top window of this tab; either the subwindow if it is not
1265 * null or the main window.
1266 * @return The top window of this tab.
1268 WebView getTopWindow() {
1269 if (mSubView != null) {
1276 * Return the main window of this tab. Note: if a tab is freed in the
1277 * background, this can return null. It is only guaranteed to be
1278 * non-null for the current tab.
1279 * @return The main WebView of this tab.
1281 WebView getWebView() {
1286 * Return the subwindow of this tab or null if there is no subwindow.
1287 * @return The subwindow of this tab or null.
1289 WebView getSubWebView() {
1294 * @return The geolocation permissions prompt for this tab.
1296 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1297 return mGeolocationPermissionsPrompt;
1301 * @return The application id string
1308 * Set the application id string
1311 void setAppId(String id) {
1316 * @return The original url associated with this Tab
1318 String getOriginalUrl() {
1319 return mOriginalUrl;
1323 * Set the original url associated with this tab
1325 void setOriginalUrl(String url) {
1330 * Get the url of this tab. Valid after calling populatePickerData, but
1331 * before calling wipePickerData, or if the webview has been destroyed.
1332 * @return The WebView's url or null.
1335 if (mPickerData != null) {
1336 return mPickerData.mUrl;
1342 * Get the title of this tab. Valid after calling populatePickerData, but
1343 * before calling wipePickerData, or if the webview has been destroyed. If
1344 * the url has no title, use the url instead.
1345 * @return The WebView's title (or url) or null.
1348 if (mPickerData != null) {
1349 return mPickerData.mTitle;
1355 * Get the favicon of this tab. Valid after calling populatePickerData, but
1356 * before calling wipePickerData, or if the webview has been destroyed.
1357 * @return The WebView's favicon or null.
1359 Bitmap getFavicon() {
1360 if (mPickerData != null) {
1361 return mPickerData.mFavicon;
1367 * Return the tab's error console. Creates the console if createIfNEcessary
1368 * is true and we haven't already created the console.
1369 * @param createIfNecessary Flag to indicate if the console should be
1370 * created if it has not been already.
1371 * @return The tab's error console, or null if one has not been created and
1372 * createIfNecessary is false.
1374 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1375 if (createIfNecessary && mErrorConsole == null) {
1376 mErrorConsole = new ErrorConsoleView(mActivity);
1377 mErrorConsole.setWebView(mMainView);
1379 return mErrorConsole;
1383 * If this Tab was created through another Tab, then this method returns
1385 * @return the Tab parent or null
1387 public Tab getParentTab() {
1392 * Return whether this tab should be closed when it is backing out of the
1394 * @return TRUE if this tab should be closed when exit.
1396 boolean closeOnExit() {
1397 return mCloseOnExit;
1401 * Saves the current lock-icon state before resetting the lock icon. If we
1402 * have an error, we may need to roll back to the previous state.
1404 void resetLockIcon(String url) {
1405 mPrevLockIconType = mLockIconType;
1406 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1407 if (URLUtil.isHttpsUrl(url)) {
1408 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1413 * Reverts the lock-icon state to the last saved state, for example, if we
1414 * had an error, and need to cancel the load.
1416 void revertLockIcon() {
1417 mLockIconType = mPrevLockIconType;
1421 * @return The tab's lock icon type.
1423 int getLockIconType() {
1424 return mLockIconType;
1428 * @return TRUE if onPageStarted is called while onPageFinished is not
1435 // force mInLoad to be false. This should only be called before closing the
1436 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1437 void clearInLoad() {
1441 void populatePickerData() {
1442 if (mMainView == null) {
1443 populatePickerDataFromSavedState();
1447 // FIXME: The only place we cared about subwindow was for
1448 // bookmarking (i.e. not when saving state). Was this deliberate?
1449 final WebBackForwardList list = mMainView.copyBackForwardList();
1450 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1451 populatePickerData(item);
1454 // Populate the picker data using the given history item and the current top
1456 private void populatePickerData(WebHistoryItem item) {
1457 mPickerData = new PickerData();
1459 mPickerData.mUrl = item.getUrl();
1460 mPickerData.mTitle = item.getTitle();
1461 mPickerData.mFavicon = item.getFavicon();
1462 if (mPickerData.mTitle == null) {
1463 mPickerData.mTitle = mPickerData.mUrl;
1468 // Create the PickerData and populate it using the saved state of the tab.
1469 void populatePickerDataFromSavedState() {
1470 if (mSavedState == null) {
1473 mPickerData = new PickerData();
1474 mPickerData.mUrl = mSavedState.getString(CURRURL);
1475 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1478 void clearPickerData() {
1483 * Get the saved state bundle.
1486 Bundle getSavedState() {
1491 * Set the saved state.
1493 void setSavedState(Bundle state) {
1494 mSavedState = state;
1498 * @return TRUE if succeed in saving the state.
1500 boolean saveState() {
1501 // If the WebView is null it means we ran low on memory and we already
1502 // stored the saved state in mSavedState.
1503 if (mMainView == null) {
1504 return mSavedState != null;
1507 mSavedState = new Bundle();
1508 final WebBackForwardList list = mMainView.saveState(mSavedState);
1510 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1511 mMainView.hashCode() + "_pic.save");
1512 if (mMainView.savePicture(mSavedState, f)) {
1513 mSavedState.putString(CURRPICTURE, f.getPath());
1517 // Store some extra info for displaying the tab in the picker.
1518 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1519 populatePickerData(item);
1521 if (mPickerData.mUrl != null) {
1522 mSavedState.putString(CURRURL, mPickerData.mUrl);
1524 if (mPickerData.mTitle != null) {
1525 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1527 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1528 if (mAppId != null) {
1529 mSavedState.putString(APPID, mAppId);
1531 if (mOriginalUrl != null) {
1532 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1534 // Remember the parent tab so the relationship can be restored.
1535 if (mParentTab != null) {
1536 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1543 * Restore the state of the tab.
1545 boolean restoreState(Bundle b) {
1549 // Restore the internal state even if the WebView fails to restore.
1550 // This will maintain the app id, original url and close-on-exit values.
1553 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1554 mAppId = b.getString(APPID);
1555 mOriginalUrl = b.getString(ORIGINALURL);
1557 final WebBackForwardList list = mMainView.restoreState(b);
1561 if (b.containsKey(CURRPICTURE)) {
1562 final File f = new File(b.getString(CURRPICTURE));
1563 mMainView.restorePicture(b, f);