blob: 535e8e7fa370f23157e129ada4266ef886c381d3 [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
19import java.io.File;
Leon Scroggins58d56c62010-01-28 15:12:40 -050020import java.util.ArrayList;
Leon Scroggins9df94972010-03-08 18:20:35 -050021import java.util.HashMap;
22import java.util.Iterator;
Grace Kloba22ac16e2009-10-07 18:00:23 -070023import java.util.LinkedList;
Leon Scroggins9df94972010-03-08 18:20:35 -050024import java.util.Map;
Grace Kloba22ac16e2009-10-07 18:00:23 -070025import java.util.Vector;
26
27import android.app.AlertDialog;
Leon Scroggins58d56c62010-01-28 15:12:40 -050028import android.app.SearchManager;
Grace Kloba22ac16e2009-10-07 18:00:23 -070029import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.DialogInterface;
32import android.content.DialogInterface.OnCancelListener;
Leon Scroggins58d56c62010-01-28 15:12:40 -050033import android.content.Intent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070034import android.database.Cursor;
35import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteException;
37import android.graphics.Bitmap;
38import android.net.Uri;
39import android.net.http.SslError;
40import android.os.AsyncTask;
41import android.os.Bundle;
42import android.os.Message;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +000043import android.os.SystemClock;
Grace Kloba22ac16e2009-10-07 18:00:23 -070044import android.provider.Browser;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050045import android.speech.RecognizerResultsIntent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070046import android.util.Log;
47import android.view.KeyEvent;
48import android.view.LayoutInflater;
49import android.view.View;
50import android.view.ViewGroup;
51import android.view.View.OnClickListener;
Ben Murdochc42addf2010-01-28 15:19:59 +000052import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070053import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050054import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070055import android.webkit.GeolocationPermissions;
56import android.webkit.HttpAuthHandler;
57import android.webkit.SslErrorHandler;
58import android.webkit.URLUtil;
59import android.webkit.ValueCallback;
60import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050061import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070062import android.webkit.WebChromeClient;
63import android.webkit.WebHistoryItem;
64import android.webkit.WebIconDatabase;
65import android.webkit.WebStorage;
66import android.webkit.WebView;
67import android.webkit.WebViewClient;
68import android.widget.FrameLayout;
69import android.widget.ImageButton;
70import android.widget.LinearLayout;
71import android.widget.TextView;
72
Leon Scroggins1fe13a52010-02-09 15:31:26 -050073import com.android.common.speech.LoggingEvents;
74
Grace Kloba22ac16e2009-10-07 18:00:23 -070075/**
76 * Class for maintaining Tabs with a main WebView and a subwindow.
77 */
78class Tab {
79 // Log Tag
80 private static final String LOGTAG = "Tab";
Ben Murdochc42addf2010-01-28 15:19:59 +000081 // Special case the logtag for messages for the Console to make it easier to
82 // filter them and match the logtag used for these messages in older versions
83 // of the browser.
84 private static final String CONSOLE_LOGTAG = "browser";
85
Grace Kloba22ac16e2009-10-07 18:00:23 -070086 // The Geolocation permissions prompt
87 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
88 // Main WebView wrapper
89 private View mContainer;
90 // Main WebView
91 private WebView mMainView;
92 // Subwindow container
93 private View mSubViewContainer;
94 // Subwindow WebView
95 private WebView mSubView;
96 // Saved bundle for when we are running low on memory. It contains the
97 // information needed to restore the WebView if the user goes back to the
98 // tab.
99 private Bundle mSavedState;
100 // Data used when displaying the tab in the picker.
101 private PickerData mPickerData;
102 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
103 // created by the UI
104 private Tab mParentTab;
105 // Tab that constructed by this Tab. This is used when this Tab is
106 // destroyed, it clears all mParentTab values in the children.
107 private Vector<Tab> mChildTabs;
108 // If true, the tab will be removed when back out of the first page.
109 private boolean mCloseOnExit;
110 // If true, the tab is in the foreground of the current activity.
111 private boolean mInForeground;
112 // If true, the tab is in loading state.
113 private boolean mInLoad;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000114 // The time the load started, used to find load page time
115 private long mLoadStartTime;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700116 // Application identifier used to find tabs that another application wants
117 // to reuse.
118 private String mAppId;
119 // Keep the original url around to avoid killing the old WebView if the url
120 // has not changed.
121 private String mOriginalUrl;
122 // Error console for the tab
123 private ErrorConsoleView mErrorConsole;
124 // the lock icon type and previous lock icon type for the tab
125 private int mLockIconType;
126 private int mPrevLockIconType;
127 // Inflation service for making subwindows.
128 private final LayoutInflater mInflateService;
129 // The BrowserActivity which owners the Tab
130 private final BrowserActivity mActivity;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -0500131 // The listener that gets invoked when a download is started from the
132 // mMainView
133 private final DownloadListener mDownloadListener;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500134 // Listener used to know when we move forward or back in the history list.
135 private final WebBackForwardListClient mWebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700136
137 // AsyncTask for downloading touch icons
138 DownloadTouchIcon mTouchIconLoader;
139
140 // Extra saved information for displaying the tab in the picker.
141 private static class PickerData {
142 String mUrl;
143 String mTitle;
144 Bitmap mFavicon;
145 }
146
147 // Used for saving and restoring each Tab
148 static final String WEBVIEW = "webview";
149 static final String NUMTABS = "numTabs";
150 static final String CURRTAB = "currentTab";
151 static final String CURRURL = "currentUrl";
152 static final String CURRTITLE = "currentTitle";
153 static final String CURRPICTURE = "currentPicture";
154 static final String CLOSEONEXIT = "closeonexit";
155 static final String PARENTTAB = "parentTab";
156 static final String APPID = "appid";
157 static final String ORIGINALURL = "originalUrl";
158
159 // -------------------------------------------------------------------------
160
Leon Scroggins58d56c62010-01-28 15:12:40 -0500161 /**
162 * Private information regarding the latest voice search. If the Tab is not
163 * in voice search mode, this will be null.
164 */
165 private VoiceSearchData mVoiceSearchData;
166 /**
167 * Return whether the tab is in voice search mode.
168 */
169 public boolean isInVoiceSearchMode() {
170 return mVoiceSearchData != null;
171 }
172 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500173 * Return true if the voice search Intent came with a String identifying
174 * that Google provided the Intent.
175 */
176 public boolean voiceSearchSourceIsGoogle() {
177 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
178 }
179 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500180 * Get the title to display for the current voice search page. If the Tab
181 * is not in voice search mode, return null.
182 */
183 public String getVoiceDisplayTitle() {
184 if (mVoiceSearchData == null) return null;
185 return mVoiceSearchData.mLastVoiceSearchTitle;
186 }
187 /**
188 * Get the latest array of voice search results, to be passed to the
189 * BrowserProvider. If the Tab is not in voice search mode, return null.
190 */
191 public ArrayList<String> getVoiceSearchResults() {
192 if (mVoiceSearchData == null) return null;
193 return mVoiceSearchData.mVoiceSearchResults;
194 }
195 /**
196 * Activate voice search mode.
197 * @param intent Intent which has the results to use, or an index into the
198 * results when reusing the old results.
199 */
200 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500201 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500202 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500203 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500204 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500205 ArrayList<String> urls = intent.getStringArrayListExtra(
206 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
207 ArrayList<String> htmls = intent.getStringArrayListExtra(
208 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
209 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
210 RecognizerResultsIntent
211 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500212 // This tab is now entering voice search mode for the first time, or
213 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500214 int size = results.size();
215 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500216 throw new AssertionError("improper extras passed in Intent");
217 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500218 if (htmls == null || htmls.size() != size || baseUrls == null ||
219 (baseUrls.size() != size && baseUrls.size() != 1)) {
220 // If either of these arrays are empty/incorrectly sized, ignore
221 // them.
222 htmls = null;
223 baseUrls = null;
224 }
225 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
226 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500227 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
228 RecognizerResultsIntent
229 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500230 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
231 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400232 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500233 }
234 String extraData = intent.getStringExtra(
235 SearchManager.EXTRA_DATA_KEY);
236 if (extraData != null) {
237 index = Integer.parseInt(extraData);
238 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
239 throw new AssertionError("index must be less than "
240 + "size of mVoiceSearchResults");
241 }
242 if (mVoiceSearchData.mSourceIsGoogle) {
243 Intent logIntent = new Intent(
244 LoggingEvents.ACTION_LOG_EVENT);
245 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
246 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
247 logIntent.putExtra(
248 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
249 index);
250 mActivity.sendBroadcast(logIntent);
251 }
252 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400253 // Copy the Intent, so that each history item will have its own
254 // Intent, with different (or none) extra data.
255 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
256 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
257 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500258 }
259 }
260 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500261 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500262 if (mInForeground) {
263 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
264 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500265 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
266 // When index was found it was already ensured that it was valid
267 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
268 if (uriString != null) {
269 Uri dataUri = Uri.parse(uriString);
270 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
271 dataUri.getScheme())) {
272 // If there is only one base URL, use it. If there are
273 // more, there will be one for each index, so use the base
274 // URL corresponding to the index.
275 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
276 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
277 index : 0);
278 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
279 mMainView.loadDataWithBaseURL(baseUrl,
280 uriString.substring(RecognizerResultsIntent
281 .URI_SCHEME_INLINE.length() + 1), "text/html",
282 "utf-8", baseUrl);
283 return;
284 }
285 }
286 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500287 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500288 = mVoiceSearchData.mVoiceSearchUrls.get(index);
289 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
290 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
291 mVoiceSearchData.mLastVoiceSearchTitle);
292 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500293 Map<String, String> headers = null;
294 if (mVoiceSearchData.mHeaders != null) {
295 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
296 : index;
297 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
298 if (bundle != null && !bundle.isEmpty()) {
299 Iterator<String> iter = bundle.keySet().iterator();
300 headers = new HashMap<String, String>();
301 while (iter.hasNext()) {
302 String key = iter.next();
303 headers.put(key, bundle.getString(key));
304 }
305 }
306 }
307 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500308 }
309 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500311 ArrayList<String> urls, ArrayList<String> htmls,
312 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500313 mVoiceSearchResults = results;
314 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500315 mVoiceSearchHtmls = htmls;
316 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500317 }
318 /*
319 * ArrayList of suggestions to be displayed when opening the
320 * SearchManager
321 */
322 public ArrayList<String> mVoiceSearchResults;
323 /*
324 * ArrayList of urls, associated with the suggestions in
325 * mVoiceSearchResults.
326 */
327 public ArrayList<String> mVoiceSearchUrls;
328 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500329 * ArrayList holding content to load for each item in
330 * mVoiceSearchResults.
331 */
332 public ArrayList<String> mVoiceSearchHtmls;
333 /*
334 * ArrayList holding base urls for the items in mVoiceSearchResults.
335 * If non null, this will either have the same size as
336 * mVoiceSearchResults or have a size of 1, in which case all will use
337 * the same base url
338 */
339 public ArrayList<String> mVoiceSearchBaseUrls;
340 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500341 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500342 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500343 */
344 public String mLastVoiceSearchUrl;
345 /**
346 * The last title used for voice search. Needed to update the title bar
347 * when switching tabs.
348 */
349 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500350 /**
351 * Whether the Intent which turned on voice search mode contained the
352 * String signifying that Google was the source.
353 */
354 public boolean mSourceIsGoogle;
355 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500356 * List of headers to be passed into the WebView containing location
357 * information
358 */
359 public ArrayList<Bundle> mHeaders;
360 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500361 * The Intent used to invoke voice search. Placed on the
362 * WebHistoryItem so that when coming back to a previous voice search
363 * page we can again activate voice search.
364 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500365 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500366 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500367 * String used to identify Google as the source of voice search.
368 */
369 public static String SOURCE_IS_GOOGLE
370 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500371 }
372
Grace Kloba22ac16e2009-10-07 18:00:23 -0700373 // Container class for the next error dialog that needs to be displayed
374 private class ErrorDialog {
375 public final int mTitle;
376 public final String mDescription;
377 public final int mError;
378 ErrorDialog(int title, String desc, int error) {
379 mTitle = title;
380 mDescription = desc;
381 mError = error;
382 }
383 };
384
385 private void processNextError() {
386 if (mQueuedErrors == null) {
387 return;
388 }
389 // The first one is currently displayed so just remove it.
390 mQueuedErrors.removeFirst();
391 if (mQueuedErrors.size() == 0) {
392 mQueuedErrors = null;
393 return;
394 }
395 showError(mQueuedErrors.getFirst());
396 }
397
398 private DialogInterface.OnDismissListener mDialogListener =
399 new DialogInterface.OnDismissListener() {
400 public void onDismiss(DialogInterface d) {
401 processNextError();
402 }
403 };
404 private LinkedList<ErrorDialog> mQueuedErrors;
405
406 private void queueError(int err, String desc) {
407 if (mQueuedErrors == null) {
408 mQueuedErrors = new LinkedList<ErrorDialog>();
409 }
410 for (ErrorDialog d : mQueuedErrors) {
411 if (d.mError == err) {
412 // Already saw a similar error, ignore the new one.
413 return;
414 }
415 }
416 ErrorDialog errDialog = new ErrorDialog(
417 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
418 R.string.browserFrameFileErrorLabel :
419 R.string.browserFrameNetworkErrorLabel,
420 desc, err);
421 mQueuedErrors.addLast(errDialog);
422
423 // Show the dialog now if the queue was empty and it is in foreground
424 if (mQueuedErrors.size() == 1 && mInForeground) {
425 showError(errDialog);
426 }
427 }
428
429 private void showError(ErrorDialog errDialog) {
430 if (mInForeground) {
431 AlertDialog d = new AlertDialog.Builder(mActivity)
432 .setTitle(errDialog.mTitle)
433 .setMessage(errDialog.mDescription)
434 .setPositiveButton(R.string.ok, null)
435 .create();
436 d.setOnDismissListener(mDialogListener);
437 d.show();
438 }
439 }
440
441 // -------------------------------------------------------------------------
442 // WebViewClient implementation for the main WebView
443 // -------------------------------------------------------------------------
444
445 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500446 private Message mDontResend;
447 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700448 @Override
449 public void onPageStarted(WebView view, String url, Bitmap favicon) {
450 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000451 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500452 if (mVoiceSearchData != null
453 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500454 if (mVoiceSearchData.mSourceIsGoogle) {
455 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
456 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
457 mActivity.sendBroadcast(i);
458 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500459 mVoiceSearchData = null;
460 if (mInForeground) {
461 mActivity.revertVoiceTitleBar();
462 }
463 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700464
465 // We've started to load a new page. If there was a pending message
466 // to save a screenshot then we will now take the new page and save
467 // an incorrect screenshot. Therefore, remove any pending thumbnail
468 // messages from the queue.
469 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
470 view);
471
472 // If we start a touch icon load and then load a new page, we don't
473 // want to cancel the current touch icon loader. But, we do want to
474 // create a new one when the touch icon url is known.
475 if (mTouchIconLoader != null) {
476 mTouchIconLoader.mTab = null;
477 mTouchIconLoader = null;
478 }
479
480 // reset the error console
481 if (mErrorConsole != null) {
482 mErrorConsole.clearErrorMessages();
483 if (mActivity.shouldShowErrorConsole()) {
484 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
485 }
486 }
487
488 // update the bookmark database for favicon
489 if (favicon != null) {
490 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
491 .getContentResolver(), view.getOriginalUrl(), view
492 .getUrl(), favicon);
493 }
494
495 // reset sync timer to avoid sync starts during loading a page
496 CookieSyncManager.getInstance().resetSync();
497
498 if (!mActivity.isNetworkUp()) {
499 view.setNetworkAvailable(false);
500 }
501
502 // finally update the UI in the activity if it is in the foreground
503 if (mInForeground) {
504 mActivity.onPageStarted(view, url, favicon);
505 }
506 }
507
508 @Override
509 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000510 LogTag.logPageFinishedLoading(
511 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700512 mInLoad = false;
513
514 if (mInForeground && !mActivity.didUserStopLoading()
515 || !mInForeground) {
516 // Only update the bookmark screenshot if the user did not
517 // cancel the load early.
518 mActivity.postMessage(
519 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
520 500);
521 }
522
523 // finally update the UI in the activity if it is in the foreground
524 if (mInForeground) {
525 mActivity.onPageFinished(view, url);
526 }
527 }
528
529 // return true if want to hijack the url to let another app to handle it
530 @Override
531 public boolean shouldOverrideUrlLoading(WebView view, String url) {
532 if (mInForeground) {
533 return mActivity.shouldOverrideUrlLoading(view, url);
534 } else {
535 return false;
536 }
537 }
538
539 /**
540 * Updates the lock icon. This method is called when we discover another
541 * resource to be loaded for this page (for example, javascript). While
542 * we update the icon type, we do not update the lock icon itself until
543 * we are done loading, it is slightly more secure this way.
544 */
545 @Override
546 public void onLoadResource(WebView view, String url) {
547 if (url != null && url.length() > 0) {
548 // It is only if the page claims to be secure that we may have
549 // to update the lock:
550 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
551 // If NOT a 'safe' url, change the lock to mixed content!
552 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
553 || URLUtil.isAboutUrl(url))) {
554 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
555 }
556 }
557 }
558 }
559
560 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700561 * Show a dialog informing the user of the network error reported by
562 * WebCore if it is in the foreground.
563 */
564 @Override
565 public void onReceivedError(WebView view, int errorCode,
566 String description, String failingUrl) {
567 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
568 errorCode != WebViewClient.ERROR_CONNECT &&
569 errorCode != WebViewClient.ERROR_BAD_URL &&
570 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
571 errorCode != WebViewClient.ERROR_FILE) {
572 queueError(errorCode, description);
573 }
574 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
575 + " " + description);
576
577 // We need to reset the title after an error if it is in foreground.
578 if (mInForeground) {
579 mActivity.resetTitleAndRevertLockIcon();
580 }
581 }
582
583 /**
584 * Check with the user if it is ok to resend POST data as the page they
585 * are trying to navigate to is the result of a POST.
586 */
587 @Override
588 public void onFormResubmission(WebView view, final Message dontResend,
589 final Message resend) {
590 if (!mInForeground) {
591 dontResend.sendToTarget();
592 return;
593 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500594 if (mDontResend != null) {
595 Log.w(LOGTAG, "onFormResubmission should not be called again "
596 + "while dialog is still up");
597 dontResend.sendToTarget();
598 return;
599 }
600 mDontResend = dontResend;
601 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700602 new AlertDialog.Builder(mActivity).setTitle(
603 R.string.browserFrameFormResubmitLabel).setMessage(
604 R.string.browserFrameFormResubmitMessage)
605 .setPositiveButton(R.string.ok,
606 new DialogInterface.OnClickListener() {
607 public void onClick(DialogInterface dialog,
608 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500609 if (mResend != null) {
610 mResend.sendToTarget();
611 mResend = null;
612 mDontResend = null;
613 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700614 }
615 }).setNegativeButton(R.string.cancel,
616 new DialogInterface.OnClickListener() {
617 public void onClick(DialogInterface dialog,
618 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500619 if (mDontResend != null) {
620 mDontResend.sendToTarget();
621 mResend = null;
622 mDontResend = null;
623 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700624 }
625 }).setOnCancelListener(new OnCancelListener() {
626 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500627 if (mDontResend != null) {
628 mDontResend.sendToTarget();
629 mResend = null;
630 mDontResend = null;
631 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700632 }
633 }).show();
634 }
635
636 /**
637 * Insert the url into the visited history database.
638 * @param url The url to be inserted.
639 * @param isReload True if this url is being reloaded.
640 * FIXME: Not sure what to do when reloading the page.
641 */
642 @Override
643 public void doUpdateVisitedHistory(WebView view, String url,
644 boolean isReload) {
645 if (url.regionMatches(true, 0, "about:", 0, 6)) {
646 return;
647 }
648 // remove "client" before updating it to the history so that it wont
649 // show up in the auto-complete list.
650 int index = url.indexOf("client=ms-");
651 if (index > 0 && url.contains(".google.")) {
652 int end = url.indexOf('&', index);
653 if (end > 0) {
654 url = url.substring(0, index)
655 .concat(url.substring(end + 1));
656 } else {
657 // the url.charAt(index-1) should be either '?' or '&'
658 url = url.substring(0, index-1);
659 }
660 }
661 Browser.updateVisitedHistory(mActivity.getContentResolver(), url,
662 true);
663 WebIconDatabase.getInstance().retainIconForPageUrl(url);
664 }
665
666 /**
667 * Displays SSL error(s) dialog to the user.
668 */
669 @Override
670 public void onReceivedSslError(final WebView view,
671 final SslErrorHandler handler, final SslError error) {
672 if (!mInForeground) {
673 handler.cancel();
674 return;
675 }
676 if (BrowserSettings.getInstance().showSecurityWarnings()) {
677 final LayoutInflater factory =
678 LayoutInflater.from(mActivity);
679 final View warningsView =
680 factory.inflate(R.layout.ssl_warnings, null);
681 final LinearLayout placeholder =
682 (LinearLayout)warningsView.findViewById(R.id.placeholder);
683
684 if (error.hasError(SslError.SSL_UNTRUSTED)) {
685 LinearLayout ll = (LinearLayout)factory
686 .inflate(R.layout.ssl_warning, null);
687 ((TextView)ll.findViewById(R.id.warning))
688 .setText(R.string.ssl_untrusted);
689 placeholder.addView(ll);
690 }
691
692 if (error.hasError(SslError.SSL_IDMISMATCH)) {
693 LinearLayout ll = (LinearLayout)factory
694 .inflate(R.layout.ssl_warning, null);
695 ((TextView)ll.findViewById(R.id.warning))
696 .setText(R.string.ssl_mismatch);
697 placeholder.addView(ll);
698 }
699
700 if (error.hasError(SslError.SSL_EXPIRED)) {
701 LinearLayout ll = (LinearLayout)factory
702 .inflate(R.layout.ssl_warning, null);
703 ((TextView)ll.findViewById(R.id.warning))
704 .setText(R.string.ssl_expired);
705 placeholder.addView(ll);
706 }
707
708 if (error.hasError(SslError.SSL_NOTYETVALID)) {
709 LinearLayout ll = (LinearLayout)factory
710 .inflate(R.layout.ssl_warning, null);
711 ((TextView)ll.findViewById(R.id.warning))
712 .setText(R.string.ssl_not_yet_valid);
713 placeholder.addView(ll);
714 }
715
716 new AlertDialog.Builder(mActivity).setTitle(
717 R.string.security_warning).setIcon(
718 android.R.drawable.ic_dialog_alert).setView(
719 warningsView).setPositiveButton(R.string.ssl_continue,
720 new DialogInterface.OnClickListener() {
721 public void onClick(DialogInterface dialog,
722 int whichButton) {
723 handler.proceed();
724 }
725 }).setNeutralButton(R.string.view_certificate,
726 new DialogInterface.OnClickListener() {
727 public void onClick(DialogInterface dialog,
728 int whichButton) {
729 mActivity.showSSLCertificateOnError(view,
730 handler, error);
731 }
732 }).setNegativeButton(R.string.cancel,
733 new DialogInterface.OnClickListener() {
734 public void onClick(DialogInterface dialog,
735 int whichButton) {
736 handler.cancel();
737 mActivity.resetTitleAndRevertLockIcon();
738 }
739 }).setOnCancelListener(
740 new DialogInterface.OnCancelListener() {
741 public void onCancel(DialogInterface dialog) {
742 handler.cancel();
743 mActivity.resetTitleAndRevertLockIcon();
744 }
745 }).show();
746 } else {
747 handler.proceed();
748 }
749 }
750
751 /**
752 * Handles an HTTP authentication request.
753 *
754 * @param handler The authentication handler
755 * @param host The host
756 * @param realm The realm
757 */
758 @Override
759 public void onReceivedHttpAuthRequest(WebView view,
760 final HttpAuthHandler handler, final String host,
761 final String realm) {
762 String username = null;
763 String password = null;
764
765 boolean reuseHttpAuthUsernamePassword = handler
766 .useHttpAuthUsernamePassword();
767
768 if (reuseHttpAuthUsernamePassword && mMainView != null) {
769 String[] credentials = mMainView.getHttpAuthUsernamePassword(
770 host, realm);
771 if (credentials != null && credentials.length == 2) {
772 username = credentials[0];
773 password = credentials[1];
774 }
775 }
776
777 if (username != null && password != null) {
778 handler.proceed(username, password);
779 } else {
780 if (mInForeground) {
781 mActivity.showHttpAuthentication(handler, host, realm,
782 null, null, null, 0);
783 } else {
784 handler.cancel();
785 }
786 }
787 }
788
789 @Override
790 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
791 if (!mInForeground) {
792 return false;
793 }
794 if (mActivity.isMenuDown()) {
795 // only check shortcut key when MENU is held
796 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
797 event);
798 } else {
799 return false;
800 }
801 }
802
803 @Override
804 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
805 if (!mInForeground) {
806 return;
807 }
808 if (event.isDown()) {
809 mActivity.onKeyDown(event.getKeyCode(), event);
810 } else {
811 mActivity.onKeyUp(event.getKeyCode(), event);
812 }
813 }
814 };
815
816 // -------------------------------------------------------------------------
817 // WebChromeClient implementation for the main WebView
818 // -------------------------------------------------------------------------
819
820 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
821 // Helper method to create a new tab or sub window.
822 private void createWindow(final boolean dialog, final Message msg) {
823 WebView.WebViewTransport transport =
824 (WebView.WebViewTransport) msg.obj;
825 if (dialog) {
826 createSubWindow();
827 mActivity.attachSubWindow(Tab.this);
828 transport.setWebView(mSubView);
829 } else {
830 final Tab newTab = mActivity.openTabAndShow(
831 BrowserActivity.EMPTY_URL_DATA, false, null);
832 if (newTab != Tab.this) {
833 Tab.this.addChildTab(newTab);
834 }
835 transport.setWebView(newTab.getWebView());
836 }
837 msg.sendToTarget();
838 }
839
840 @Override
841 public boolean onCreateWindow(WebView view, final boolean dialog,
842 final boolean userGesture, final Message resultMsg) {
843 // only allow new window or sub window for the foreground case
844 if (!mInForeground) {
845 return false;
846 }
847 // Short-circuit if we can't create any more tabs or sub windows.
848 if (dialog && mSubView != null) {
849 new AlertDialog.Builder(mActivity)
850 .setTitle(R.string.too_many_subwindows_dialog_title)
851 .setIcon(android.R.drawable.ic_dialog_alert)
852 .setMessage(R.string.too_many_subwindows_dialog_message)
853 .setPositiveButton(R.string.ok, null)
854 .show();
855 return false;
856 } else if (!mActivity.getTabControl().canCreateNewTab()) {
857 new AlertDialog.Builder(mActivity)
858 .setTitle(R.string.too_many_windows_dialog_title)
859 .setIcon(android.R.drawable.ic_dialog_alert)
860 .setMessage(R.string.too_many_windows_dialog_message)
861 .setPositiveButton(R.string.ok, null)
862 .show();
863 return false;
864 }
865
866 // Short-circuit if this was a user gesture.
867 if (userGesture) {
868 createWindow(dialog, resultMsg);
869 return true;
870 }
871
872 // Allow the popup and create the appropriate window.
873 final AlertDialog.OnClickListener allowListener =
874 new AlertDialog.OnClickListener() {
875 public void onClick(DialogInterface d,
876 int which) {
877 createWindow(dialog, resultMsg);
878 }
879 };
880
881 // Block the popup by returning a null WebView.
882 final AlertDialog.OnClickListener blockListener =
883 new AlertDialog.OnClickListener() {
884 public void onClick(DialogInterface d, int which) {
885 resultMsg.sendToTarget();
886 }
887 };
888
889 // Build a confirmation dialog to display to the user.
890 final AlertDialog d =
891 new AlertDialog.Builder(mActivity)
892 .setTitle(R.string.attention)
893 .setIcon(android.R.drawable.ic_dialog_alert)
894 .setMessage(R.string.popup_window_attempt)
895 .setPositiveButton(R.string.allow, allowListener)
896 .setNegativeButton(R.string.block, blockListener)
897 .setCancelable(false)
898 .create();
899
900 // Show the confirmation dialog.
901 d.show();
902 return true;
903 }
904
905 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500906 public void onRequestFocus(WebView view) {
907 if (!mInForeground) {
908 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
909 Tab.this));
910 }
911 }
912
913 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700914 public void onCloseWindow(WebView window) {
915 if (mParentTab != null) {
916 // JavaScript can only close popup window.
917 if (mInForeground) {
918 mActivity.switchToTab(mActivity.getTabControl()
919 .getTabIndex(mParentTab));
920 }
921 mActivity.closeTab(Tab.this);
922 }
923 }
924
925 @Override
926 public void onProgressChanged(WebView view, int newProgress) {
927 if (newProgress == 100) {
928 // sync cookies and cache promptly here.
929 CookieSyncManager.getInstance().sync();
930 }
931 if (mInForeground) {
932 mActivity.onProgressChanged(view, newProgress);
933 }
934 }
935
936 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500937 public void onReceivedTitle(WebView view, final String title) {
938 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 if (mInForeground) {
940 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500941 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700942 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500943 if (pageUrl == null || pageUrl.length()
944 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700945 return;
946 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500947 new AsyncTask<Void, Void, Void>() {
948 protected Void doInBackground(Void... unused) {
949 // See if we can find the current url in our history
950 // database and add the new title to it.
951 String url = pageUrl;
952 if (url.startsWith("http://www.")) {
953 url = url.substring(11);
954 } else if (url.startsWith("http://")) {
955 url = url.substring(4);
956 }
957 Cursor c = null;
958 try {
959 final ContentResolver cr
960 = mActivity.getContentResolver();
961 url = "%" + url;
962 String [] selArgs = new String[] { url };
963 String where = Browser.BookmarkColumns.URL
964 + " LIKE ? AND "
965 + Browser.BookmarkColumns.BOOKMARK + " = 0";
966 c = cr.query(Browser.BOOKMARKS_URI, new String[]
967 { Browser.BookmarkColumns._ID }, where, selArgs,
968 null);
969 if (c.moveToFirst()) {
970 // Current implementation of database only has one
971 // entry per url.
972 ContentValues map = new ContentValues();
973 map.put(Browser.BookmarkColumns.TITLE, title);
974 String[] projection = new String[]
975 { Integer.valueOf(c.getInt(0)).toString() };
976 cr.update(Browser.BOOKMARKS_URI, map, "_id = ?",
977 projection);
978 }
979 } catch (IllegalStateException e) {
980 Log.e(LOGTAG, "Tab onReceived title", e);
981 } catch (SQLiteException ex) {
982 Log.e(LOGTAG,
983 "onReceivedTitle() caught SQLiteException: ",
984 ex);
985 } finally {
986 if (c != null) c.close();
987 }
988 return null;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700989 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500990 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700991 }
992
993 @Override
994 public void onReceivedIcon(WebView view, Bitmap icon) {
995 if (icon != null) {
996 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
997 .getContentResolver(), view.getOriginalUrl(), view
998 .getUrl(), icon);
999 }
1000 if (mInForeground) {
1001 mActivity.setFavicon(icon);
1002 }
1003 }
1004
1005 @Override
1006 public void onReceivedTouchIconUrl(WebView view, String url,
1007 boolean precomposed) {
1008 final ContentResolver cr = mActivity.getContentResolver();
1009 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
1010 view.getOriginalUrl(), view.getUrl(), true);
1011 if (c != null) {
1012 if (c.getCount() > 0) {
1013 // Let precomposed icons take precedence over non-composed
1014 // icons.
1015 if (precomposed && mTouchIconLoader != null) {
1016 mTouchIconLoader.cancel(false);
1017 mTouchIconLoader = null;
1018 }
1019 // Have only one async task at a time.
1020 if (mTouchIconLoader == null) {
1021 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
1022 c, view);
1023 mTouchIconLoader.execute(url);
Patrick Scott8e9fe322010-03-04 14:29:31 -05001024 } else {
1025 c.close();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001026 }
1027 } else {
1028 c.close();
1029 }
1030 }
1031 }
1032
1033 @Override
1034 public void onShowCustomView(View view,
1035 WebChromeClient.CustomViewCallback callback) {
1036 if (mInForeground) mActivity.onShowCustomView(view, callback);
1037 }
1038
1039 @Override
1040 public void onHideCustomView() {
1041 if (mInForeground) mActivity.onHideCustomView();
1042 }
1043
1044 /**
1045 * The origin has exceeded its database quota.
1046 * @param url the URL that exceeded the quota
1047 * @param databaseIdentifier the identifier of the database on which the
1048 * transaction that caused the quota overflow was run
1049 * @param currentQuota the current quota for the origin.
1050 * @param estimatedSize the estimated size of the database.
1051 * @param totalUsedQuota is the sum of all origins' quota.
1052 * @param quotaUpdater The callback to run when a decision to allow or
1053 * deny quota has been made. Don't forget to call this!
1054 */
1055 @Override
1056 public void onExceededDatabaseQuota(String url,
1057 String databaseIdentifier, long currentQuota, long estimatedSize,
1058 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1059 BrowserSettings.getInstance().getWebStorageSizeManager()
1060 .onExceededDatabaseQuota(url, databaseIdentifier,
1061 currentQuota, estimatedSize, totalUsedQuota,
1062 quotaUpdater);
1063 }
1064
1065 /**
1066 * The Application Cache has exceeded its max size.
1067 * @param spaceNeeded is the amount of disk space that would be needed
1068 * in order for the last appcache operation to succeed.
1069 * @param totalUsedQuota is the sum of all origins' quota.
1070 * @param quotaUpdater A callback to inform the WebCore thread that a
1071 * new app cache size is available. This callback must always
1072 * be executed at some point to ensure that the sleeping
1073 * WebCore thread is woken up.
1074 */
1075 @Override
1076 public void onReachedMaxAppCacheSize(long spaceNeeded,
1077 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1078 BrowserSettings.getInstance().getWebStorageSizeManager()
1079 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1080 quotaUpdater);
1081 }
1082
1083 /**
1084 * Instructs the browser to show a prompt to ask the user to set the
1085 * Geolocation permission state for the specified origin.
1086 * @param origin The origin for which Geolocation permissions are
1087 * requested.
1088 * @param callback The callback to call once the user has set the
1089 * Geolocation permission state.
1090 */
1091 @Override
1092 public void onGeolocationPermissionsShowPrompt(String origin,
1093 GeolocationPermissions.Callback callback) {
1094 if (mInForeground) {
1095 mGeolocationPermissionsPrompt.show(origin, callback);
1096 }
1097 }
1098
1099 /**
1100 * Instructs the browser to hide the Geolocation permissions prompt.
1101 */
1102 @Override
1103 public void onGeolocationPermissionsHidePrompt() {
1104 if (mInForeground) {
1105 mGeolocationPermissionsPrompt.hide();
1106 }
1107 }
1108
Ben Murdoch65acc352009-11-19 18:16:04 +00001109 /* Adds a JavaScript error message to the system log and if the JS
1110 * console is enabled in the about:debug options, to that console
1111 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001112 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001113 */
1114 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001115 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001116 if (mInForeground) {
1117 // call getErrorConsole(true) so it will create one if needed
1118 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001119 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001120 if (mActivity.shouldShowErrorConsole()
1121 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1122 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1123 }
1124 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001125
1126 String message = "Console: " + consoleMessage.message() + " "
1127 + consoleMessage.sourceId() + ":"
1128 + consoleMessage.lineNumber();
1129
1130 switch (consoleMessage.messageLevel()) {
1131 case TIP:
1132 Log.v(CONSOLE_LOGTAG, message);
1133 break;
1134 case LOG:
1135 Log.i(CONSOLE_LOGTAG, message);
1136 break;
1137 case WARNING:
1138 Log.w(CONSOLE_LOGTAG, message);
1139 break;
1140 case ERROR:
1141 Log.e(CONSOLE_LOGTAG, message);
1142 break;
1143 case DEBUG:
1144 Log.d(CONSOLE_LOGTAG, message);
1145 break;
1146 }
1147
1148 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001149 }
1150
1151 /**
1152 * Ask the browser for an icon to represent a <video> element.
1153 * This icon will be used if the Web page did not specify a poster attribute.
1154 * @return Bitmap The icon or null if no such icon is available.
1155 */
1156 @Override
1157 public Bitmap getDefaultVideoPoster() {
1158 if (mInForeground) {
1159 return mActivity.getDefaultVideoPoster();
1160 }
1161 return null;
1162 }
1163
1164 /**
1165 * Ask the host application for a custom progress view to show while
1166 * a <video> is loading.
1167 * @return View The progress view.
1168 */
1169 @Override
1170 public View getVideoLoadingProgressView() {
1171 if (mInForeground) {
1172 return mActivity.getVideoLoadingProgressView();
1173 }
1174 return null;
1175 }
1176
1177 @Override
1178 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
1179 if (mInForeground) {
1180 mActivity.openFileChooser(uploadMsg);
1181 } else {
1182 uploadMsg.onReceiveValue(null);
1183 }
1184 }
1185
1186 /**
1187 * Deliver a list of already-visited URLs
1188 */
1189 @Override
1190 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1191 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
1192 public String[] doInBackground(Void... unused) {
1193 return Browser.getVisitedHistory(mActivity
1194 .getContentResolver());
1195 }
1196 public void onPostExecute(String[] result) {
1197 callback.onReceiveValue(result);
1198 };
1199 };
1200 task.execute();
1201 };
1202 };
1203
1204 // -------------------------------------------------------------------------
1205 // WebViewClient implementation for the sub window
1206 // -------------------------------------------------------------------------
1207
1208 // Subclass of WebViewClient used in subwindows to notify the main
1209 // WebViewClient of certain WebView activities.
1210 private static class SubWindowClient extends WebViewClient {
1211 // The main WebViewClient.
1212 private final WebViewClient mClient;
1213
1214 SubWindowClient(WebViewClient client) {
1215 mClient = client;
1216 }
1217 @Override
1218 public void doUpdateVisitedHistory(WebView view, String url,
1219 boolean isReload) {
1220 mClient.doUpdateVisitedHistory(view, url, isReload);
1221 }
1222 @Override
1223 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1224 return mClient.shouldOverrideUrlLoading(view, url);
1225 }
1226 @Override
1227 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1228 SslError error) {
1229 mClient.onReceivedSslError(view, handler, error);
1230 }
1231 @Override
1232 public void onReceivedHttpAuthRequest(WebView view,
1233 HttpAuthHandler handler, String host, String realm) {
1234 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1235 }
1236 @Override
1237 public void onFormResubmission(WebView view, Message dontResend,
1238 Message resend) {
1239 mClient.onFormResubmission(view, dontResend, resend);
1240 }
1241 @Override
1242 public void onReceivedError(WebView view, int errorCode,
1243 String description, String failingUrl) {
1244 mClient.onReceivedError(view, errorCode, description, failingUrl);
1245 }
1246 @Override
1247 public boolean shouldOverrideKeyEvent(WebView view,
1248 android.view.KeyEvent event) {
1249 return mClient.shouldOverrideKeyEvent(view, event);
1250 }
1251 @Override
1252 public void onUnhandledKeyEvent(WebView view,
1253 android.view.KeyEvent event) {
1254 mClient.onUnhandledKeyEvent(view, event);
1255 }
1256 }
1257
1258 // -------------------------------------------------------------------------
1259 // WebChromeClient implementation for the sub window
1260 // -------------------------------------------------------------------------
1261
1262 private class SubWindowChromeClient extends WebChromeClient {
1263 // The main WebChromeClient.
1264 private final WebChromeClient mClient;
1265
1266 SubWindowChromeClient(WebChromeClient client) {
1267 mClient = client;
1268 }
1269 @Override
1270 public void onProgressChanged(WebView view, int newProgress) {
1271 mClient.onProgressChanged(view, newProgress);
1272 }
1273 @Override
1274 public boolean onCreateWindow(WebView view, boolean dialog,
1275 boolean userGesture, android.os.Message resultMsg) {
1276 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1277 }
1278 @Override
1279 public void onCloseWindow(WebView window) {
1280 if (window != mSubView) {
1281 Log.e(LOGTAG, "Can't close the window");
1282 }
1283 mActivity.dismissSubWindow(Tab.this);
1284 }
1285 }
1286
1287 // -------------------------------------------------------------------------
1288
1289 // Construct a new tab
1290 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1291 String url) {
1292 mActivity = activity;
1293 mCloseOnExit = closeOnExit;
1294 mAppId = appId;
1295 mOriginalUrl = url;
1296 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1297 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1298 mInLoad = false;
1299 mInForeground = false;
1300
1301 mInflateService = LayoutInflater.from(activity);
1302
1303 // The tab consists of a container view, which contains the main
1304 // WebView, as well as any other UI elements associated with the tab.
1305 mContainer = mInflateService.inflate(R.layout.tab, null);
1306
1307 mGeolocationPermissionsPrompt =
1308 (GeolocationPermissionsPrompt) mContainer.findViewById(
1309 R.id.geolocation_permissions_prompt);
1310
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001311 mDownloadListener = new DownloadListener() {
1312 public void onDownloadStart(String url, String userAgent,
1313 String contentDisposition, String mimetype,
1314 long contentLength) {
1315 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1316 mimetype, contentLength);
1317 if (mMainView.copyBackForwardList().getSize() == 0) {
1318 // This Tab was opened for the sole purpose of downloading a
1319 // file. Remove it.
1320 if (mActivity.getTabControl().getCurrentWebView()
1321 == mMainView) {
1322 // In this case, the Tab is still on top.
1323 mActivity.goBackOnePageOrQuit();
1324 } else {
1325 // In this case, it is not.
1326 mActivity.closeTab(Tab.this);
1327 }
1328 }
1329 }
1330 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001331 mWebBackForwardListClient = new WebBackForwardListClient() {
1332 @Override
1333 public void onNewHistoryItem(WebHistoryItem item) {
1334 if (isInVoiceSearchMode()) {
1335 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1336 }
1337 }
1338 @Override
1339 public void onIndexChanged(WebHistoryItem item, int index) {
1340 Object data = item.getCustomData();
1341 if (data != null && data instanceof Intent) {
1342 activateVoiceSearchMode((Intent) data);
1343 }
1344 }
1345 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001346
Grace Kloba22ac16e2009-10-07 18:00:23 -07001347 setWebView(w);
1348 }
1349
1350 /**
1351 * Sets the WebView for this tab, correctly removing the old WebView from
1352 * the container view.
1353 */
1354 void setWebView(WebView w) {
1355 if (mMainView == w) {
1356 return;
1357 }
1358 // If the WebView is changing, the page will be reloaded, so any ongoing
1359 // Geolocation permission requests are void.
1360 mGeolocationPermissionsPrompt.hide();
1361
1362 // Just remove the old one.
1363 FrameLayout wrapper =
1364 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1365 wrapper.removeView(mMainView);
1366
1367 // set the new one
1368 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001369 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001370 if (mMainView != null) {
1371 mMainView.setWebViewClient(mWebViewClient);
1372 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001373 // Attach DownloadManager so that downloads can start in an active
1374 // or a non-active window. This can happen when going to a site that
1375 // does a redirect after a period of time. The user could have
1376 // switched to another tab while waiting for the download to start.
1377 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001378 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001379 }
1380 }
1381
1382 /**
1383 * Destroy the tab's main WebView and subWindow if any
1384 */
1385 void destroy() {
1386 if (mMainView != null) {
1387 dismissSubWindow();
1388 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1389 // save the WebView to call destroy() after detach it from the tab
1390 WebView webView = mMainView;
1391 setWebView(null);
1392 webView.destroy();
1393 }
1394 }
1395
1396 /**
1397 * Remove the tab from the parent
1398 */
1399 void removeFromTree() {
1400 // detach the children
1401 if (mChildTabs != null) {
1402 for(Tab t : mChildTabs) {
1403 t.setParentTab(null);
1404 }
1405 }
1406 // remove itself from the parent list
1407 if (mParentTab != null) {
1408 mParentTab.mChildTabs.remove(this);
1409 }
1410 }
1411
1412 /**
1413 * Create a new subwindow unless a subwindow already exists.
1414 * @return True if a new subwindow was created. False if one already exists.
1415 */
1416 boolean createSubWindow() {
1417 if (mSubView == null) {
1418 mSubViewContainer = mInflateService.inflate(
1419 R.layout.browser_subwindow, null);
1420 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1421 // use trackball directly
1422 mSubView.setMapTrackballToArrowKeys(false);
1423 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1424 mSubView.setWebChromeClient(new SubWindowChromeClient(
1425 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001426 // Set a different DownloadListener for the mSubView, since it will
1427 // just need to dismiss the mSubView, rather than close the Tab
1428 mSubView.setDownloadListener(new DownloadListener() {
1429 public void onDownloadStart(String url, String userAgent,
1430 String contentDisposition, String mimetype,
1431 long contentLength) {
1432 mActivity.onDownloadStart(url, userAgent,
1433 contentDisposition, mimetype, contentLength);
1434 if (mSubView.copyBackForwardList().getSize() == 0) {
1435 // This subwindow was opened for the sole purpose of
1436 // downloading a file. Remove it.
1437 dismissSubWindow();
1438 }
1439 }
1440 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001441 mSubView.setOnCreateContextMenuListener(mActivity);
1442 final BrowserSettings s = BrowserSettings.getInstance();
1443 s.addObserver(mSubView.getSettings()).update(s, null);
1444 final ImageButton cancel = (ImageButton) mSubViewContainer
1445 .findViewById(R.id.subwindow_close);
1446 cancel.setOnClickListener(new OnClickListener() {
1447 public void onClick(View v) {
1448 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1449 }
1450 });
1451 return true;
1452 }
1453 return false;
1454 }
1455
1456 /**
1457 * Dismiss the subWindow for the tab.
1458 */
1459 void dismissSubWindow() {
1460 if (mSubView != null) {
1461 BrowserSettings.getInstance().deleteObserver(
1462 mSubView.getSettings());
1463 mSubView.destroy();
1464 mSubView = null;
1465 mSubViewContainer = null;
1466 }
1467 }
1468
1469 /**
1470 * Attach the sub window to the content view.
1471 */
1472 void attachSubWindow(ViewGroup content) {
1473 if (mSubView != null) {
1474 content.addView(mSubViewContainer,
1475 BrowserActivity.COVER_SCREEN_PARAMS);
1476 }
1477 }
1478
1479 /**
1480 * Remove the sub window from the content view.
1481 */
1482 void removeSubWindow(ViewGroup content) {
1483 if (mSubView != null) {
1484 content.removeView(mSubViewContainer);
1485 }
1486 }
1487
1488 /**
1489 * This method attaches both the WebView and any sub window to the
1490 * given content view.
1491 */
1492 void attachTabToContentView(ViewGroup content) {
1493 if (mMainView == null) {
1494 return;
1495 }
1496
1497 // Attach the WebView to the container and then attach the
1498 // container to the content view.
1499 FrameLayout wrapper =
1500 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1501 wrapper.addView(mMainView);
1502 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1503 attachSubWindow(content);
1504 }
1505
1506 /**
1507 * Remove the WebView and any sub window from the given content view.
1508 */
1509 void removeTabFromContentView(ViewGroup content) {
1510 if (mMainView == null) {
1511 return;
1512 }
1513
1514 // Remove the container from the content and then remove the
1515 // WebView from the container. This will trigger a focus change
1516 // needed by WebView.
1517 FrameLayout wrapper =
1518 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1519 wrapper.removeView(mMainView);
1520 content.removeView(mContainer);
1521 removeSubWindow(content);
1522 }
1523
1524 /**
1525 * Set the parent tab of this tab.
1526 */
1527 void setParentTab(Tab parent) {
1528 mParentTab = parent;
1529 // This tab may have been freed due to low memory. If that is the case,
1530 // the parent tab index is already saved. If we are changing that index
1531 // (most likely due to removing the parent tab) we must update the
1532 // parent tab index in the saved Bundle.
1533 if (mSavedState != null) {
1534 if (parent == null) {
1535 mSavedState.remove(PARENTTAB);
1536 } else {
1537 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1538 .getTabIndex(parent));
1539 }
1540 }
1541 }
1542
1543 /**
1544 * When a Tab is created through the content of another Tab, then we
1545 * associate the Tabs.
1546 * @param child the Tab that was created from this Tab
1547 */
1548 void addChildTab(Tab child) {
1549 if (mChildTabs == null) {
1550 mChildTabs = new Vector<Tab>();
1551 }
1552 mChildTabs.add(child);
1553 child.setParentTab(this);
1554 }
1555
1556 Vector<Tab> getChildTabs() {
1557 return mChildTabs;
1558 }
1559
1560 void resume() {
1561 if (mMainView != null) {
1562 mMainView.onResume();
1563 if (mSubView != null) {
1564 mSubView.onResume();
1565 }
1566 }
1567 }
1568
1569 void pause() {
1570 if (mMainView != null) {
1571 mMainView.onPause();
1572 if (mSubView != null) {
1573 mSubView.onPause();
1574 }
1575 }
1576 }
1577
1578 void putInForeground() {
1579 mInForeground = true;
1580 resume();
1581 mMainView.setOnCreateContextMenuListener(mActivity);
1582 if (mSubView != null) {
1583 mSubView.setOnCreateContextMenuListener(mActivity);
1584 }
1585 // Show the pending error dialog if the queue is not empty
1586 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1587 showError(mQueuedErrors.getFirst());
1588 }
1589 }
1590
1591 void putInBackground() {
1592 mInForeground = false;
1593 pause();
1594 mMainView.setOnCreateContextMenuListener(null);
1595 if (mSubView != null) {
1596 mSubView.setOnCreateContextMenuListener(null);
1597 }
1598 }
1599
1600 /**
1601 * Return the top window of this tab; either the subwindow if it is not
1602 * null or the main window.
1603 * @return The top window of this tab.
1604 */
1605 WebView getTopWindow() {
1606 if (mSubView != null) {
1607 return mSubView;
1608 }
1609 return mMainView;
1610 }
1611
1612 /**
1613 * Return the main window of this tab. Note: if a tab is freed in the
1614 * background, this can return null. It is only guaranteed to be
1615 * non-null for the current tab.
1616 * @return The main WebView of this tab.
1617 */
1618 WebView getWebView() {
1619 return mMainView;
1620 }
1621
1622 /**
1623 * Return the subwindow of this tab or null if there is no subwindow.
1624 * @return The subwindow of this tab or null.
1625 */
1626 WebView getSubWebView() {
1627 return mSubView;
1628 }
1629
1630 /**
1631 * @return The geolocation permissions prompt for this tab.
1632 */
1633 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1634 return mGeolocationPermissionsPrompt;
1635 }
1636
1637 /**
1638 * @return The application id string
1639 */
1640 String getAppId() {
1641 return mAppId;
1642 }
1643
1644 /**
1645 * Set the application id string
1646 * @param id
1647 */
1648 void setAppId(String id) {
1649 mAppId = id;
1650 }
1651
1652 /**
1653 * @return The original url associated with this Tab
1654 */
1655 String getOriginalUrl() {
1656 return mOriginalUrl;
1657 }
1658
1659 /**
1660 * Set the original url associated with this tab
1661 */
1662 void setOriginalUrl(String url) {
1663 mOriginalUrl = url;
1664 }
1665
1666 /**
1667 * Get the url of this tab. Valid after calling populatePickerData, but
1668 * before calling wipePickerData, or if the webview has been destroyed.
1669 * @return The WebView's url or null.
1670 */
1671 String getUrl() {
1672 if (mPickerData != null) {
1673 return mPickerData.mUrl;
1674 }
1675 return null;
1676 }
1677
1678 /**
1679 * Get the title of this tab. Valid after calling populatePickerData, but
1680 * before calling wipePickerData, or if the webview has been destroyed. If
1681 * the url has no title, use the url instead.
1682 * @return The WebView's title (or url) or null.
1683 */
1684 String getTitle() {
1685 if (mPickerData != null) {
1686 return mPickerData.mTitle;
1687 }
1688 return null;
1689 }
1690
1691 /**
1692 * Get the favicon of this tab. Valid after calling populatePickerData, but
1693 * before calling wipePickerData, or if the webview has been destroyed.
1694 * @return The WebView's favicon or null.
1695 */
1696 Bitmap getFavicon() {
1697 if (mPickerData != null) {
1698 return mPickerData.mFavicon;
1699 }
1700 return null;
1701 }
1702
1703 /**
1704 * Return the tab's error console. Creates the console if createIfNEcessary
1705 * is true and we haven't already created the console.
1706 * @param createIfNecessary Flag to indicate if the console should be
1707 * created if it has not been already.
1708 * @return The tab's error console, or null if one has not been created and
1709 * createIfNecessary is false.
1710 */
1711 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1712 if (createIfNecessary && mErrorConsole == null) {
1713 mErrorConsole = new ErrorConsoleView(mActivity);
1714 mErrorConsole.setWebView(mMainView);
1715 }
1716 return mErrorConsole;
1717 }
1718
1719 /**
1720 * If this Tab was created through another Tab, then this method returns
1721 * that Tab.
1722 * @return the Tab parent or null
1723 */
1724 public Tab getParentTab() {
1725 return mParentTab;
1726 }
1727
1728 /**
1729 * Return whether this tab should be closed when it is backing out of the
1730 * first page.
1731 * @return TRUE if this tab should be closed when exit.
1732 */
1733 boolean closeOnExit() {
1734 return mCloseOnExit;
1735 }
1736
1737 /**
1738 * Saves the current lock-icon state before resetting the lock icon. If we
1739 * have an error, we may need to roll back to the previous state.
1740 */
1741 void resetLockIcon(String url) {
1742 mPrevLockIconType = mLockIconType;
1743 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1744 if (URLUtil.isHttpsUrl(url)) {
1745 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1746 }
1747 }
1748
1749 /**
1750 * Reverts the lock-icon state to the last saved state, for example, if we
1751 * had an error, and need to cancel the load.
1752 */
1753 void revertLockIcon() {
1754 mLockIconType = mPrevLockIconType;
1755 }
1756
1757 /**
1758 * @return The tab's lock icon type.
1759 */
1760 int getLockIconType() {
1761 return mLockIconType;
1762 }
1763
1764 /**
1765 * @return TRUE if onPageStarted is called while onPageFinished is not
1766 * called yet.
1767 */
1768 boolean inLoad() {
1769 return mInLoad;
1770 }
1771
1772 // force mInLoad to be false. This should only be called before closing the
1773 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1774 void clearInLoad() {
1775 mInLoad = false;
1776 }
1777
1778 void populatePickerData() {
1779 if (mMainView == null) {
1780 populatePickerDataFromSavedState();
1781 return;
1782 }
1783
1784 // FIXME: The only place we cared about subwindow was for
1785 // bookmarking (i.e. not when saving state). Was this deliberate?
1786 final WebBackForwardList list = mMainView.copyBackForwardList();
1787 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1788 populatePickerData(item);
1789 }
1790
1791 // Populate the picker data using the given history item and the current top
1792 // WebView.
1793 private void populatePickerData(WebHistoryItem item) {
1794 mPickerData = new PickerData();
1795 if (item != null) {
1796 mPickerData.mUrl = item.getUrl();
1797 mPickerData.mTitle = item.getTitle();
1798 mPickerData.mFavicon = item.getFavicon();
1799 if (mPickerData.mTitle == null) {
1800 mPickerData.mTitle = mPickerData.mUrl;
1801 }
1802 }
1803 }
1804
1805 // Create the PickerData and populate it using the saved state of the tab.
1806 void populatePickerDataFromSavedState() {
1807 if (mSavedState == null) {
1808 return;
1809 }
1810 mPickerData = new PickerData();
1811 mPickerData.mUrl = mSavedState.getString(CURRURL);
1812 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1813 }
1814
1815 void clearPickerData() {
1816 mPickerData = null;
1817 }
1818
1819 /**
1820 * Get the saved state bundle.
1821 * @return
1822 */
1823 Bundle getSavedState() {
1824 return mSavedState;
1825 }
1826
1827 /**
1828 * Set the saved state.
1829 */
1830 void setSavedState(Bundle state) {
1831 mSavedState = state;
1832 }
1833
1834 /**
1835 * @return TRUE if succeed in saving the state.
1836 */
1837 boolean saveState() {
1838 // If the WebView is null it means we ran low on memory and we already
1839 // stored the saved state in mSavedState.
1840 if (mMainView == null) {
1841 return mSavedState != null;
1842 }
1843
1844 mSavedState = new Bundle();
1845 final WebBackForwardList list = mMainView.saveState(mSavedState);
1846 if (list != null) {
1847 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1848 mMainView.hashCode() + "_pic.save");
1849 if (mMainView.savePicture(mSavedState, f)) {
1850 mSavedState.putString(CURRPICTURE, f.getPath());
Mike Reedd5eee692010-03-05 10:13:34 -05001851 } else {
1852 // if savePicture returned false, we can't trust the contents,
1853 // and it may be large, so we delete it right away
1854 f.delete();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001855 }
1856 }
1857
1858 // Store some extra info for displaying the tab in the picker.
1859 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1860 populatePickerData(item);
1861
1862 if (mPickerData.mUrl != null) {
1863 mSavedState.putString(CURRURL, mPickerData.mUrl);
1864 }
1865 if (mPickerData.mTitle != null) {
1866 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1867 }
1868 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1869 if (mAppId != null) {
1870 mSavedState.putString(APPID, mAppId);
1871 }
1872 if (mOriginalUrl != null) {
1873 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1874 }
1875 // Remember the parent tab so the relationship can be restored.
1876 if (mParentTab != null) {
1877 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1878 mParentTab));
1879 }
1880 return true;
1881 }
1882
1883 /*
1884 * Restore the state of the tab.
1885 */
1886 boolean restoreState(Bundle b) {
1887 if (b == null) {
1888 return false;
1889 }
1890 // Restore the internal state even if the WebView fails to restore.
1891 // This will maintain the app id, original url and close-on-exit values.
1892 mSavedState = null;
1893 mPickerData = null;
1894 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1895 mAppId = b.getString(APPID);
1896 mOriginalUrl = b.getString(ORIGINALURL);
1897
1898 final WebBackForwardList list = mMainView.restoreState(b);
1899 if (list == null) {
1900 return false;
1901 }
1902 if (b.containsKey(CURRPICTURE)) {
1903 final File f = new File(b.getString(CURRPICTURE));
1904 mMainView.restorePicture(b, f);
1905 f.delete();
1906 }
1907 return true;
1908 }
1909}