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 a dialog informing the user of the network error reported by
308 * WebCore if it is in the foreground.
311 public void onReceivedError(WebView view, int errorCode,
312 String description, String failingUrl) {
313 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
314 errorCode != WebViewClient.ERROR_CONNECT &&
315 errorCode != WebViewClient.ERROR_BAD_URL &&
316 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
317 errorCode != WebViewClient.ERROR_FILE) {
318 queueError(errorCode, description);
320 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
321 + " " + description);
323 // We need to reset the title after an error if it is in foreground.
325 mActivity.resetTitleAndRevertLockIcon();
330 * Check with the user if it is ok to resend POST data as the page they
331 * are trying to navigate to is the result of a POST.
334 public void onFormResubmission(WebView view, final Message dontResend,
335 final Message resend) {
336 if (!mInForeground) {
337 dontResend.sendToTarget();
340 new AlertDialog.Builder(mActivity).setTitle(
341 R.string.browserFrameFormResubmitLabel).setMessage(
342 R.string.browserFrameFormResubmitMessage)
343 .setPositiveButton(R.string.ok,
344 new DialogInterface.OnClickListener() {
345 public void onClick(DialogInterface dialog,
347 resend.sendToTarget();
349 }).setNegativeButton(R.string.cancel,
350 new DialogInterface.OnClickListener() {
351 public void onClick(DialogInterface dialog,
353 dontResend.sendToTarget();
355 }).setOnCancelListener(new OnCancelListener() {
356 public void onCancel(DialogInterface dialog) {
357 dontResend.sendToTarget();
363 * Insert the url into the visited history database.
364 * @param url The url to be inserted.
365 * @param isReload True if this url is being reloaded.
366 * FIXME: Not sure what to do when reloading the page.
369 public void doUpdateVisitedHistory(WebView view, String url,
371 if (url.regionMatches(true, 0, "about:", 0, 6)) {
374 // remove "client" before updating it to the history so that it wont
375 // show up in the auto-complete list.
376 int index = url.indexOf("client=ms-");
377 if (index > 0 && url.contains(".google.")) {
378 int end = url.indexOf('&', index);
380 url = url.substring(0, index)
381 .concat(url.substring(end + 1));
383 // the url.charAt(index-1) should be either '?' or '&'
384 url = url.substring(0, index-1);
387 Browser.updateVisitedHistory(mActivity.getContentResolver(), url,
389 WebIconDatabase.getInstance().retainIconForPageUrl(url);
393 * Displays SSL error(s) dialog to the user.
396 public void onReceivedSslError(final WebView view,
397 final SslErrorHandler handler, final SslError error) {
398 if (!mInForeground) {
402 if (BrowserSettings.getInstance().showSecurityWarnings()) {
403 final LayoutInflater factory =
404 LayoutInflater.from(mActivity);
405 final View warningsView =
406 factory.inflate(R.layout.ssl_warnings, null);
407 final LinearLayout placeholder =
408 (LinearLayout)warningsView.findViewById(R.id.placeholder);
410 if (error.hasError(SslError.SSL_UNTRUSTED)) {
411 LinearLayout ll = (LinearLayout)factory
412 .inflate(R.layout.ssl_warning, null);
413 ((TextView)ll.findViewById(R.id.warning))
414 .setText(R.string.ssl_untrusted);
415 placeholder.addView(ll);
418 if (error.hasError(SslError.SSL_IDMISMATCH)) {
419 LinearLayout ll = (LinearLayout)factory
420 .inflate(R.layout.ssl_warning, null);
421 ((TextView)ll.findViewById(R.id.warning))
422 .setText(R.string.ssl_mismatch);
423 placeholder.addView(ll);
426 if (error.hasError(SslError.SSL_EXPIRED)) {
427 LinearLayout ll = (LinearLayout)factory
428 .inflate(R.layout.ssl_warning, null);
429 ((TextView)ll.findViewById(R.id.warning))
430 .setText(R.string.ssl_expired);
431 placeholder.addView(ll);
434 if (error.hasError(SslError.SSL_NOTYETVALID)) {
435 LinearLayout ll = (LinearLayout)factory
436 .inflate(R.layout.ssl_warning, null);
437 ((TextView)ll.findViewById(R.id.warning))
438 .setText(R.string.ssl_not_yet_valid);
439 placeholder.addView(ll);
442 new AlertDialog.Builder(mActivity).setTitle(
443 R.string.security_warning).setIcon(
444 android.R.drawable.ic_dialog_alert).setView(
445 warningsView).setPositiveButton(R.string.ssl_continue,
446 new DialogInterface.OnClickListener() {
447 public void onClick(DialogInterface dialog,
451 }).setNeutralButton(R.string.view_certificate,
452 new DialogInterface.OnClickListener() {
453 public void onClick(DialogInterface dialog,
455 mActivity.showSSLCertificateOnError(view,
458 }).setNegativeButton(R.string.cancel,
459 new DialogInterface.OnClickListener() {
460 public void onClick(DialogInterface dialog,
463 mActivity.resetTitleAndRevertLockIcon();
465 }).setOnCancelListener(
466 new DialogInterface.OnCancelListener() {
467 public void onCancel(DialogInterface dialog) {
469 mActivity.resetTitleAndRevertLockIcon();
478 * Handles an HTTP authentication request.
480 * @param handler The authentication handler
481 * @param host The host
482 * @param realm The realm
485 public void onReceivedHttpAuthRequest(WebView view,
486 final HttpAuthHandler handler, final String host,
487 final String realm) {
488 String username = null;
489 String password = null;
491 boolean reuseHttpAuthUsernamePassword = handler
492 .useHttpAuthUsernamePassword();
494 if (reuseHttpAuthUsernamePassword && mMainView != null) {
495 String[] credentials = mMainView.getHttpAuthUsernamePassword(
497 if (credentials != null && credentials.length == 2) {
498 username = credentials[0];
499 password = credentials[1];
503 if (username != null && password != null) {
504 handler.proceed(username, password);
507 mActivity.showHttpAuthentication(handler, host, realm,
508 null, null, null, 0);
516 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
517 if (!mInForeground) {
520 if (mActivity.isMenuDown()) {
521 // only check shortcut key when MENU is held
522 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
530 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
531 if (!mInForeground) {
534 if (event.isDown()) {
535 mActivity.onKeyDown(event.getKeyCode(), event);
537 mActivity.onKeyUp(event.getKeyCode(), event);
542 // -------------------------------------------------------------------------
543 // WebChromeClient implementation for the main WebView
544 // -------------------------------------------------------------------------
546 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
547 // Helper method to create a new tab or sub window.
548 private void createWindow(final boolean dialog, final Message msg) {
549 WebView.WebViewTransport transport =
550 (WebView.WebViewTransport) msg.obj;
553 mActivity.attachSubWindow(Tab.this);
554 transport.setWebView(mSubView);
556 final Tab newTab = mActivity.openTabAndShow(
557 BrowserActivity.EMPTY_URL_DATA, false, null);
558 if (newTab != Tab.this) {
559 Tab.this.addChildTab(newTab);
561 transport.setWebView(newTab.getWebView());
567 public boolean onCreateWindow(WebView view, final boolean dialog,
568 final boolean userGesture, final Message resultMsg) {
569 // only allow new window or sub window for the foreground case
570 if (!mInForeground) {
573 // Short-circuit if we can't create any more tabs or sub windows.
574 if (dialog && mSubView != null) {
575 new AlertDialog.Builder(mActivity)
576 .setTitle(R.string.too_many_subwindows_dialog_title)
577 .setIcon(android.R.drawable.ic_dialog_alert)
578 .setMessage(R.string.too_many_subwindows_dialog_message)
579 .setPositiveButton(R.string.ok, null)
582 } else if (!mActivity.getTabControl().canCreateNewTab()) {
583 new AlertDialog.Builder(mActivity)
584 .setTitle(R.string.too_many_windows_dialog_title)
585 .setIcon(android.R.drawable.ic_dialog_alert)
586 .setMessage(R.string.too_many_windows_dialog_message)
587 .setPositiveButton(R.string.ok, null)
592 // Short-circuit if this was a user gesture.
594 createWindow(dialog, resultMsg);
598 // Allow the popup and create the appropriate window.
599 final AlertDialog.OnClickListener allowListener =
600 new AlertDialog.OnClickListener() {
601 public void onClick(DialogInterface d,
603 createWindow(dialog, resultMsg);
607 // Block the popup by returning a null WebView.
608 final AlertDialog.OnClickListener blockListener =
609 new AlertDialog.OnClickListener() {
610 public void onClick(DialogInterface d, int which) {
611 resultMsg.sendToTarget();
615 // Build a confirmation dialog to display to the user.
616 final AlertDialog d =
617 new AlertDialog.Builder(mActivity)
618 .setTitle(R.string.attention)
619 .setIcon(android.R.drawable.ic_dialog_alert)
620 .setMessage(R.string.popup_window_attempt)
621 .setPositiveButton(R.string.allow, allowListener)
622 .setNegativeButton(R.string.block, blockListener)
623 .setCancelable(false)
626 // Show the confirmation dialog.
632 public void onRequestFocus(WebView view) {
633 if (!mInForeground) {
634 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
640 public void onCloseWindow(WebView window) {
641 if (mParentTab != null) {
642 // JavaScript can only close popup window.
644 mActivity.switchToTab(mActivity.getTabControl()
645 .getTabIndex(mParentTab));
647 mActivity.closeTab(Tab.this);
652 public void onProgressChanged(WebView view, int newProgress) {
653 if (newProgress == 100) {
654 // sync cookies and cache promptly here.
655 CookieSyncManager.getInstance().sync();
658 mActivity.onProgressChanged(view, newProgress);
663 public void onReceivedTitle(WebView view, String title) {
664 String url = view.getUrl();
666 // here, if url is null, we want to reset the title
667 mActivity.setUrlTitle(url, title);
670 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
673 // See if we can find the current url in our history database and
674 // add the new title to it.
675 if (url.startsWith("http://www.")) {
676 url = url.substring(11);
677 } else if (url.startsWith("http://")) {
678 url = url.substring(4);
681 final ContentResolver cr = mActivity.getContentResolver();
683 String [] selArgs = new String[] { url };
684 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
685 + Browser.BookmarkColumns.BOOKMARK + " = 0";
686 Cursor c = cr.query(Browser.BOOKMARKS_URI,
687 Browser.HISTORY_PROJECTION, where, selArgs, null);
688 if (c.moveToFirst()) {
689 // Current implementation of database only has one entry per
691 ContentValues map = new ContentValues();
692 map.put(Browser.BookmarkColumns.TITLE, title);
693 cr.update(Browser.BOOKMARKS_URI, map, "_id = "
694 + c.getInt(0), null);
697 } catch (IllegalStateException e) {
698 Log.e(LOGTAG, "Tab onReceived title", e);
699 } catch (SQLiteException ex) {
700 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
705 public void onReceivedIcon(WebView view, Bitmap icon) {
707 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
708 .getContentResolver(), view.getOriginalUrl(), view
712 mActivity.setFavicon(icon);
717 public void onReceivedTouchIconUrl(WebView view, String url,
718 boolean precomposed) {
719 final ContentResolver cr = mActivity.getContentResolver();
720 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
721 view.getOriginalUrl(), view.getUrl(), true);
723 if (c.getCount() > 0) {
724 // Let precomposed icons take precedence over non-composed
726 if (precomposed && mTouchIconLoader != null) {
727 mTouchIconLoader.cancel(false);
728 mTouchIconLoader = null;
730 // Have only one async task at a time.
731 if (mTouchIconLoader == null) {
732 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
734 mTouchIconLoader.execute(url);
743 public void onShowCustomView(View view,
744 WebChromeClient.CustomViewCallback callback) {
745 if (mInForeground) mActivity.onShowCustomView(view, callback);
749 public void onHideCustomView() {
750 if (mInForeground) mActivity.onHideCustomView();
754 * The origin has exceeded its database quota.
755 * @param url the URL that exceeded the quota
756 * @param databaseIdentifier the identifier of the database on which the
757 * transaction that caused the quota overflow was run
758 * @param currentQuota the current quota for the origin.
759 * @param estimatedSize the estimated size of the database.
760 * @param totalUsedQuota is the sum of all origins' quota.
761 * @param quotaUpdater The callback to run when a decision to allow or
762 * deny quota has been made. Don't forget to call this!
765 public void onExceededDatabaseQuota(String url,
766 String databaseIdentifier, long currentQuota, long estimatedSize,
767 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
768 BrowserSettings.getInstance().getWebStorageSizeManager()
769 .onExceededDatabaseQuota(url, databaseIdentifier,
770 currentQuota, estimatedSize, totalUsedQuota,
775 * The Application Cache has exceeded its max size.
776 * @param spaceNeeded is the amount of disk space that would be needed
777 * in order for the last appcache operation to succeed.
778 * @param totalUsedQuota is the sum of all origins' quota.
779 * @param quotaUpdater A callback to inform the WebCore thread that a
780 * new app cache size is available. This callback must always
781 * be executed at some point to ensure that the sleeping
782 * WebCore thread is woken up.
785 public void onReachedMaxAppCacheSize(long spaceNeeded,
786 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
787 BrowserSettings.getInstance().getWebStorageSizeManager()
788 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
793 * Instructs the browser to show a prompt to ask the user to set the
794 * Geolocation permission state for the specified origin.
795 * @param origin The origin for which Geolocation permissions are
797 * @param callback The callback to call once the user has set the
798 * Geolocation permission state.
801 public void onGeolocationPermissionsShowPrompt(String origin,
802 GeolocationPermissions.Callback callback) {
804 mGeolocationPermissionsPrompt.show(origin, callback);
809 * Instructs the browser to hide the Geolocation permissions prompt.
812 public void onGeolocationPermissionsHidePrompt() {
814 mGeolocationPermissionsPrompt.hide();
818 /* Adds a JavaScript error message to the system log and if the JS
819 * console is enabled in the about:debug options, to that console
821 * @param message The error message to report.
822 * @param lineNumber The line number of the error.
823 * @param sourceID The name of the source file that caused the error.
826 public void onConsoleMessage(String message, int lineNumber,
829 // call getErrorConsole(true) so it will create one if needed
830 ErrorConsoleView errorConsole = getErrorConsole(true);
831 errorConsole.addErrorMessage(message, sourceID, lineNumber);
832 if (mActivity.shouldShowErrorConsole()
833 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
834 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
837 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":"
842 * Ask the browser for an icon to represent a <video> element.
843 * This icon will be used if the Web page did not specify a poster attribute.
844 * @return Bitmap The icon or null if no such icon is available.
847 public Bitmap getDefaultVideoPoster() {
849 return mActivity.getDefaultVideoPoster();
855 * Ask the host application for a custom progress view to show while
856 * a <video> is loading.
857 * @return View The progress view.
860 public View getVideoLoadingProgressView() {
862 return mActivity.getVideoLoadingProgressView();
868 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
870 mActivity.openFileChooser(uploadMsg);
872 uploadMsg.onReceiveValue(null);
877 * Deliver a list of already-visited URLs
880 public void getVisitedHistory(final ValueCallback<String[]> callback) {
881 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
882 public String[] doInBackground(Void... unused) {
883 return Browser.getVisitedHistory(mActivity
884 .getContentResolver());
886 public void onPostExecute(String[] result) {
887 callback.onReceiveValue(result);
894 // -------------------------------------------------------------------------
895 // WebViewClient implementation for the sub window
896 // -------------------------------------------------------------------------
898 // Subclass of WebViewClient used in subwindows to notify the main
899 // WebViewClient of certain WebView activities.
900 private static class SubWindowClient extends WebViewClient {
901 // The main WebViewClient.
902 private final WebViewClient mClient;
904 SubWindowClient(WebViewClient client) {
908 public void doUpdateVisitedHistory(WebView view, String url,
910 mClient.doUpdateVisitedHistory(view, url, isReload);
913 public boolean shouldOverrideUrlLoading(WebView view, String url) {
914 return mClient.shouldOverrideUrlLoading(view, url);
917 public void onReceivedSslError(WebView view, SslErrorHandler handler,
919 mClient.onReceivedSslError(view, handler, error);
922 public void onReceivedHttpAuthRequest(WebView view,
923 HttpAuthHandler handler, String host, String realm) {
924 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
927 public void onFormResubmission(WebView view, Message dontResend,
929 mClient.onFormResubmission(view, dontResend, resend);
932 public void onReceivedError(WebView view, int errorCode,
933 String description, String failingUrl) {
934 mClient.onReceivedError(view, errorCode, description, failingUrl);
937 public boolean shouldOverrideKeyEvent(WebView view,
938 android.view.KeyEvent event) {
939 return mClient.shouldOverrideKeyEvent(view, event);
942 public void onUnhandledKeyEvent(WebView view,
943 android.view.KeyEvent event) {
944 mClient.onUnhandledKeyEvent(view, event);
948 // -------------------------------------------------------------------------
949 // WebChromeClient implementation for the sub window
950 // -------------------------------------------------------------------------
952 private class SubWindowChromeClient extends WebChromeClient {
953 // The main WebChromeClient.
954 private final WebChromeClient mClient;
956 SubWindowChromeClient(WebChromeClient client) {
960 public void onProgressChanged(WebView view, int newProgress) {
961 mClient.onProgressChanged(view, newProgress);
964 public boolean onCreateWindow(WebView view, boolean dialog,
965 boolean userGesture, android.os.Message resultMsg) {
966 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
969 public void onCloseWindow(WebView window) {
970 if (window != mSubView) {
971 Log.e(LOGTAG, "Can't close the window");
973 mActivity.dismissSubWindow(Tab.this);
977 // -------------------------------------------------------------------------
979 // Construct a new tab
980 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
982 mActivity = activity;
983 mCloseOnExit = closeOnExit;
986 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
987 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
989 mInForeground = false;
991 mInflateService = LayoutInflater.from(activity);
993 // The tab consists of a container view, which contains the main
994 // WebView, as well as any other UI elements associated with the tab.
995 mContainer = mInflateService.inflate(R.layout.tab, null);
997 mGeolocationPermissionsPrompt =
998 (GeolocationPermissionsPrompt) mContainer.findViewById(
999 R.id.geolocation_permissions_prompt);
1005 * Sets the WebView for this tab, correctly removing the old WebView from
1006 * the container view.
1008 void setWebView(WebView w) {
1009 if (mMainView == w) {
1012 // If the WebView is changing, the page will be reloaded, so any ongoing
1013 // Geolocation permission requests are void.
1014 mGeolocationPermissionsPrompt.hide();
1016 // Just remove the old one.
1017 FrameLayout wrapper =
1018 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1019 wrapper.removeView(mMainView);
1023 // attached the WebViewClient and WebChromeClient
1024 if (mMainView != null) {
1025 mMainView.setWebViewClient(mWebViewClient);
1026 mMainView.setWebChromeClient(mWebChromeClient);
1031 * Destroy the tab's main WebView and subWindow if any
1034 if (mMainView != null) {
1036 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1037 // save the WebView to call destroy() after detach it from the tab
1038 WebView webView = mMainView;
1045 * Remove the tab from the parent
1047 void removeFromTree() {
1048 // detach the children
1049 if (mChildTabs != null) {
1050 for(Tab t : mChildTabs) {
1051 t.setParentTab(null);
1054 // remove itself from the parent list
1055 if (mParentTab != null) {
1056 mParentTab.mChildTabs.remove(this);
1061 * Create a new subwindow unless a subwindow already exists.
1062 * @return True if a new subwindow was created. False if one already exists.
1064 boolean createSubWindow() {
1065 if (mSubView == null) {
1066 mSubViewContainer = mInflateService.inflate(
1067 R.layout.browser_subwindow, null);
1068 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1069 // use trackball directly
1070 mSubView.setMapTrackballToArrowKeys(false);
1071 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1072 mSubView.setWebChromeClient(new SubWindowChromeClient(
1074 mSubView.setDownloadListener(mActivity);
1075 mSubView.setOnCreateContextMenuListener(mActivity);
1076 final BrowserSettings s = BrowserSettings.getInstance();
1077 s.addObserver(mSubView.getSettings()).update(s, null);
1078 final ImageButton cancel = (ImageButton) mSubViewContainer
1079 .findViewById(R.id.subwindow_close);
1080 cancel.setOnClickListener(new OnClickListener() {
1081 public void onClick(View v) {
1082 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1091 * Dismiss the subWindow for the tab.
1093 void dismissSubWindow() {
1094 if (mSubView != null) {
1095 BrowserSettings.getInstance().deleteObserver(
1096 mSubView.getSettings());
1099 mSubViewContainer = null;
1104 * Attach the sub window to the content view.
1106 void attachSubWindow(ViewGroup content) {
1107 if (mSubView != null) {
1108 content.addView(mSubViewContainer,
1109 BrowserActivity.COVER_SCREEN_PARAMS);
1114 * Remove the sub window from the content view.
1116 void removeSubWindow(ViewGroup content) {
1117 if (mSubView != null) {
1118 content.removeView(mSubViewContainer);
1123 * This method attaches both the WebView and any sub window to the
1124 * given content view.
1126 void attachTabToContentView(ViewGroup content) {
1127 if (mMainView == null) {
1131 // Attach the WebView to the container and then attach the
1132 // container to the content view.
1133 FrameLayout wrapper =
1134 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1135 wrapper.addView(mMainView);
1136 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1137 attachSubWindow(content);
1141 * Remove the WebView and any sub window from the given content view.
1143 void removeTabFromContentView(ViewGroup content) {
1144 if (mMainView == null) {
1148 // Remove the container from the content and then remove the
1149 // WebView from the container. This will trigger a focus change
1150 // needed by WebView.
1151 FrameLayout wrapper =
1152 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1153 wrapper.removeView(mMainView);
1154 content.removeView(mContainer);
1155 removeSubWindow(content);
1159 * Set the parent tab of this tab.
1161 void setParentTab(Tab parent) {
1162 mParentTab = parent;
1163 // This tab may have been freed due to low memory. If that is the case,
1164 // the parent tab index is already saved. If we are changing that index
1165 // (most likely due to removing the parent tab) we must update the
1166 // parent tab index in the saved Bundle.
1167 if (mSavedState != null) {
1168 if (parent == null) {
1169 mSavedState.remove(PARENTTAB);
1171 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1172 .getTabIndex(parent));
1178 * When a Tab is created through the content of another Tab, then we
1179 * associate the Tabs.
1180 * @param child the Tab that was created from this Tab
1182 void addChildTab(Tab child) {
1183 if (mChildTabs == null) {
1184 mChildTabs = new Vector<Tab>();
1186 mChildTabs.add(child);
1187 child.setParentTab(this);
1190 Vector<Tab> getChildTabs() {
1195 if (mMainView != null) {
1196 mMainView.onResume();
1197 if (mSubView != null) {
1198 mSubView.onResume();
1204 if (mMainView != null) {
1205 mMainView.onPause();
1206 if (mSubView != null) {
1212 void putInForeground() {
1213 mInForeground = true;
1215 mMainView.setOnCreateContextMenuListener(mActivity);
1216 if (mSubView != null) {
1217 mSubView.setOnCreateContextMenuListener(mActivity);
1219 // Show the pending error dialog if the queue is not empty
1220 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1221 showError(mQueuedErrors.getFirst());
1225 void putInBackground() {
1226 mInForeground = false;
1228 mMainView.setOnCreateContextMenuListener(null);
1229 if (mSubView != null) {
1230 mSubView.setOnCreateContextMenuListener(null);
1235 * Return the top window of this tab; either the subwindow if it is not
1236 * null or the main window.
1237 * @return The top window of this tab.
1239 WebView getTopWindow() {
1240 if (mSubView != null) {
1247 * Return the main window of this tab. Note: if a tab is freed in the
1248 * background, this can return null. It is only guaranteed to be
1249 * non-null for the current tab.
1250 * @return The main WebView of this tab.
1252 WebView getWebView() {
1257 * Return the subwindow of this tab or null if there is no subwindow.
1258 * @return The subwindow of this tab or null.
1260 WebView getSubWebView() {
1265 * @return The geolocation permissions prompt for this tab.
1267 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1268 return mGeolocationPermissionsPrompt;
1272 * @return The application id string
1279 * Set the application id string
1282 void setAppId(String id) {
1287 * @return The original url associated with this Tab
1289 String getOriginalUrl() {
1290 return mOriginalUrl;
1294 * Set the original url associated with this tab
1296 void setOriginalUrl(String url) {
1301 * Get the url of this tab. Valid after calling populatePickerData, but
1302 * before calling wipePickerData, or if the webview has been destroyed.
1303 * @return The WebView's url or null.
1306 if (mPickerData != null) {
1307 return mPickerData.mUrl;
1313 * Get the title of this tab. Valid after calling populatePickerData, but
1314 * before calling wipePickerData, or if the webview has been destroyed. If
1315 * the url has no title, use the url instead.
1316 * @return The WebView's title (or url) or null.
1319 if (mPickerData != null) {
1320 return mPickerData.mTitle;
1326 * Get the favicon of this tab. Valid after calling populatePickerData, but
1327 * before calling wipePickerData, or if the webview has been destroyed.
1328 * @return The WebView's favicon or null.
1330 Bitmap getFavicon() {
1331 if (mPickerData != null) {
1332 return mPickerData.mFavicon;
1338 * Return the tab's error console. Creates the console if createIfNEcessary
1339 * is true and we haven't already created the console.
1340 * @param createIfNecessary Flag to indicate if the console should be
1341 * created if it has not been already.
1342 * @return The tab's error console, or null if one has not been created and
1343 * createIfNecessary is false.
1345 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1346 if (createIfNecessary && mErrorConsole == null) {
1347 mErrorConsole = new ErrorConsoleView(mActivity);
1348 mErrorConsole.setWebView(mMainView);
1350 return mErrorConsole;
1354 * If this Tab was created through another Tab, then this method returns
1356 * @return the Tab parent or null
1358 public Tab getParentTab() {
1363 * Return whether this tab should be closed when it is backing out of the
1365 * @return TRUE if this tab should be closed when exit.
1367 boolean closeOnExit() {
1368 return mCloseOnExit;
1372 * Saves the current lock-icon state before resetting the lock icon. If we
1373 * have an error, we may need to roll back to the previous state.
1375 void resetLockIcon(String url) {
1376 mPrevLockIconType = mLockIconType;
1377 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1378 if (URLUtil.isHttpsUrl(url)) {
1379 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1384 * Reverts the lock-icon state to the last saved state, for example, if we
1385 * had an error, and need to cancel the load.
1387 void revertLockIcon() {
1388 mLockIconType = mPrevLockIconType;
1392 * @return The tab's lock icon type.
1394 int getLockIconType() {
1395 return mLockIconType;
1399 * @return TRUE if onPageStarted is called while onPageFinished is not
1406 // force mInLoad to be false. This should only be called before closing the
1407 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1408 void clearInLoad() {
1412 void populatePickerData() {
1413 if (mMainView == null) {
1414 populatePickerDataFromSavedState();
1418 // FIXME: The only place we cared about subwindow was for
1419 // bookmarking (i.e. not when saving state). Was this deliberate?
1420 final WebBackForwardList list = mMainView.copyBackForwardList();
1421 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1422 populatePickerData(item);
1425 // Populate the picker data using the given history item and the current top
1427 private void populatePickerData(WebHistoryItem item) {
1428 mPickerData = new PickerData();
1430 mPickerData.mUrl = item.getUrl();
1431 mPickerData.mTitle = item.getTitle();
1432 mPickerData.mFavicon = item.getFavicon();
1433 if (mPickerData.mTitle == null) {
1434 mPickerData.mTitle = mPickerData.mUrl;
1439 // Create the PickerData and populate it using the saved state of the tab.
1440 void populatePickerDataFromSavedState() {
1441 if (mSavedState == null) {
1444 mPickerData = new PickerData();
1445 mPickerData.mUrl = mSavedState.getString(CURRURL);
1446 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1449 void clearPickerData() {
1454 * Get the saved state bundle.
1457 Bundle getSavedState() {
1462 * Set the saved state.
1464 void setSavedState(Bundle state) {
1465 mSavedState = state;
1469 * @return TRUE if succeed in saving the state.
1471 boolean saveState() {
1472 // If the WebView is null it means we ran low on memory and we already
1473 // stored the saved state in mSavedState.
1474 if (mMainView == null) {
1475 return mSavedState != null;
1478 mSavedState = new Bundle();
1479 final WebBackForwardList list = mMainView.saveState(mSavedState);
1481 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1482 mMainView.hashCode() + "_pic.save");
1483 if (mMainView.savePicture(mSavedState, f)) {
1484 mSavedState.putString(CURRPICTURE, f.getPath());
1488 // Store some extra info for displaying the tab in the picker.
1489 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1490 populatePickerData(item);
1492 if (mPickerData.mUrl != null) {
1493 mSavedState.putString(CURRURL, mPickerData.mUrl);
1495 if (mPickerData.mTitle != null) {
1496 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1498 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1499 if (mAppId != null) {
1500 mSavedState.putString(APPID, mAppId);
1502 if (mOriginalUrl != null) {
1503 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1505 // Remember the parent tab so the relationship can be restored.
1506 if (mParentTab != null) {
1507 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1514 * Restore the state of the tab.
1516 boolean restoreState(Bundle b) {
1520 // Restore the internal state even if the WebView fails to restore.
1521 // This will maintain the app id, original url and close-on-exit values.
1524 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1525 mAppId = b.getString(APPID);
1526 mOriginalUrl = b.getString(ORIGINALURL);
1528 final WebBackForwardList list = mMainView.restoreState(b);
1532 if (b.containsKey(CURRPICTURE)) {
1533 final File f = new File(b.getString(CURRPICTURE));
1534 mMainView.restorePicture(b, f);