blob: 11f85660a32e4d6f8c4febab5c7da2f229154c42 [file] [log] [blame]
Grace Kloba22ac16e2009-10-07 18:00:23 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050019import com.android.browser.TabControl.TabChangeListener;
20import com.android.common.speech.LoggingEvents;
21
Grace Kloba22ac16e2009-10-07 18:00:23 -070022import android.app.AlertDialog;
Leon Scroggins58d56c62010-01-28 15:12:40 -050023import android.app.SearchManager;
Grace Kloba22ac16e2009-10-07 18:00:23 -070024import android.content.ContentResolver;
25import android.content.ContentValues;
26import android.content.DialogInterface;
Michael Kolbfe251992010-07-08 15:41:55 -070027import android.content.DialogInterface.OnCancelListener;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050028import android.content.Intent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070029import android.database.Cursor;
30import android.database.sqlite.SQLiteDatabase;
31import android.database.sqlite.SQLiteException;
32import android.graphics.Bitmap;
33import android.net.Uri;
34import android.net.http.SslError;
35import android.os.AsyncTask;
36import android.os.Bundle;
37import android.os.Message;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +000038import android.os.SystemClock;
Grace Kloba22ac16e2009-10-07 18:00:23 -070039import android.provider.Browser;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050040import android.provider.BrowserContract.History;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050041import android.speech.RecognizerResultsIntent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070042import android.util.Log;
43import android.view.KeyEvent;
44import android.view.LayoutInflater;
45import android.view.View;
Jeff Hamilton8ce956c2010-08-17 11:13:53 -050046import android.view.View.OnClickListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070047import android.view.ViewGroup;
Grace Kloba50c241e2010-04-20 11:07:50 -070048import android.view.ViewStub;
Ben Murdochc42addf2010-01-28 15:19:59 +000049import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070050import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050051import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070052import android.webkit.GeolocationPermissions;
53import android.webkit.HttpAuthHandler;
54import android.webkit.SslErrorHandler;
55import android.webkit.URLUtil;
56import android.webkit.ValueCallback;
57import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050058import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070059import android.webkit.WebChromeClient;
60import android.webkit.WebHistoryItem;
61import android.webkit.WebIconDatabase;
62import android.webkit.WebStorage;
63import android.webkit.WebView;
64import android.webkit.WebViewClient;
65import android.widget.FrameLayout;
66import android.widget.ImageButton;
67import android.widget.LinearLayout;
68import android.widget.TextView;
69
Michael Kolbfe251992010-07-08 15:41:55 -070070import java.util.ArrayList;
71import java.util.HashMap;
72import java.util.Iterator;
73import java.util.LinkedList;
74import java.util.Map;
75import java.util.Vector;
76
Grace Kloba22ac16e2009-10-07 18:00:23 -070077/**
78 * Class for maintaining Tabs with a main WebView and a subwindow.
79 */
80class Tab {
81 // Log Tag
82 private static final String LOGTAG = "Tab";
Ben Murdochc42addf2010-01-28 15:19:59 +000083 // Special case the logtag for messages for the Console to make it easier to
84 // filter them and match the logtag used for these messages in older versions
85 // of the browser.
86 private static final String CONSOLE_LOGTAG = "browser";
87
Grace Kloba22ac16e2009-10-07 18:00:23 -070088 // The Geolocation permissions prompt
89 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
90 // Main WebView wrapper
Leon Scroggins III211ba542010-04-19 13:21:13 -040091 private LinearLayout mContainer;
Grace Kloba22ac16e2009-10-07 18:00:23 -070092 // Main WebView
93 private WebView mMainView;
94 // Subwindow container
95 private View mSubViewContainer;
96 // Subwindow WebView
97 private WebView mSubView;
98 // Saved bundle for when we are running low on memory. It contains the
99 // information needed to restore the WebView if the user goes back to the
100 // tab.
101 private Bundle mSavedState;
102 // Data used when displaying the tab in the picker.
103 private PickerData mPickerData;
104 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
105 // created by the UI
106 private Tab mParentTab;
107 // Tab that constructed by this Tab. This is used when this Tab is
108 // destroyed, it clears all mParentTab values in the children.
109 private Vector<Tab> mChildTabs;
110 // If true, the tab will be removed when back out of the first page.
111 private boolean mCloseOnExit;
112 // If true, the tab is in the foreground of the current activity.
113 private boolean mInForeground;
114 // If true, the tab is in loading state.
115 private boolean mInLoad;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000116 // The time the load started, used to find load page time
117 private long mLoadStartTime;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700118 // Application identifier used to find tabs that another application wants
119 // to reuse.
120 private String mAppId;
121 // Keep the original url around to avoid killing the old WebView if the url
122 // has not changed.
123 private String mOriginalUrl;
124 // Error console for the tab
125 private ErrorConsoleView mErrorConsole;
126 // the lock icon type and previous lock icon type for the tab
127 private int mLockIconType;
128 private int mPrevLockIconType;
129 // Inflation service for making subwindows.
130 private final LayoutInflater mInflateService;
131 // The BrowserActivity which owners the Tab
132 private final BrowserActivity mActivity;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -0500133 // The listener that gets invoked when a download is started from the
134 // mMainView
135 private final DownloadListener mDownloadListener;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500136 // Listener used to know when we move forward or back in the history list.
137 private final WebBackForwardListClient mWebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700138
139 // AsyncTask for downloading touch icons
140 DownloadTouchIcon mTouchIconLoader;
141
142 // Extra saved information for displaying the tab in the picker.
143 private static class PickerData {
144 String mUrl;
145 String mTitle;
146 Bitmap mFavicon;
147 }
148
149 // Used for saving and restoring each Tab
150 static final String WEBVIEW = "webview";
151 static final String NUMTABS = "numTabs";
152 static final String CURRTAB = "currentTab";
153 static final String CURRURL = "currentUrl";
154 static final String CURRTITLE = "currentTitle";
Grace Kloba22ac16e2009-10-07 18:00:23 -0700155 static final String CLOSEONEXIT = "closeonexit";
156 static final String PARENTTAB = "parentTab";
157 static final String APPID = "appid";
158 static final String ORIGINALURL = "originalUrl";
Elliott Slaughter3d6df162010-08-25 13:17:44 -0700159 static final String INCOGNITO = "privateBrowsingEnabled";
Grace Kloba22ac16e2009-10-07 18:00:23 -0700160
161 // -------------------------------------------------------------------------
162
Leon Scroggins58d56c62010-01-28 15:12:40 -0500163 /**
164 * Private information regarding the latest voice search. If the Tab is not
165 * in voice search mode, this will be null.
166 */
167 private VoiceSearchData mVoiceSearchData;
168 /**
169 * Return whether the tab is in voice search mode.
170 */
171 public boolean isInVoiceSearchMode() {
172 return mVoiceSearchData != null;
173 }
174 /**
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400175 * Return true if the Tab is in voice search mode and the voice search
176 * Intent came with a String identifying that Google provided the Intent.
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500177 */
178 public boolean voiceSearchSourceIsGoogle() {
179 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
180 }
181 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500182 * Get the title to display for the current voice search page. If the Tab
183 * is not in voice search mode, return null.
184 */
185 public String getVoiceDisplayTitle() {
186 if (mVoiceSearchData == null) return null;
187 return mVoiceSearchData.mLastVoiceSearchTitle;
188 }
189 /**
190 * Get the latest array of voice search results, to be passed to the
191 * BrowserProvider. If the Tab is not in voice search mode, return null.
192 */
193 public ArrayList<String> getVoiceSearchResults() {
194 if (mVoiceSearchData == null) return null;
195 return mVoiceSearchData.mVoiceSearchResults;
196 }
197 /**
198 * Activate voice search mode.
199 * @param intent Intent which has the results to use, or an index into the
200 * results when reusing the old results.
201 */
202 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500203 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500204 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500205 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500206 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500207 ArrayList<String> urls = intent.getStringArrayListExtra(
208 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
209 ArrayList<String> htmls = intent.getStringArrayListExtra(
210 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
211 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
212 RecognizerResultsIntent
213 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500214 // This tab is now entering voice search mode for the first time, or
215 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500216 int size = results.size();
217 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500218 throw new AssertionError("improper extras passed in Intent");
219 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500220 if (htmls == null || htmls.size() != size || baseUrls == null ||
221 (baseUrls.size() != size && baseUrls.size() != 1)) {
222 // If either of these arrays are empty/incorrectly sized, ignore
223 // them.
224 htmls = null;
225 baseUrls = null;
226 }
227 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
228 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500229 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
230 RecognizerResultsIntent
231 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500232 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
233 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400234 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500235 }
236 String extraData = intent.getStringExtra(
237 SearchManager.EXTRA_DATA_KEY);
238 if (extraData != null) {
239 index = Integer.parseInt(extraData);
240 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
241 throw new AssertionError("index must be less than "
242 + "size of mVoiceSearchResults");
243 }
244 if (mVoiceSearchData.mSourceIsGoogle) {
245 Intent logIntent = new Intent(
246 LoggingEvents.ACTION_LOG_EVENT);
247 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
248 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
249 logIntent.putExtra(
250 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
251 index);
252 mActivity.sendBroadcast(logIntent);
253 }
254 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400255 // Copy the Intent, so that each history item will have its own
256 // Intent, with different (or none) extra data.
257 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
258 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
259 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500260 }
261 }
262 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500263 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500264 if (mInForeground) {
265 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
266 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500267 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
268 // When index was found it was already ensured that it was valid
269 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
270 if (uriString != null) {
271 Uri dataUri = Uri.parse(uriString);
272 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
273 dataUri.getScheme())) {
274 // If there is only one base URL, use it. If there are
275 // more, there will be one for each index, so use the base
276 // URL corresponding to the index.
277 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
278 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
279 index : 0);
280 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
281 mMainView.loadDataWithBaseURL(baseUrl,
282 uriString.substring(RecognizerResultsIntent
283 .URI_SCHEME_INLINE.length() + 1), "text/html",
284 "utf-8", baseUrl);
285 return;
286 }
287 }
288 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500289 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500290 = mVoiceSearchData.mVoiceSearchUrls.get(index);
291 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
292 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
293 mVoiceSearchData.mLastVoiceSearchTitle);
294 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500295 Map<String, String> headers = null;
296 if (mVoiceSearchData.mHeaders != null) {
297 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
298 : index;
299 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
300 if (bundle != null && !bundle.isEmpty()) {
301 Iterator<String> iter = bundle.keySet().iterator();
302 headers = new HashMap<String, String>();
303 while (iter.hasNext()) {
304 String key = iter.next();
305 headers.put(key, bundle.getString(key));
306 }
307 }
308 }
309 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 }
311 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500312 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500313 ArrayList<String> urls, ArrayList<String> htmls,
314 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500315 mVoiceSearchResults = results;
316 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500317 mVoiceSearchHtmls = htmls;
318 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500319 }
320 /*
321 * ArrayList of suggestions to be displayed when opening the
322 * SearchManager
323 */
324 public ArrayList<String> mVoiceSearchResults;
325 /*
326 * ArrayList of urls, associated with the suggestions in
327 * mVoiceSearchResults.
328 */
329 public ArrayList<String> mVoiceSearchUrls;
330 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500331 * ArrayList holding content to load for each item in
332 * mVoiceSearchResults.
333 */
334 public ArrayList<String> mVoiceSearchHtmls;
335 /*
336 * ArrayList holding base urls for the items in mVoiceSearchResults.
337 * If non null, this will either have the same size as
338 * mVoiceSearchResults or have a size of 1, in which case all will use
339 * the same base url
340 */
341 public ArrayList<String> mVoiceSearchBaseUrls;
342 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500343 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500344 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500345 */
346 public String mLastVoiceSearchUrl;
347 /**
348 * The last title used for voice search. Needed to update the title bar
349 * when switching tabs.
350 */
351 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500352 /**
353 * Whether the Intent which turned on voice search mode contained the
354 * String signifying that Google was the source.
355 */
356 public boolean mSourceIsGoogle;
357 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500358 * List of headers to be passed into the WebView containing location
359 * information
360 */
361 public ArrayList<Bundle> mHeaders;
362 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500363 * The Intent used to invoke voice search. Placed on the
364 * WebHistoryItem so that when coming back to a previous voice search
365 * page we can again activate voice search.
366 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500367 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500368 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500369 * String used to identify Google as the source of voice search.
370 */
371 public static String SOURCE_IS_GOOGLE
372 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500373 }
374
Grace Kloba22ac16e2009-10-07 18:00:23 -0700375 // Container class for the next error dialog that needs to be displayed
376 private class ErrorDialog {
377 public final int mTitle;
378 public final String mDescription;
379 public final int mError;
380 ErrorDialog(int title, String desc, int error) {
381 mTitle = title;
382 mDescription = desc;
383 mError = error;
384 }
385 };
386
387 private void processNextError() {
388 if (mQueuedErrors == null) {
389 return;
390 }
391 // The first one is currently displayed so just remove it.
392 mQueuedErrors.removeFirst();
393 if (mQueuedErrors.size() == 0) {
394 mQueuedErrors = null;
395 return;
396 }
397 showError(mQueuedErrors.getFirst());
398 }
399
400 private DialogInterface.OnDismissListener mDialogListener =
401 new DialogInterface.OnDismissListener() {
402 public void onDismiss(DialogInterface d) {
403 processNextError();
404 }
405 };
406 private LinkedList<ErrorDialog> mQueuedErrors;
407
408 private void queueError(int err, String desc) {
409 if (mQueuedErrors == null) {
410 mQueuedErrors = new LinkedList<ErrorDialog>();
411 }
412 for (ErrorDialog d : mQueuedErrors) {
413 if (d.mError == err) {
414 // Already saw a similar error, ignore the new one.
415 return;
416 }
417 }
418 ErrorDialog errDialog = new ErrorDialog(
419 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
420 R.string.browserFrameFileErrorLabel :
421 R.string.browserFrameNetworkErrorLabel,
422 desc, err);
423 mQueuedErrors.addLast(errDialog);
424
425 // Show the dialog now if the queue was empty and it is in foreground
426 if (mQueuedErrors.size() == 1 && mInForeground) {
427 showError(errDialog);
428 }
429 }
430
431 private void showError(ErrorDialog errDialog) {
432 if (mInForeground) {
433 AlertDialog d = new AlertDialog.Builder(mActivity)
434 .setTitle(errDialog.mTitle)
435 .setMessage(errDialog.mDescription)
436 .setPositiveButton(R.string.ok, null)
437 .create();
438 d.setOnDismissListener(mDialogListener);
439 d.show();
440 }
441 }
442
443 // -------------------------------------------------------------------------
444 // WebViewClient implementation for the main WebView
445 // -------------------------------------------------------------------------
446
447 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500448 private Message mDontResend;
449 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700450 @Override
451 public void onPageStarted(WebView view, String url, Bitmap favicon) {
452 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000453 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500454 if (mVoiceSearchData != null
455 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500456 if (mVoiceSearchData.mSourceIsGoogle) {
457 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
458 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
459 mActivity.sendBroadcast(i);
460 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500461 mVoiceSearchData = null;
462 if (mInForeground) {
463 mActivity.revertVoiceTitleBar();
464 }
465 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700466
467 // We've started to load a new page. If there was a pending message
468 // to save a screenshot then we will now take the new page and save
469 // an incorrect screenshot. Therefore, remove any pending thumbnail
470 // messages from the queue.
471 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
472 view);
473
474 // If we start a touch icon load and then load a new page, we don't
475 // want to cancel the current touch icon loader. But, we do want to
476 // create a new one when the touch icon url is known.
477 if (mTouchIconLoader != null) {
478 mTouchIconLoader.mTab = null;
479 mTouchIconLoader = null;
480 }
481
482 // reset the error console
483 if (mErrorConsole != null) {
484 mErrorConsole.clearErrorMessages();
485 if (mActivity.shouldShowErrorConsole()) {
486 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
487 }
488 }
489
490 // update the bookmark database for favicon
491 if (favicon != null) {
Jeff Hamilton84029622010-08-05 14:29:28 -0500492 Bookmarks.updateBookmarkFavicon(mActivity
Patrick Scottcc949122010-03-17 16:06:30 -0400493 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700494 }
495
496 // reset sync timer to avoid sync starts during loading a page
497 CookieSyncManager.getInstance().resetSync();
498
499 if (!mActivity.isNetworkUp()) {
500 view.setNetworkAvailable(false);
501 }
502
503 // finally update the UI in the activity if it is in the foreground
504 if (mInForeground) {
505 mActivity.onPageStarted(view, url, favicon);
506 }
Michael Kolbfe251992010-07-08 15:41:55 -0700507 if (getTabChangeListener() != null) {
508 getTabChangeListener().onPageStarted(Tab.this);
509 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700510 }
511
512 @Override
513 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000514 LogTag.logPageFinishedLoading(
515 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700516 mInLoad = false;
517
518 if (mInForeground && !mActivity.didUserStopLoading()
519 || !mInForeground) {
520 // Only update the bookmark screenshot if the user did not
521 // cancel the load early.
522 mActivity.postMessage(
523 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
524 500);
525 }
526
527 // finally update the UI in the activity if it is in the foreground
528 if (mInForeground) {
529 mActivity.onPageFinished(view, url);
530 }
Michael Kolbfe251992010-07-08 15:41:55 -0700531 if (getTabChangeListener() != null) {
532 getTabChangeListener().onPageFinished(Tab.this);
533 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700534 }
535
536 // return true if want to hijack the url to let another app to handle it
537 @Override
538 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400539 if (voiceSearchSourceIsGoogle()) {
540 // This method is called when the user clicks on a link.
541 // VoiceSearchMode is turned off when the user leaves the
542 // Google results page, so at this point the user must be on
543 // that page. If the user clicked a link on that page, assume
544 // that the voice search was effective, and broadcast an Intent
545 // so a receiver can take note of that fact.
546 Intent logIntent = new Intent(LoggingEvents.ACTION_LOG_EVENT);
547 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
548 LoggingEvents.VoiceSearch.RESULT_CLICKED);
549 mActivity.sendBroadcast(logIntent);
550 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700551 if (mInForeground) {
552 return mActivity.shouldOverrideUrlLoading(view, url);
553 } else {
554 return false;
555 }
556 }
557
558 /**
559 * Updates the lock icon. This method is called when we discover another
560 * resource to be loaded for this page (for example, javascript). While
561 * we update the icon type, we do not update the lock icon itself until
562 * we are done loading, it is slightly more secure this way.
563 */
564 @Override
565 public void onLoadResource(WebView view, String url) {
566 if (url != null && url.length() > 0) {
567 // It is only if the page claims to be secure that we may have
568 // to update the lock:
569 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
570 // If NOT a 'safe' url, change the lock to mixed content!
571 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
572 || URLUtil.isAboutUrl(url))) {
573 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
574 }
575 }
576 }
577 }
578
579 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700580 * Show a dialog informing the user of the network error reported by
581 * WebCore if it is in the foreground.
582 */
583 @Override
584 public void onReceivedError(WebView view, int errorCode,
585 String description, String failingUrl) {
586 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
587 errorCode != WebViewClient.ERROR_CONNECT &&
588 errorCode != WebViewClient.ERROR_BAD_URL &&
589 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
590 errorCode != WebViewClient.ERROR_FILE) {
591 queueError(errorCode, description);
592 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500593
594 // Don't log URLs when in private browsing mode
595 if (!getWebView().isPrivateBrowsingEnabled()) {
596 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
597 + " " + description);
598 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700599
600 // We need to reset the title after an error if it is in foreground.
601 if (mInForeground) {
602 mActivity.resetTitleAndRevertLockIcon();
603 }
604 }
605
606 /**
607 * Check with the user if it is ok to resend POST data as the page they
608 * are trying to navigate to is the result of a POST.
609 */
610 @Override
611 public void onFormResubmission(WebView view, final Message dontResend,
612 final Message resend) {
613 if (!mInForeground) {
614 dontResend.sendToTarget();
615 return;
616 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500617 if (mDontResend != null) {
618 Log.w(LOGTAG, "onFormResubmission should not be called again "
619 + "while dialog is still up");
620 dontResend.sendToTarget();
621 return;
622 }
623 mDontResend = dontResend;
624 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700625 new AlertDialog.Builder(mActivity).setTitle(
626 R.string.browserFrameFormResubmitLabel).setMessage(
627 R.string.browserFrameFormResubmitMessage)
628 .setPositiveButton(R.string.ok,
629 new DialogInterface.OnClickListener() {
630 public void onClick(DialogInterface dialog,
631 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500632 if (mResend != null) {
633 mResend.sendToTarget();
634 mResend = null;
635 mDontResend = null;
636 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700637 }
638 }).setNegativeButton(R.string.cancel,
639 new DialogInterface.OnClickListener() {
640 public void onClick(DialogInterface dialog,
641 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500642 if (mDontResend != null) {
643 mDontResend.sendToTarget();
644 mResend = null;
645 mDontResend = null;
646 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700647 }
648 }).setOnCancelListener(new OnCancelListener() {
649 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500650 if (mDontResend != null) {
651 mDontResend.sendToTarget();
652 mResend = null;
653 mDontResend = null;
654 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700655 }
656 }).show();
657 }
658
659 /**
660 * Insert the url into the visited history database.
661 * @param url The url to be inserted.
662 * @param isReload True if this url is being reloaded.
663 * FIXME: Not sure what to do when reloading the page.
664 */
665 @Override
666 public void doUpdateVisitedHistory(WebView view, String url,
667 boolean isReload) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500668 // Don't save anything in private browsing mode
669 if (getWebView().isPrivateBrowsingEnabled()) return;
670
Grace Kloba22ac16e2009-10-07 18:00:23 -0700671 if (url.regionMatches(true, 0, "about:", 0, 6)) {
672 return;
673 }
674 // remove "client" before updating it to the history so that it wont
675 // show up in the auto-complete list.
676 int index = url.indexOf("client=ms-");
677 if (index > 0 && url.contains(".google.")) {
678 int end = url.indexOf('&', index);
679 if (end > 0) {
680 url = url.substring(0, index)
681 .concat(url.substring(end + 1));
682 } else {
683 // the url.charAt(index-1) should be either '?' or '&'
684 url = url.substring(0, index-1);
685 }
686 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400687 final ContentResolver cr = mActivity.getContentResolver();
688 final String newUrl = url;
689 new AsyncTask<Void, Void, Void>() {
Michael Kolbfe251992010-07-08 15:41:55 -0700690 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400691 protected Void doInBackground(Void... unused) {
692 Browser.updateVisitedHistory(cr, newUrl, true);
693 return null;
694 }
695 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700696 WebIconDatabase.getInstance().retainIconForPageUrl(url);
697 }
698
699 /**
700 * Displays SSL error(s) dialog to the user.
701 */
702 @Override
703 public void onReceivedSslError(final WebView view,
704 final SslErrorHandler handler, final SslError error) {
705 if (!mInForeground) {
706 handler.cancel();
707 return;
708 }
709 if (BrowserSettings.getInstance().showSecurityWarnings()) {
710 final LayoutInflater factory =
711 LayoutInflater.from(mActivity);
712 final View warningsView =
713 factory.inflate(R.layout.ssl_warnings, null);
714 final LinearLayout placeholder =
715 (LinearLayout)warningsView.findViewById(R.id.placeholder);
716
717 if (error.hasError(SslError.SSL_UNTRUSTED)) {
718 LinearLayout ll = (LinearLayout)factory
719 .inflate(R.layout.ssl_warning, null);
720 ((TextView)ll.findViewById(R.id.warning))
721 .setText(R.string.ssl_untrusted);
722 placeholder.addView(ll);
723 }
724
725 if (error.hasError(SslError.SSL_IDMISMATCH)) {
726 LinearLayout ll = (LinearLayout)factory
727 .inflate(R.layout.ssl_warning, null);
728 ((TextView)ll.findViewById(R.id.warning))
729 .setText(R.string.ssl_mismatch);
730 placeholder.addView(ll);
731 }
732
733 if (error.hasError(SslError.SSL_EXPIRED)) {
734 LinearLayout ll = (LinearLayout)factory
735 .inflate(R.layout.ssl_warning, null);
736 ((TextView)ll.findViewById(R.id.warning))
737 .setText(R.string.ssl_expired);
738 placeholder.addView(ll);
739 }
740
741 if (error.hasError(SslError.SSL_NOTYETVALID)) {
742 LinearLayout ll = (LinearLayout)factory
743 .inflate(R.layout.ssl_warning, null);
744 ((TextView)ll.findViewById(R.id.warning))
745 .setText(R.string.ssl_not_yet_valid);
746 placeholder.addView(ll);
747 }
748
749 new AlertDialog.Builder(mActivity).setTitle(
750 R.string.security_warning).setIcon(
751 android.R.drawable.ic_dialog_alert).setView(
752 warningsView).setPositiveButton(R.string.ssl_continue,
753 new DialogInterface.OnClickListener() {
754 public void onClick(DialogInterface dialog,
755 int whichButton) {
756 handler.proceed();
757 }
758 }).setNeutralButton(R.string.view_certificate,
759 new DialogInterface.OnClickListener() {
760 public void onClick(DialogInterface dialog,
761 int whichButton) {
762 mActivity.showSSLCertificateOnError(view,
763 handler, error);
764 }
765 }).setNegativeButton(R.string.cancel,
766 new DialogInterface.OnClickListener() {
767 public void onClick(DialogInterface dialog,
768 int whichButton) {
769 handler.cancel();
770 mActivity.resetTitleAndRevertLockIcon();
771 }
772 }).setOnCancelListener(
773 new DialogInterface.OnCancelListener() {
774 public void onCancel(DialogInterface dialog) {
775 handler.cancel();
776 mActivity.resetTitleAndRevertLockIcon();
777 }
778 }).show();
779 } else {
780 handler.proceed();
781 }
782 }
783
784 /**
785 * Handles an HTTP authentication request.
786 *
787 * @param handler The authentication handler
788 * @param host The host
789 * @param realm The realm
790 */
791 @Override
792 public void onReceivedHttpAuthRequest(WebView view,
793 final HttpAuthHandler handler, final String host,
794 final String realm) {
795 String username = null;
796 String password = null;
797
798 boolean reuseHttpAuthUsernamePassword = handler
799 .useHttpAuthUsernamePassword();
800
Steve Block95a53b22010-03-25 17:24:58 +0000801 if (reuseHttpAuthUsernamePassword && view != null) {
802 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700803 host, realm);
804 if (credentials != null && credentials.length == 2) {
805 username = credentials[0];
806 password = credentials[1];
807 }
808 }
809
810 if (username != null && password != null) {
811 handler.proceed(username, password);
812 } else {
813 if (mInForeground) {
814 mActivity.showHttpAuthentication(handler, host, realm,
815 null, null, null, 0);
816 } else {
817 handler.cancel();
818 }
819 }
820 }
821
822 @Override
823 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
824 if (!mInForeground) {
825 return false;
826 }
827 if (mActivity.isMenuDown()) {
828 // only check shortcut key when MENU is held
829 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
830 event);
831 } else {
832 return false;
833 }
834 }
835
836 @Override
837 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400838 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700839 return;
840 }
841 if (event.isDown()) {
842 mActivity.onKeyDown(event.getKeyCode(), event);
843 } else {
844 mActivity.onKeyUp(event.getKeyCode(), event);
845 }
846 }
847 };
848
849 // -------------------------------------------------------------------------
850 // WebChromeClient implementation for the main WebView
851 // -------------------------------------------------------------------------
852
853 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
854 // Helper method to create a new tab or sub window.
855 private void createWindow(final boolean dialog, final Message msg) {
856 WebView.WebViewTransport transport =
857 (WebView.WebViewTransport) msg.obj;
858 if (dialog) {
859 createSubWindow();
860 mActivity.attachSubWindow(Tab.this);
861 transport.setWebView(mSubView);
862 } else {
863 final Tab newTab = mActivity.openTabAndShow(
864 BrowserActivity.EMPTY_URL_DATA, false, null);
865 if (newTab != Tab.this) {
866 Tab.this.addChildTab(newTab);
867 }
868 transport.setWebView(newTab.getWebView());
869 }
870 msg.sendToTarget();
871 }
872
873 @Override
874 public boolean onCreateWindow(WebView view, final boolean dialog,
875 final boolean userGesture, final Message resultMsg) {
876 // only allow new window or sub window for the foreground case
877 if (!mInForeground) {
878 return false;
879 }
880 // Short-circuit if we can't create any more tabs or sub windows.
881 if (dialog && mSubView != null) {
882 new AlertDialog.Builder(mActivity)
883 .setTitle(R.string.too_many_subwindows_dialog_title)
884 .setIcon(android.R.drawable.ic_dialog_alert)
885 .setMessage(R.string.too_many_subwindows_dialog_message)
886 .setPositiveButton(R.string.ok, null)
887 .show();
888 return false;
889 } else if (!mActivity.getTabControl().canCreateNewTab()) {
890 new AlertDialog.Builder(mActivity)
891 .setTitle(R.string.too_many_windows_dialog_title)
892 .setIcon(android.R.drawable.ic_dialog_alert)
893 .setMessage(R.string.too_many_windows_dialog_message)
894 .setPositiveButton(R.string.ok, null)
895 .show();
896 return false;
897 }
898
899 // Short-circuit if this was a user gesture.
900 if (userGesture) {
901 createWindow(dialog, resultMsg);
902 return true;
903 }
904
905 // Allow the popup and create the appropriate window.
906 final AlertDialog.OnClickListener allowListener =
907 new AlertDialog.OnClickListener() {
908 public void onClick(DialogInterface d,
909 int which) {
910 createWindow(dialog, resultMsg);
911 }
912 };
913
914 // Block the popup by returning a null WebView.
915 final AlertDialog.OnClickListener blockListener =
916 new AlertDialog.OnClickListener() {
917 public void onClick(DialogInterface d, int which) {
918 resultMsg.sendToTarget();
919 }
920 };
921
922 // Build a confirmation dialog to display to the user.
923 final AlertDialog d =
924 new AlertDialog.Builder(mActivity)
925 .setTitle(R.string.attention)
926 .setIcon(android.R.drawable.ic_dialog_alert)
927 .setMessage(R.string.popup_window_attempt)
928 .setPositiveButton(R.string.allow, allowListener)
929 .setNegativeButton(R.string.block, blockListener)
930 .setCancelable(false)
931 .create();
932
933 // Show the confirmation dialog.
934 d.show();
935 return true;
936 }
937
938 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500939 public void onRequestFocus(WebView view) {
940 if (!mInForeground) {
941 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
942 Tab.this));
943 }
944 }
945
946 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700947 public void onCloseWindow(WebView window) {
948 if (mParentTab != null) {
949 // JavaScript can only close popup window.
950 if (mInForeground) {
951 mActivity.switchToTab(mActivity.getTabControl()
952 .getTabIndex(mParentTab));
953 }
954 mActivity.closeTab(Tab.this);
955 }
956 }
957
958 @Override
959 public void onProgressChanged(WebView view, int newProgress) {
960 if (newProgress == 100) {
961 // sync cookies and cache promptly here.
962 CookieSyncManager.getInstance().sync();
963 }
964 if (mInForeground) {
965 mActivity.onProgressChanged(view, newProgress);
966 }
Michael Kolbfe251992010-07-08 15:41:55 -0700967 if (getTabChangeListener() != null) {
968 getTabChangeListener().onProgress(Tab.this, newProgress);
969 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700970 }
971
972 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500973 public void onReceivedTitle(WebView view, final String title) {
974 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700975 if (mInForeground) {
976 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500977 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700978 }
Michael Kolbfe251992010-07-08 15:41:55 -0700979 TabChangeListener tcl = getTabChangeListener();
980 if (tcl != null) {
981 tcl.onUrlAndTitle(Tab.this, pageUrl,title);
982 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500983 if (pageUrl == null || pageUrl.length()
984 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700985 return;
986 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500987
988 // Update the title in the history database if not in private browsing mode
989 if (!getWebView().isPrivateBrowsingEnabled()) {
990 new AsyncTask<Void, Void, Void>() {
991 @Override
992 protected Void doInBackground(Void... unused) {
993 // See if we can find the current url in our history
994 // database and add the new title to it.
995 String url = pageUrl;
996 if (url.startsWith("http://www.")) {
997 url = url.substring(11);
998 } else if (url.startsWith("http://")) {
999 url = url.substring(4);
1000 }
1001 // Escape wildcards for LIKE operator.
1002 url = url.replace("\\", "\\\\").replace("%", "\\%")
1003 .replace("_", "\\_");
1004 Cursor c = null;
1005 try {
1006 final ContentResolver cr = mActivity.getContentResolver();
1007 String selection = History.URL + " LIKE ? ESCAPE '\\'";
1008 String [] selectionArgs = new String[] { "%" + url };
1009 ContentValues values = new ContentValues();
1010 values.put(History.TITLE, title);
1011 cr.update(History.CONTENT_URI, values, selection, selectionArgs);
1012 } catch (IllegalStateException e) {
1013 Log.e(LOGTAG, "Tab onReceived title", e);
1014 } catch (SQLiteException ex) {
1015 Log.e(LOGTAG,
1016 "onReceivedTitle() caught SQLiteException: ",
1017 ex);
1018 } finally {
1019 if (c != null) c.close();
1020 }
1021 return null;
Leon Scroggins21d9b902010-03-11 09:33:11 -05001022 }
Jeff Hamilton47654f42010-09-07 09:57:51 -05001023 }.execute();
1024 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001025 }
1026
1027 @Override
1028 public void onReceivedIcon(WebView view, Bitmap icon) {
1029 if (icon != null) {
Jeff Hamilton84029622010-08-05 14:29:28 -05001030 Bookmarks.updateBookmarkFavicon(mActivity
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 .getContentResolver(), view.getOriginalUrl(), view
1032 .getUrl(), icon);
1033 }
1034 if (mInForeground) {
1035 mActivity.setFavicon(icon);
1036 }
Michael Kolbfe251992010-07-08 15:41:55 -07001037 if (getTabChangeListener() != null) {
1038 getTabChangeListener().onFavicon(Tab.this, icon);
1039 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001040 }
1041
1042 @Override
1043 public void onReceivedTouchIconUrl(WebView view, String url,
1044 boolean precomposed) {
1045 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001046 // Let precomposed icons take precedence over non-composed
1047 // icons.
1048 if (precomposed && mTouchIconLoader != null) {
1049 mTouchIconLoader.cancel(false);
1050 mTouchIconLoader = null;
1051 }
1052 // Have only one async task at a time.
1053 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001054 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001055 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001056 }
1057 }
1058
1059 @Override
1060 public void onShowCustomView(View view,
1061 WebChromeClient.CustomViewCallback callback) {
1062 if (mInForeground) mActivity.onShowCustomView(view, callback);
1063 }
1064
1065 @Override
1066 public void onHideCustomView() {
1067 if (mInForeground) mActivity.onHideCustomView();
1068 }
1069
1070 /**
1071 * The origin has exceeded its database quota.
1072 * @param url the URL that exceeded the quota
1073 * @param databaseIdentifier the identifier of the database on which the
1074 * transaction that caused the quota overflow was run
1075 * @param currentQuota the current quota for the origin.
1076 * @param estimatedSize the estimated size of the database.
1077 * @param totalUsedQuota is the sum of all origins' quota.
1078 * @param quotaUpdater The callback to run when a decision to allow or
1079 * deny quota has been made. Don't forget to call this!
1080 */
1081 @Override
1082 public void onExceededDatabaseQuota(String url,
1083 String databaseIdentifier, long currentQuota, long estimatedSize,
1084 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1085 BrowserSettings.getInstance().getWebStorageSizeManager()
1086 .onExceededDatabaseQuota(url, databaseIdentifier,
1087 currentQuota, estimatedSize, totalUsedQuota,
1088 quotaUpdater);
1089 }
1090
1091 /**
1092 * The Application Cache has exceeded its max size.
1093 * @param spaceNeeded is the amount of disk space that would be needed
1094 * in order for the last appcache operation to succeed.
1095 * @param totalUsedQuota is the sum of all origins' quota.
1096 * @param quotaUpdater A callback to inform the WebCore thread that a
1097 * new app cache size is available. This callback must always
1098 * be executed at some point to ensure that the sleeping
1099 * WebCore thread is woken up.
1100 */
1101 @Override
1102 public void onReachedMaxAppCacheSize(long spaceNeeded,
1103 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1104 BrowserSettings.getInstance().getWebStorageSizeManager()
1105 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1106 quotaUpdater);
1107 }
1108
1109 /**
1110 * Instructs the browser to show a prompt to ask the user to set the
1111 * Geolocation permission state for the specified origin.
1112 * @param origin The origin for which Geolocation permissions are
1113 * requested.
1114 * @param callback The callback to call once the user has set the
1115 * Geolocation permission state.
1116 */
1117 @Override
1118 public void onGeolocationPermissionsShowPrompt(String origin,
1119 GeolocationPermissions.Callback callback) {
1120 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001121 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 }
1123 }
1124
1125 /**
1126 * Instructs the browser to hide the Geolocation permissions prompt.
1127 */
1128 @Override
1129 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001130 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001131 mGeolocationPermissionsPrompt.hide();
1132 }
1133 }
1134
Ben Murdoch65acc352009-11-19 18:16:04 +00001135 /* Adds a JavaScript error message to the system log and if the JS
1136 * console is enabled in the about:debug options, to that console
1137 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001138 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001139 */
1140 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001141 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001142 if (mInForeground) {
1143 // call getErrorConsole(true) so it will create one if needed
1144 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001145 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001146 if (mActivity.shouldShowErrorConsole()
1147 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1148 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1149 }
1150 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001151
Jeff Hamilton47654f42010-09-07 09:57:51 -05001152 // Don't log console messages in private browsing mode
1153 if (getWebView().isPrivateBrowsingEnabled()) return true;
1154
Ben Murdochc42addf2010-01-28 15:19:59 +00001155 String message = "Console: " + consoleMessage.message() + " "
1156 + consoleMessage.sourceId() + ":"
1157 + consoleMessage.lineNumber();
1158
1159 switch (consoleMessage.messageLevel()) {
1160 case TIP:
1161 Log.v(CONSOLE_LOGTAG, message);
1162 break;
1163 case LOG:
1164 Log.i(CONSOLE_LOGTAG, message);
1165 break;
1166 case WARNING:
1167 Log.w(CONSOLE_LOGTAG, message);
1168 break;
1169 case ERROR:
1170 Log.e(CONSOLE_LOGTAG, message);
1171 break;
1172 case DEBUG:
1173 Log.d(CONSOLE_LOGTAG, message);
1174 break;
1175 }
1176
1177 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001178 }
1179
1180 /**
1181 * Ask the browser for an icon to represent a <video> element.
1182 * This icon will be used if the Web page did not specify a poster attribute.
1183 * @return Bitmap The icon or null if no such icon is available.
1184 */
1185 @Override
1186 public Bitmap getDefaultVideoPoster() {
1187 if (mInForeground) {
1188 return mActivity.getDefaultVideoPoster();
1189 }
1190 return null;
1191 }
1192
1193 /**
1194 * Ask the host application for a custom progress view to show while
1195 * a <video> is loading.
1196 * @return View The progress view.
1197 */
1198 @Override
1199 public View getVideoLoadingProgressView() {
1200 if (mInForeground) {
1201 return mActivity.getVideoLoadingProgressView();
1202 }
1203 return null;
1204 }
1205
1206 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001207 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001208 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001209 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001210 } else {
1211 uploadMsg.onReceiveValue(null);
1212 }
1213 }
1214
1215 /**
1216 * Deliver a list of already-visited URLs
1217 */
1218 @Override
1219 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1220 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
Michael Kolbfe251992010-07-08 15:41:55 -07001221 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001222 public String[] doInBackground(Void... unused) {
1223 return Browser.getVisitedHistory(mActivity
1224 .getContentResolver());
1225 }
Michael Kolbfe251992010-07-08 15:41:55 -07001226 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001227 public void onPostExecute(String[] result) {
1228 callback.onReceiveValue(result);
1229 };
1230 };
1231 task.execute();
1232 };
1233 };
1234
1235 // -------------------------------------------------------------------------
1236 // WebViewClient implementation for the sub window
1237 // -------------------------------------------------------------------------
1238
1239 // Subclass of WebViewClient used in subwindows to notify the main
1240 // WebViewClient of certain WebView activities.
1241 private static class SubWindowClient extends WebViewClient {
1242 // The main WebViewClient.
1243 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001244 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001245
Leon Scroggins III211ba542010-04-19 13:21:13 -04001246 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001247 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001248 mBrowserActivity = activity;
1249 }
1250 @Override
1251 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1252 // Unlike the others, do not call mClient's version, which would
1253 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001254 // find or select dialog.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001255 mBrowserActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001256 }
1257 @Override
1258 public void doUpdateVisitedHistory(WebView view, String url,
1259 boolean isReload) {
1260 mClient.doUpdateVisitedHistory(view, url, isReload);
1261 }
1262 @Override
1263 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1264 return mClient.shouldOverrideUrlLoading(view, url);
1265 }
1266 @Override
1267 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1268 SslError error) {
1269 mClient.onReceivedSslError(view, handler, error);
1270 }
1271 @Override
1272 public void onReceivedHttpAuthRequest(WebView view,
1273 HttpAuthHandler handler, String host, String realm) {
1274 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1275 }
1276 @Override
1277 public void onFormResubmission(WebView view, Message dontResend,
1278 Message resend) {
1279 mClient.onFormResubmission(view, dontResend, resend);
1280 }
1281 @Override
1282 public void onReceivedError(WebView view, int errorCode,
1283 String description, String failingUrl) {
1284 mClient.onReceivedError(view, errorCode, description, failingUrl);
1285 }
1286 @Override
1287 public boolean shouldOverrideKeyEvent(WebView view,
1288 android.view.KeyEvent event) {
1289 return mClient.shouldOverrideKeyEvent(view, event);
1290 }
1291 @Override
1292 public void onUnhandledKeyEvent(WebView view,
1293 android.view.KeyEvent event) {
1294 mClient.onUnhandledKeyEvent(view, event);
1295 }
1296 }
1297
1298 // -------------------------------------------------------------------------
1299 // WebChromeClient implementation for the sub window
1300 // -------------------------------------------------------------------------
1301
1302 private class SubWindowChromeClient extends WebChromeClient {
1303 // The main WebChromeClient.
1304 private final WebChromeClient mClient;
1305
1306 SubWindowChromeClient(WebChromeClient client) {
1307 mClient = client;
1308 }
1309 @Override
1310 public void onProgressChanged(WebView view, int newProgress) {
1311 mClient.onProgressChanged(view, newProgress);
1312 }
1313 @Override
1314 public boolean onCreateWindow(WebView view, boolean dialog,
1315 boolean userGesture, android.os.Message resultMsg) {
1316 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1317 }
1318 @Override
1319 public void onCloseWindow(WebView window) {
1320 if (window != mSubView) {
1321 Log.e(LOGTAG, "Can't close the window");
1322 }
1323 mActivity.dismissSubWindow(Tab.this);
1324 }
1325 }
1326
1327 // -------------------------------------------------------------------------
1328
1329 // Construct a new tab
1330 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1331 String url) {
1332 mActivity = activity;
1333 mCloseOnExit = closeOnExit;
1334 mAppId = appId;
1335 mOriginalUrl = url;
1336 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1337 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1338 mInLoad = false;
1339 mInForeground = false;
1340
1341 mInflateService = LayoutInflater.from(activity);
1342
1343 // The tab consists of a container view, which contains the main
1344 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001345 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001346
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001347 mDownloadListener = new DownloadListener() {
1348 public void onDownloadStart(String url, String userAgent,
1349 String contentDisposition, String mimetype,
1350 long contentLength) {
1351 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1352 mimetype, contentLength);
1353 if (mMainView.copyBackForwardList().getSize() == 0) {
1354 // This Tab was opened for the sole purpose of downloading a
1355 // file. Remove it.
1356 if (mActivity.getTabControl().getCurrentWebView()
1357 == mMainView) {
1358 // In this case, the Tab is still on top.
1359 mActivity.goBackOnePageOrQuit();
1360 } else {
1361 // In this case, it is not.
1362 mActivity.closeTab(Tab.this);
1363 }
1364 }
1365 }
1366 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001367 mWebBackForwardListClient = new WebBackForwardListClient() {
1368 @Override
1369 public void onNewHistoryItem(WebHistoryItem item) {
1370 if (isInVoiceSearchMode()) {
1371 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1372 }
1373 }
1374 @Override
1375 public void onIndexChanged(WebHistoryItem item, int index) {
1376 Object data = item.getCustomData();
1377 if (data != null && data instanceof Intent) {
1378 activateVoiceSearchMode((Intent) data);
1379 }
1380 }
1381 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001382
Grace Kloba22ac16e2009-10-07 18:00:23 -07001383 setWebView(w);
1384 }
1385
1386 /**
1387 * Sets the WebView for this tab, correctly removing the old WebView from
1388 * the container view.
1389 */
1390 void setWebView(WebView w) {
1391 if (mMainView == w) {
1392 return;
1393 }
1394 // If the WebView is changing, the page will be reloaded, so any ongoing
1395 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001396 if (mGeolocationPermissionsPrompt != null) {
1397 mGeolocationPermissionsPrompt.hide();
1398 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001399
1400 // Just remove the old one.
1401 FrameLayout wrapper =
1402 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1403 wrapper.removeView(mMainView);
1404
1405 // set the new one
1406 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001407 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 if (mMainView != null) {
1409 mMainView.setWebViewClient(mWebViewClient);
1410 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001411 // Attach DownloadManager so that downloads can start in an active
1412 // or a non-active window. This can happen when going to a site that
1413 // does a redirect after a period of time. The user could have
1414 // switched to another tab while waiting for the download to start.
1415 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001416 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001417 }
1418 }
1419
1420 /**
1421 * Destroy the tab's main WebView and subWindow if any
1422 */
1423 void destroy() {
1424 if (mMainView != null) {
1425 dismissSubWindow();
1426 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1427 // save the WebView to call destroy() after detach it from the tab
1428 WebView webView = mMainView;
1429 setWebView(null);
1430 webView.destroy();
1431 }
1432 }
1433
1434 /**
1435 * Remove the tab from the parent
1436 */
1437 void removeFromTree() {
1438 // detach the children
1439 if (mChildTabs != null) {
1440 for(Tab t : mChildTabs) {
1441 t.setParentTab(null);
1442 }
1443 }
1444 // remove itself from the parent list
1445 if (mParentTab != null) {
1446 mParentTab.mChildTabs.remove(this);
1447 }
1448 }
1449
1450 /**
1451 * Create a new subwindow unless a subwindow already exists.
1452 * @return True if a new subwindow was created. False if one already exists.
1453 */
1454 boolean createSubWindow() {
1455 if (mSubView == null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001456 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001457 mSubViewContainer = mInflateService.inflate(
1458 R.layout.browser_subwindow, null);
1459 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001460 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001461 // use trackball directly
1462 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001463 // Enable the built-in zoom
1464 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001465 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1466 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001467 mSubView.setWebChromeClient(new SubWindowChromeClient(
1468 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001469 // Set a different DownloadListener for the mSubView, since it will
1470 // just need to dismiss the mSubView, rather than close the Tab
1471 mSubView.setDownloadListener(new DownloadListener() {
1472 public void onDownloadStart(String url, String userAgent,
1473 String contentDisposition, String mimetype,
1474 long contentLength) {
1475 mActivity.onDownloadStart(url, userAgent,
1476 contentDisposition, mimetype, contentLength);
1477 if (mSubView.copyBackForwardList().getSize() == 0) {
1478 // This subwindow was opened for the sole purpose of
1479 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001480 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001481 }
1482 }
1483 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001484 mSubView.setOnCreateContextMenuListener(mActivity);
1485 final BrowserSettings s = BrowserSettings.getInstance();
1486 s.addObserver(mSubView.getSettings()).update(s, null);
1487 final ImageButton cancel = (ImageButton) mSubViewContainer
1488 .findViewById(R.id.subwindow_close);
1489 cancel.setOnClickListener(new OnClickListener() {
1490 public void onClick(View v) {
1491 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1492 }
1493 });
1494 return true;
1495 }
1496 return false;
1497 }
1498
1499 /**
1500 * Dismiss the subWindow for the tab.
1501 */
1502 void dismissSubWindow() {
1503 if (mSubView != null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001504 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001505 BrowserSettings.getInstance().deleteObserver(
1506 mSubView.getSettings());
1507 mSubView.destroy();
1508 mSubView = null;
1509 mSubViewContainer = null;
1510 }
1511 }
1512
1513 /**
1514 * Attach the sub window to the content view.
1515 */
1516 void attachSubWindow(ViewGroup content) {
1517 if (mSubView != null) {
1518 content.addView(mSubViewContainer,
1519 BrowserActivity.COVER_SCREEN_PARAMS);
1520 }
1521 }
1522
1523 /**
1524 * Remove the sub window from the content view.
1525 */
1526 void removeSubWindow(ViewGroup content) {
1527 if (mSubView != null) {
1528 content.removeView(mSubViewContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001529 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001530 }
1531 }
1532
1533 /**
1534 * This method attaches both the WebView and any sub window to the
1535 * given content view.
1536 */
1537 void attachTabToContentView(ViewGroup content) {
1538 if (mMainView == null) {
1539 return;
1540 }
1541
1542 // Attach the WebView to the container and then attach the
1543 // container to the content view.
1544 FrameLayout wrapper =
1545 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001546 ViewGroup parent = (ViewGroup) mMainView.getParent();
1547 if (parent != wrapper) {
1548 if (parent != null) {
1549 Log.w(LOGTAG, "mMainView already has a parent in"
1550 + " attachTabToContentView!");
1551 parent.removeView(mMainView);
1552 }
1553 wrapper.addView(mMainView);
1554 } else {
1555 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1556 + " attachTabToContentView!");
1557 }
1558 parent = (ViewGroup) mContainer.getParent();
1559 if (parent != content) {
1560 if (parent != null) {
1561 Log.w(LOGTAG, "mContainer already has a parent in"
1562 + " attachTabToContentView!");
1563 parent.removeView(mContainer);
1564 }
1565 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1566 } else {
1567 Log.w(LOGTAG, "mContainer is already attached to content in"
1568 + " attachTabToContentView!");
1569 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001570 attachSubWindow(content);
1571 }
1572
1573 /**
1574 * Remove the WebView and any sub window from the given content view.
1575 */
1576 void removeTabFromContentView(ViewGroup content) {
1577 if (mMainView == null) {
1578 return;
1579 }
1580
1581 // Remove the container from the content and then remove the
1582 // WebView from the container. This will trigger a focus change
1583 // needed by WebView.
1584 FrameLayout wrapper =
1585 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1586 wrapper.removeView(mMainView);
1587 content.removeView(mContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001588 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001589 removeSubWindow(content);
1590 }
1591
1592 /**
1593 * Set the parent tab of this tab.
1594 */
1595 void setParentTab(Tab parent) {
1596 mParentTab = parent;
1597 // This tab may have been freed due to low memory. If that is the case,
1598 // the parent tab index is already saved. If we are changing that index
1599 // (most likely due to removing the parent tab) we must update the
1600 // parent tab index in the saved Bundle.
1601 if (mSavedState != null) {
1602 if (parent == null) {
1603 mSavedState.remove(PARENTTAB);
1604 } else {
1605 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1606 .getTabIndex(parent));
1607 }
1608 }
1609 }
1610
1611 /**
1612 * When a Tab is created through the content of another Tab, then we
1613 * associate the Tabs.
1614 * @param child the Tab that was created from this Tab
1615 */
1616 void addChildTab(Tab child) {
1617 if (mChildTabs == null) {
1618 mChildTabs = new Vector<Tab>();
1619 }
1620 mChildTabs.add(child);
1621 child.setParentTab(this);
1622 }
1623
1624 Vector<Tab> getChildTabs() {
1625 return mChildTabs;
1626 }
1627
1628 void resume() {
1629 if (mMainView != null) {
1630 mMainView.onResume();
1631 if (mSubView != null) {
1632 mSubView.onResume();
1633 }
1634 }
1635 }
1636
1637 void pause() {
1638 if (mMainView != null) {
1639 mMainView.onPause();
1640 if (mSubView != null) {
1641 mSubView.onPause();
1642 }
1643 }
1644 }
1645
1646 void putInForeground() {
1647 mInForeground = true;
1648 resume();
1649 mMainView.setOnCreateContextMenuListener(mActivity);
1650 if (mSubView != null) {
1651 mSubView.setOnCreateContextMenuListener(mActivity);
1652 }
1653 // Show the pending error dialog if the queue is not empty
1654 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1655 showError(mQueuedErrors.getFirst());
1656 }
1657 }
1658
1659 void putInBackground() {
1660 mInForeground = false;
1661 pause();
1662 mMainView.setOnCreateContextMenuListener(null);
1663 if (mSubView != null) {
1664 mSubView.setOnCreateContextMenuListener(null);
1665 }
1666 }
1667
1668 /**
1669 * Return the top window of this tab; either the subwindow if it is not
1670 * null or the main window.
1671 * @return The top window of this tab.
1672 */
1673 WebView getTopWindow() {
1674 if (mSubView != null) {
1675 return mSubView;
1676 }
1677 return mMainView;
1678 }
1679
1680 /**
1681 * Return the main window of this tab. Note: if a tab is freed in the
1682 * background, this can return null. It is only guaranteed to be
1683 * non-null for the current tab.
1684 * @return The main WebView of this tab.
1685 */
1686 WebView getWebView() {
1687 return mMainView;
1688 }
1689
1690 /**
1691 * Return the subwindow of this tab or null if there is no subwindow.
1692 * @return The subwindow of this tab or null.
1693 */
1694 WebView getSubWebView() {
1695 return mSubView;
1696 }
1697
1698 /**
1699 * @return The geolocation permissions prompt for this tab.
1700 */
1701 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001702 if (mGeolocationPermissionsPrompt == null) {
1703 ViewStub stub = (ViewStub) mContainer
1704 .findViewById(R.id.geolocation_permissions_prompt);
1705 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1706 .inflate();
1707 mGeolocationPermissionsPrompt.init();
1708 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001709 return mGeolocationPermissionsPrompt;
1710 }
1711
1712 /**
1713 * @return The application id string
1714 */
1715 String getAppId() {
1716 return mAppId;
1717 }
1718
1719 /**
1720 * Set the application id string
1721 * @param id
1722 */
1723 void setAppId(String id) {
1724 mAppId = id;
1725 }
1726
1727 /**
1728 * @return The original url associated with this Tab
1729 */
1730 String getOriginalUrl() {
1731 return mOriginalUrl;
1732 }
1733
1734 /**
1735 * Set the original url associated with this tab
1736 */
1737 void setOriginalUrl(String url) {
1738 mOriginalUrl = url;
1739 }
1740
1741 /**
1742 * Get the url of this tab. Valid after calling populatePickerData, but
1743 * before calling wipePickerData, or if the webview has been destroyed.
1744 * @return The WebView's url or null.
1745 */
1746 String getUrl() {
1747 if (mPickerData != null) {
1748 return mPickerData.mUrl;
1749 }
1750 return null;
1751 }
1752
1753 /**
1754 * Get the title of this tab. Valid after calling populatePickerData, but
1755 * before calling wipePickerData, or if the webview has been destroyed. If
1756 * the url has no title, use the url instead.
1757 * @return The WebView's title (or url) or null.
1758 */
1759 String getTitle() {
1760 if (mPickerData != null) {
1761 return mPickerData.mTitle;
1762 }
1763 return null;
1764 }
1765
1766 /**
1767 * Get the favicon of this tab. Valid after calling populatePickerData, but
1768 * before calling wipePickerData, or if the webview has been destroyed.
1769 * @return The WebView's favicon or null.
1770 */
1771 Bitmap getFavicon() {
1772 if (mPickerData != null) {
1773 return mPickerData.mFavicon;
1774 }
1775 return null;
1776 }
1777
1778 /**
1779 * Return the tab's error console. Creates the console if createIfNEcessary
1780 * is true and we haven't already created the console.
1781 * @param createIfNecessary Flag to indicate if the console should be
1782 * created if it has not been already.
1783 * @return The tab's error console, or null if one has not been created and
1784 * createIfNecessary is false.
1785 */
1786 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1787 if (createIfNecessary && mErrorConsole == null) {
1788 mErrorConsole = new ErrorConsoleView(mActivity);
1789 mErrorConsole.setWebView(mMainView);
1790 }
1791 return mErrorConsole;
1792 }
1793
1794 /**
1795 * If this Tab was created through another Tab, then this method returns
1796 * that Tab.
1797 * @return the Tab parent or null
1798 */
1799 public Tab getParentTab() {
1800 return mParentTab;
1801 }
1802
1803 /**
1804 * Return whether this tab should be closed when it is backing out of the
1805 * first page.
1806 * @return TRUE if this tab should be closed when exit.
1807 */
1808 boolean closeOnExit() {
1809 return mCloseOnExit;
1810 }
1811
1812 /**
1813 * Saves the current lock-icon state before resetting the lock icon. If we
1814 * have an error, we may need to roll back to the previous state.
1815 */
1816 void resetLockIcon(String url) {
1817 mPrevLockIconType = mLockIconType;
1818 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1819 if (URLUtil.isHttpsUrl(url)) {
1820 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1821 }
1822 }
1823
1824 /**
1825 * Reverts the lock-icon state to the last saved state, for example, if we
1826 * had an error, and need to cancel the load.
1827 */
1828 void revertLockIcon() {
1829 mLockIconType = mPrevLockIconType;
1830 }
1831
1832 /**
1833 * @return The tab's lock icon type.
1834 */
1835 int getLockIconType() {
1836 return mLockIconType;
1837 }
1838
1839 /**
1840 * @return TRUE if onPageStarted is called while onPageFinished is not
1841 * called yet.
1842 */
1843 boolean inLoad() {
1844 return mInLoad;
1845 }
1846
1847 // force mInLoad to be false. This should only be called before closing the
1848 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1849 void clearInLoad() {
1850 mInLoad = false;
1851 }
1852
1853 void populatePickerData() {
1854 if (mMainView == null) {
1855 populatePickerDataFromSavedState();
1856 return;
1857 }
1858
1859 // FIXME: The only place we cared about subwindow was for
1860 // bookmarking (i.e. not when saving state). Was this deliberate?
1861 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001862 if (list == null) {
1863 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1864 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001865 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1866 populatePickerData(item);
1867 }
1868
1869 // Populate the picker data using the given history item and the current top
1870 // WebView.
1871 private void populatePickerData(WebHistoryItem item) {
1872 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001873 if (item == null) {
1874 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1875 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001876 mPickerData.mUrl = item.getUrl();
1877 mPickerData.mTitle = item.getTitle();
1878 mPickerData.mFavicon = item.getFavicon();
1879 if (mPickerData.mTitle == null) {
1880 mPickerData.mTitle = mPickerData.mUrl;
1881 }
1882 }
1883 }
1884
1885 // Create the PickerData and populate it using the saved state of the tab.
1886 void populatePickerDataFromSavedState() {
1887 if (mSavedState == null) {
1888 return;
1889 }
1890 mPickerData = new PickerData();
1891 mPickerData.mUrl = mSavedState.getString(CURRURL);
1892 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1893 }
1894
1895 void clearPickerData() {
1896 mPickerData = null;
1897 }
1898
1899 /**
1900 * Get the saved state bundle.
1901 * @return
1902 */
1903 Bundle getSavedState() {
1904 return mSavedState;
1905 }
1906
1907 /**
1908 * Set the saved state.
1909 */
1910 void setSavedState(Bundle state) {
1911 mSavedState = state;
1912 }
1913
1914 /**
1915 * @return TRUE if succeed in saving the state.
1916 */
1917 boolean saveState() {
1918 // If the WebView is null it means we ran low on memory and we already
1919 // stored the saved state in mSavedState.
1920 if (mMainView == null) {
1921 return mSavedState != null;
1922 }
1923
1924 mSavedState = new Bundle();
1925 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001926
1927 // Store some extra info for displaying the tab in the picker.
1928 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1929 populatePickerData(item);
1930
1931 if (mPickerData.mUrl != null) {
1932 mSavedState.putString(CURRURL, mPickerData.mUrl);
1933 }
1934 if (mPickerData.mTitle != null) {
1935 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1936 }
1937 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1938 if (mAppId != null) {
1939 mSavedState.putString(APPID, mAppId);
1940 }
1941 if (mOriginalUrl != null) {
1942 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1943 }
1944 // Remember the parent tab so the relationship can be restored.
1945 if (mParentTab != null) {
1946 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1947 mParentTab));
1948 }
1949 return true;
1950 }
1951
1952 /*
1953 * Restore the state of the tab.
1954 */
1955 boolean restoreState(Bundle b) {
1956 if (b == null) {
1957 return false;
1958 }
1959 // Restore the internal state even if the WebView fails to restore.
1960 // This will maintain the app id, original url and close-on-exit values.
1961 mSavedState = null;
1962 mPickerData = null;
1963 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1964 mAppId = b.getString(APPID);
1965 mOriginalUrl = b.getString(ORIGINALURL);
1966
1967 final WebBackForwardList list = mMainView.restoreState(b);
1968 if (list == null) {
1969 return false;
1970 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001971 return true;
1972 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001973
Michael Kolbfe251992010-07-08 15:41:55 -07001974 /**
1975 * always get the TabChangeListener form the tab control
1976 * @return the TabControl change listener
1977 */
1978 private TabChangeListener getTabChangeListener() {
1979 return mActivity.getTabControl().getTabChangeListener();
1980 }
1981
Grace Kloba22ac16e2009-10-07 18:00:23 -07001982}