blob: d450b508abd8b37c6903a5cae67cf00b738d279c [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
Patrick Scottcc949122010-03-17 16:06:30 -0400491 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700492 }
493
494 // reset sync timer to avoid sync starts during loading a page
495 CookieSyncManager.getInstance().resetSync();
496
497 if (!mActivity.isNetworkUp()) {
498 view.setNetworkAvailable(false);
499 }
500
501 // finally update the UI in the activity if it is in the foreground
502 if (mInForeground) {
503 mActivity.onPageStarted(view, url, favicon);
504 }
505 }
506
507 @Override
508 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000509 LogTag.logPageFinishedLoading(
510 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700511 mInLoad = false;
512
513 if (mInForeground && !mActivity.didUserStopLoading()
514 || !mInForeground) {
515 // Only update the bookmark screenshot if the user did not
516 // cancel the load early.
517 mActivity.postMessage(
518 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
519 500);
520 }
521
522 // finally update the UI in the activity if it is in the foreground
523 if (mInForeground) {
524 mActivity.onPageFinished(view, url);
525 }
526 }
527
528 // return true if want to hijack the url to let another app to handle it
529 @Override
530 public boolean shouldOverrideUrlLoading(WebView view, String url) {
531 if (mInForeground) {
532 return mActivity.shouldOverrideUrlLoading(view, url);
533 } else {
534 return false;
535 }
536 }
537
538 /**
539 * Updates the lock icon. This method is called when we discover another
540 * resource to be loaded for this page (for example, javascript). While
541 * we update the icon type, we do not update the lock icon itself until
542 * we are done loading, it is slightly more secure this way.
543 */
544 @Override
545 public void onLoadResource(WebView view, String url) {
546 if (url != null && url.length() > 0) {
547 // It is only if the page claims to be secure that we may have
548 // to update the lock:
549 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
550 // If NOT a 'safe' url, change the lock to mixed content!
551 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
552 || URLUtil.isAboutUrl(url))) {
553 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
554 }
555 }
556 }
557 }
558
559 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700560 * Show a dialog informing the user of the network error reported by
561 * WebCore if it is in the foreground.
562 */
563 @Override
564 public void onReceivedError(WebView view, int errorCode,
565 String description, String failingUrl) {
566 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
567 errorCode != WebViewClient.ERROR_CONNECT &&
568 errorCode != WebViewClient.ERROR_BAD_URL &&
569 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
570 errorCode != WebViewClient.ERROR_FILE) {
571 queueError(errorCode, description);
572 }
573 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
574 + " " + description);
575
576 // We need to reset the title after an error if it is in foreground.
577 if (mInForeground) {
578 mActivity.resetTitleAndRevertLockIcon();
579 }
580 }
581
582 /**
583 * Check with the user if it is ok to resend POST data as the page they
584 * are trying to navigate to is the result of a POST.
585 */
586 @Override
587 public void onFormResubmission(WebView view, final Message dontResend,
588 final Message resend) {
589 if (!mInForeground) {
590 dontResend.sendToTarget();
591 return;
592 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500593 if (mDontResend != null) {
594 Log.w(LOGTAG, "onFormResubmission should not be called again "
595 + "while dialog is still up");
596 dontResend.sendToTarget();
597 return;
598 }
599 mDontResend = dontResend;
600 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700601 new AlertDialog.Builder(mActivity).setTitle(
602 R.string.browserFrameFormResubmitLabel).setMessage(
603 R.string.browserFrameFormResubmitMessage)
604 .setPositiveButton(R.string.ok,
605 new DialogInterface.OnClickListener() {
606 public void onClick(DialogInterface dialog,
607 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500608 if (mResend != null) {
609 mResend.sendToTarget();
610 mResend = null;
611 mDontResend = null;
612 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700613 }
614 }).setNegativeButton(R.string.cancel,
615 new DialogInterface.OnClickListener() {
616 public void onClick(DialogInterface dialog,
617 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500618 if (mDontResend != null) {
619 mDontResend.sendToTarget();
620 mResend = null;
621 mDontResend = null;
622 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700623 }
624 }).setOnCancelListener(new OnCancelListener() {
625 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500626 if (mDontResend != null) {
627 mDontResend.sendToTarget();
628 mResend = null;
629 mDontResend = null;
630 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700631 }
632 }).show();
633 }
634
635 /**
636 * Insert the url into the visited history database.
637 * @param url The url to be inserted.
638 * @param isReload True if this url is being reloaded.
639 * FIXME: Not sure what to do when reloading the page.
640 */
641 @Override
642 public void doUpdateVisitedHistory(WebView view, String url,
643 boolean isReload) {
644 if (url.regionMatches(true, 0, "about:", 0, 6)) {
645 return;
646 }
647 // remove "client" before updating it to the history so that it wont
648 // show up in the auto-complete list.
649 int index = url.indexOf("client=ms-");
650 if (index > 0 && url.contains(".google.")) {
651 int end = url.indexOf('&', index);
652 if (end > 0) {
653 url = url.substring(0, index)
654 .concat(url.substring(end + 1));
655 } else {
656 // the url.charAt(index-1) should be either '?' or '&'
657 url = url.substring(0, index-1);
658 }
659 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400660 final ContentResolver cr = mActivity.getContentResolver();
661 final String newUrl = url;
662 new AsyncTask<Void, Void, Void>() {
663 protected Void doInBackground(Void... unused) {
664 Browser.updateVisitedHistory(cr, newUrl, true);
665 return null;
666 }
667 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700668 WebIconDatabase.getInstance().retainIconForPageUrl(url);
669 }
670
671 /**
672 * Displays SSL error(s) dialog to the user.
673 */
674 @Override
675 public void onReceivedSslError(final WebView view,
676 final SslErrorHandler handler, final SslError error) {
677 if (!mInForeground) {
678 handler.cancel();
679 return;
680 }
681 if (BrowserSettings.getInstance().showSecurityWarnings()) {
682 final LayoutInflater factory =
683 LayoutInflater.from(mActivity);
684 final View warningsView =
685 factory.inflate(R.layout.ssl_warnings, null);
686 final LinearLayout placeholder =
687 (LinearLayout)warningsView.findViewById(R.id.placeholder);
688
689 if (error.hasError(SslError.SSL_UNTRUSTED)) {
690 LinearLayout ll = (LinearLayout)factory
691 .inflate(R.layout.ssl_warning, null);
692 ((TextView)ll.findViewById(R.id.warning))
693 .setText(R.string.ssl_untrusted);
694 placeholder.addView(ll);
695 }
696
697 if (error.hasError(SslError.SSL_IDMISMATCH)) {
698 LinearLayout ll = (LinearLayout)factory
699 .inflate(R.layout.ssl_warning, null);
700 ((TextView)ll.findViewById(R.id.warning))
701 .setText(R.string.ssl_mismatch);
702 placeholder.addView(ll);
703 }
704
705 if (error.hasError(SslError.SSL_EXPIRED)) {
706 LinearLayout ll = (LinearLayout)factory
707 .inflate(R.layout.ssl_warning, null);
708 ((TextView)ll.findViewById(R.id.warning))
709 .setText(R.string.ssl_expired);
710 placeholder.addView(ll);
711 }
712
713 if (error.hasError(SslError.SSL_NOTYETVALID)) {
714 LinearLayout ll = (LinearLayout)factory
715 .inflate(R.layout.ssl_warning, null);
716 ((TextView)ll.findViewById(R.id.warning))
717 .setText(R.string.ssl_not_yet_valid);
718 placeholder.addView(ll);
719 }
720
721 new AlertDialog.Builder(mActivity).setTitle(
722 R.string.security_warning).setIcon(
723 android.R.drawable.ic_dialog_alert).setView(
724 warningsView).setPositiveButton(R.string.ssl_continue,
725 new DialogInterface.OnClickListener() {
726 public void onClick(DialogInterface dialog,
727 int whichButton) {
728 handler.proceed();
729 }
730 }).setNeutralButton(R.string.view_certificate,
731 new DialogInterface.OnClickListener() {
732 public void onClick(DialogInterface dialog,
733 int whichButton) {
734 mActivity.showSSLCertificateOnError(view,
735 handler, error);
736 }
737 }).setNegativeButton(R.string.cancel,
738 new DialogInterface.OnClickListener() {
739 public void onClick(DialogInterface dialog,
740 int whichButton) {
741 handler.cancel();
742 mActivity.resetTitleAndRevertLockIcon();
743 }
744 }).setOnCancelListener(
745 new DialogInterface.OnCancelListener() {
746 public void onCancel(DialogInterface dialog) {
747 handler.cancel();
748 mActivity.resetTitleAndRevertLockIcon();
749 }
750 }).show();
751 } else {
752 handler.proceed();
753 }
754 }
755
756 /**
757 * Handles an HTTP authentication request.
758 *
759 * @param handler The authentication handler
760 * @param host The host
761 * @param realm The realm
762 */
763 @Override
764 public void onReceivedHttpAuthRequest(WebView view,
765 final HttpAuthHandler handler, final String host,
766 final String realm) {
767 String username = null;
768 String password = null;
769
770 boolean reuseHttpAuthUsernamePassword = handler
771 .useHttpAuthUsernamePassword();
772
773 if (reuseHttpAuthUsernamePassword && mMainView != null) {
774 String[] credentials = mMainView.getHttpAuthUsernamePassword(
775 host, realm);
776 if (credentials != null && credentials.length == 2) {
777 username = credentials[0];
778 password = credentials[1];
779 }
780 }
781
782 if (username != null && password != null) {
783 handler.proceed(username, password);
784 } else {
785 if (mInForeground) {
786 mActivity.showHttpAuthentication(handler, host, realm,
787 null, null, null, 0);
788 } else {
789 handler.cancel();
790 }
791 }
792 }
793
794 @Override
795 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
796 if (!mInForeground) {
797 return false;
798 }
799 if (mActivity.isMenuDown()) {
800 // only check shortcut key when MENU is held
801 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
802 event);
803 } else {
804 return false;
805 }
806 }
807
808 @Override
809 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400810 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700811 return;
812 }
813 if (event.isDown()) {
814 mActivity.onKeyDown(event.getKeyCode(), event);
815 } else {
816 mActivity.onKeyUp(event.getKeyCode(), event);
817 }
818 }
819 };
820
821 // -------------------------------------------------------------------------
822 // WebChromeClient implementation for the main WebView
823 // -------------------------------------------------------------------------
824
825 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
826 // Helper method to create a new tab or sub window.
827 private void createWindow(final boolean dialog, final Message msg) {
828 WebView.WebViewTransport transport =
829 (WebView.WebViewTransport) msg.obj;
830 if (dialog) {
831 createSubWindow();
832 mActivity.attachSubWindow(Tab.this);
833 transport.setWebView(mSubView);
834 } else {
835 final Tab newTab = mActivity.openTabAndShow(
836 BrowserActivity.EMPTY_URL_DATA, false, null);
837 if (newTab != Tab.this) {
838 Tab.this.addChildTab(newTab);
839 }
840 transport.setWebView(newTab.getWebView());
841 }
842 msg.sendToTarget();
843 }
844
845 @Override
846 public boolean onCreateWindow(WebView view, final boolean dialog,
847 final boolean userGesture, final Message resultMsg) {
848 // only allow new window or sub window for the foreground case
849 if (!mInForeground) {
850 return false;
851 }
852 // Short-circuit if we can't create any more tabs or sub windows.
853 if (dialog && mSubView != null) {
854 new AlertDialog.Builder(mActivity)
855 .setTitle(R.string.too_many_subwindows_dialog_title)
856 .setIcon(android.R.drawable.ic_dialog_alert)
857 .setMessage(R.string.too_many_subwindows_dialog_message)
858 .setPositiveButton(R.string.ok, null)
859 .show();
860 return false;
861 } else if (!mActivity.getTabControl().canCreateNewTab()) {
862 new AlertDialog.Builder(mActivity)
863 .setTitle(R.string.too_many_windows_dialog_title)
864 .setIcon(android.R.drawable.ic_dialog_alert)
865 .setMessage(R.string.too_many_windows_dialog_message)
866 .setPositiveButton(R.string.ok, null)
867 .show();
868 return false;
869 }
870
871 // Short-circuit if this was a user gesture.
872 if (userGesture) {
873 createWindow(dialog, resultMsg);
874 return true;
875 }
876
877 // Allow the popup and create the appropriate window.
878 final AlertDialog.OnClickListener allowListener =
879 new AlertDialog.OnClickListener() {
880 public void onClick(DialogInterface d,
881 int which) {
882 createWindow(dialog, resultMsg);
883 }
884 };
885
886 // Block the popup by returning a null WebView.
887 final AlertDialog.OnClickListener blockListener =
888 new AlertDialog.OnClickListener() {
889 public void onClick(DialogInterface d, int which) {
890 resultMsg.sendToTarget();
891 }
892 };
893
894 // Build a confirmation dialog to display to the user.
895 final AlertDialog d =
896 new AlertDialog.Builder(mActivity)
897 .setTitle(R.string.attention)
898 .setIcon(android.R.drawable.ic_dialog_alert)
899 .setMessage(R.string.popup_window_attempt)
900 .setPositiveButton(R.string.allow, allowListener)
901 .setNegativeButton(R.string.block, blockListener)
902 .setCancelable(false)
903 .create();
904
905 // Show the confirmation dialog.
906 d.show();
907 return true;
908 }
909
910 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500911 public void onRequestFocus(WebView view) {
912 if (!mInForeground) {
913 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
914 Tab.this));
915 }
916 }
917
918 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700919 public void onCloseWindow(WebView window) {
920 if (mParentTab != null) {
921 // JavaScript can only close popup window.
922 if (mInForeground) {
923 mActivity.switchToTab(mActivity.getTabControl()
924 .getTabIndex(mParentTab));
925 }
926 mActivity.closeTab(Tab.this);
927 }
928 }
929
930 @Override
931 public void onProgressChanged(WebView view, int newProgress) {
932 if (newProgress == 100) {
933 // sync cookies and cache promptly here.
934 CookieSyncManager.getInstance().sync();
935 }
936 if (mInForeground) {
937 mActivity.onProgressChanged(view, newProgress);
938 }
939 }
940
941 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500942 public void onReceivedTitle(WebView view, final String title) {
943 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700944 if (mInForeground) {
945 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500946 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700947 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500948 if (pageUrl == null || pageUrl.length()
949 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700950 return;
951 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500952 new AsyncTask<Void, Void, Void>() {
953 protected Void doInBackground(Void... unused) {
954 // See if we can find the current url in our history
955 // database and add the new title to it.
956 String url = pageUrl;
957 if (url.startsWith("http://www.")) {
958 url = url.substring(11);
959 } else if (url.startsWith("http://")) {
960 url = url.substring(4);
961 }
962 Cursor c = null;
963 try {
964 final ContentResolver cr
965 = mActivity.getContentResolver();
966 url = "%" + url;
967 String [] selArgs = new String[] { url };
968 String where = Browser.BookmarkColumns.URL
969 + " LIKE ? AND "
970 + Browser.BookmarkColumns.BOOKMARK + " = 0";
971 c = cr.query(Browser.BOOKMARKS_URI, new String[]
972 { Browser.BookmarkColumns._ID }, where, selArgs,
973 null);
974 if (c.moveToFirst()) {
975 // Current implementation of database only has one
976 // entry per url.
977 ContentValues map = new ContentValues();
978 map.put(Browser.BookmarkColumns.TITLE, title);
979 String[] projection = new String[]
980 { Integer.valueOf(c.getInt(0)).toString() };
981 cr.update(Browser.BOOKMARKS_URI, map, "_id = ?",
982 projection);
983 }
984 } catch (IllegalStateException e) {
985 Log.e(LOGTAG, "Tab onReceived title", e);
986 } catch (SQLiteException ex) {
987 Log.e(LOGTAG,
988 "onReceivedTitle() caught SQLiteException: ",
989 ex);
990 } finally {
991 if (c != null) c.close();
992 }
993 return null;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700994 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500995 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700996 }
997
998 @Override
999 public void onReceivedIcon(WebView view, Bitmap icon) {
1000 if (icon != null) {
1001 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
1002 .getContentResolver(), view.getOriginalUrl(), view
1003 .getUrl(), icon);
1004 }
1005 if (mInForeground) {
1006 mActivity.setFavicon(icon);
1007 }
1008 }
1009
1010 @Override
1011 public void onReceivedTouchIconUrl(WebView view, String url,
1012 boolean precomposed) {
1013 final ContentResolver cr = mActivity.getContentResolver();
1014 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
1015 view.getOriginalUrl(), view.getUrl(), true);
1016 if (c != null) {
1017 if (c.getCount() > 0) {
1018 // Let precomposed icons take precedence over non-composed
1019 // icons.
1020 if (precomposed && mTouchIconLoader != null) {
1021 mTouchIconLoader.cancel(false);
1022 mTouchIconLoader = null;
1023 }
1024 // Have only one async task at a time.
1025 if (mTouchIconLoader == null) {
1026 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
1027 c, view);
1028 mTouchIconLoader.execute(url);
Patrick Scott8e9fe322010-03-04 14:29:31 -05001029 } else {
1030 c.close();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 }
1032 } else {
1033 c.close();
1034 }
1035 }
1036 }
1037
1038 @Override
1039 public void onShowCustomView(View view,
1040 WebChromeClient.CustomViewCallback callback) {
1041 if (mInForeground) mActivity.onShowCustomView(view, callback);
1042 }
1043
1044 @Override
1045 public void onHideCustomView() {
1046 if (mInForeground) mActivity.onHideCustomView();
1047 }
1048
1049 /**
1050 * The origin has exceeded its database quota.
1051 * @param url the URL that exceeded the quota
1052 * @param databaseIdentifier the identifier of the database on which the
1053 * transaction that caused the quota overflow was run
1054 * @param currentQuota the current quota for the origin.
1055 * @param estimatedSize the estimated size of the database.
1056 * @param totalUsedQuota is the sum of all origins' quota.
1057 * @param quotaUpdater The callback to run when a decision to allow or
1058 * deny quota has been made. Don't forget to call this!
1059 */
1060 @Override
1061 public void onExceededDatabaseQuota(String url,
1062 String databaseIdentifier, long currentQuota, long estimatedSize,
1063 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1064 BrowserSettings.getInstance().getWebStorageSizeManager()
1065 .onExceededDatabaseQuota(url, databaseIdentifier,
1066 currentQuota, estimatedSize, totalUsedQuota,
1067 quotaUpdater);
1068 }
1069
1070 /**
1071 * The Application Cache has exceeded its max size.
1072 * @param spaceNeeded is the amount of disk space that would be needed
1073 * in order for the last appcache operation to succeed.
1074 * @param totalUsedQuota is the sum of all origins' quota.
1075 * @param quotaUpdater A callback to inform the WebCore thread that a
1076 * new app cache size is available. This callback must always
1077 * be executed at some point to ensure that the sleeping
1078 * WebCore thread is woken up.
1079 */
1080 @Override
1081 public void onReachedMaxAppCacheSize(long spaceNeeded,
1082 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1083 BrowserSettings.getInstance().getWebStorageSizeManager()
1084 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1085 quotaUpdater);
1086 }
1087
1088 /**
1089 * Instructs the browser to show a prompt to ask the user to set the
1090 * Geolocation permission state for the specified origin.
1091 * @param origin The origin for which Geolocation permissions are
1092 * requested.
1093 * @param callback The callback to call once the user has set the
1094 * Geolocation permission state.
1095 */
1096 @Override
1097 public void onGeolocationPermissionsShowPrompt(String origin,
1098 GeolocationPermissions.Callback callback) {
1099 if (mInForeground) {
1100 mGeolocationPermissionsPrompt.show(origin, callback);
1101 }
1102 }
1103
1104 /**
1105 * Instructs the browser to hide the Geolocation permissions prompt.
1106 */
1107 @Override
1108 public void onGeolocationPermissionsHidePrompt() {
1109 if (mInForeground) {
1110 mGeolocationPermissionsPrompt.hide();
1111 }
1112 }
1113
Ben Murdoch65acc352009-11-19 18:16:04 +00001114 /* Adds a JavaScript error message to the system log and if the JS
1115 * console is enabled in the about:debug options, to that console
1116 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001117 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001118 */
1119 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001120 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001121 if (mInForeground) {
1122 // call getErrorConsole(true) so it will create one if needed
1123 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001124 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001125 if (mActivity.shouldShowErrorConsole()
1126 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1127 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1128 }
1129 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001130
1131 String message = "Console: " + consoleMessage.message() + " "
1132 + consoleMessage.sourceId() + ":"
1133 + consoleMessage.lineNumber();
1134
1135 switch (consoleMessage.messageLevel()) {
1136 case TIP:
1137 Log.v(CONSOLE_LOGTAG, message);
1138 break;
1139 case LOG:
1140 Log.i(CONSOLE_LOGTAG, message);
1141 break;
1142 case WARNING:
1143 Log.w(CONSOLE_LOGTAG, message);
1144 break;
1145 case ERROR:
1146 Log.e(CONSOLE_LOGTAG, message);
1147 break;
1148 case DEBUG:
1149 Log.d(CONSOLE_LOGTAG, message);
1150 break;
1151 }
1152
1153 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001154 }
1155
1156 /**
1157 * Ask the browser for an icon to represent a <video> element.
1158 * This icon will be used if the Web page did not specify a poster attribute.
1159 * @return Bitmap The icon or null if no such icon is available.
1160 */
1161 @Override
1162 public Bitmap getDefaultVideoPoster() {
1163 if (mInForeground) {
1164 return mActivity.getDefaultVideoPoster();
1165 }
1166 return null;
1167 }
1168
1169 /**
1170 * Ask the host application for a custom progress view to show while
1171 * a <video> is loading.
1172 * @return View The progress view.
1173 */
1174 @Override
1175 public View getVideoLoadingProgressView() {
1176 if (mInForeground) {
1177 return mActivity.getVideoLoadingProgressView();
1178 }
1179 return null;
1180 }
1181
1182 @Override
1183 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
1184 if (mInForeground) {
1185 mActivity.openFileChooser(uploadMsg);
1186 } else {
1187 uploadMsg.onReceiveValue(null);
1188 }
1189 }
1190
1191 /**
1192 * Deliver a list of already-visited URLs
1193 */
1194 @Override
1195 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1196 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
1197 public String[] doInBackground(Void... unused) {
1198 return Browser.getVisitedHistory(mActivity
1199 .getContentResolver());
1200 }
1201 public void onPostExecute(String[] result) {
1202 callback.onReceiveValue(result);
1203 };
1204 };
1205 task.execute();
1206 };
1207 };
1208
1209 // -------------------------------------------------------------------------
1210 // WebViewClient implementation for the sub window
1211 // -------------------------------------------------------------------------
1212
1213 // Subclass of WebViewClient used in subwindows to notify the main
1214 // WebViewClient of certain WebView activities.
1215 private static class SubWindowClient extends WebViewClient {
1216 // The main WebViewClient.
1217 private final WebViewClient mClient;
1218
1219 SubWindowClient(WebViewClient client) {
1220 mClient = client;
1221 }
1222 @Override
1223 public void doUpdateVisitedHistory(WebView view, String url,
1224 boolean isReload) {
1225 mClient.doUpdateVisitedHistory(view, url, isReload);
1226 }
1227 @Override
1228 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1229 return mClient.shouldOverrideUrlLoading(view, url);
1230 }
1231 @Override
1232 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1233 SslError error) {
1234 mClient.onReceivedSslError(view, handler, error);
1235 }
1236 @Override
1237 public void onReceivedHttpAuthRequest(WebView view,
1238 HttpAuthHandler handler, String host, String realm) {
1239 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1240 }
1241 @Override
1242 public void onFormResubmission(WebView view, Message dontResend,
1243 Message resend) {
1244 mClient.onFormResubmission(view, dontResend, resend);
1245 }
1246 @Override
1247 public void onReceivedError(WebView view, int errorCode,
1248 String description, String failingUrl) {
1249 mClient.onReceivedError(view, errorCode, description, failingUrl);
1250 }
1251 @Override
1252 public boolean shouldOverrideKeyEvent(WebView view,
1253 android.view.KeyEvent event) {
1254 return mClient.shouldOverrideKeyEvent(view, event);
1255 }
1256 @Override
1257 public void onUnhandledKeyEvent(WebView view,
1258 android.view.KeyEvent event) {
1259 mClient.onUnhandledKeyEvent(view, event);
1260 }
1261 }
1262
1263 // -------------------------------------------------------------------------
1264 // WebChromeClient implementation for the sub window
1265 // -------------------------------------------------------------------------
1266
1267 private class SubWindowChromeClient extends WebChromeClient {
1268 // The main WebChromeClient.
1269 private final WebChromeClient mClient;
1270
1271 SubWindowChromeClient(WebChromeClient client) {
1272 mClient = client;
1273 }
1274 @Override
1275 public void onProgressChanged(WebView view, int newProgress) {
1276 mClient.onProgressChanged(view, newProgress);
1277 }
1278 @Override
1279 public boolean onCreateWindow(WebView view, boolean dialog,
1280 boolean userGesture, android.os.Message resultMsg) {
1281 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1282 }
1283 @Override
1284 public void onCloseWindow(WebView window) {
1285 if (window != mSubView) {
1286 Log.e(LOGTAG, "Can't close the window");
1287 }
1288 mActivity.dismissSubWindow(Tab.this);
1289 }
1290 }
1291
1292 // -------------------------------------------------------------------------
1293
1294 // Construct a new tab
1295 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1296 String url) {
1297 mActivity = activity;
1298 mCloseOnExit = closeOnExit;
1299 mAppId = appId;
1300 mOriginalUrl = url;
1301 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1302 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1303 mInLoad = false;
1304 mInForeground = false;
1305
1306 mInflateService = LayoutInflater.from(activity);
1307
1308 // The tab consists of a container view, which contains the main
1309 // WebView, as well as any other UI elements associated with the tab.
1310 mContainer = mInflateService.inflate(R.layout.tab, null);
1311
1312 mGeolocationPermissionsPrompt =
1313 (GeolocationPermissionsPrompt) mContainer.findViewById(
1314 R.id.geolocation_permissions_prompt);
1315
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001316 mDownloadListener = new DownloadListener() {
1317 public void onDownloadStart(String url, String userAgent,
1318 String contentDisposition, String mimetype,
1319 long contentLength) {
1320 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1321 mimetype, contentLength);
1322 if (mMainView.copyBackForwardList().getSize() == 0) {
1323 // This Tab was opened for the sole purpose of downloading a
1324 // file. Remove it.
1325 if (mActivity.getTabControl().getCurrentWebView()
1326 == mMainView) {
1327 // In this case, the Tab is still on top.
1328 mActivity.goBackOnePageOrQuit();
1329 } else {
1330 // In this case, it is not.
1331 mActivity.closeTab(Tab.this);
1332 }
1333 }
1334 }
1335 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001336 mWebBackForwardListClient = new WebBackForwardListClient() {
1337 @Override
1338 public void onNewHistoryItem(WebHistoryItem item) {
1339 if (isInVoiceSearchMode()) {
1340 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1341 }
1342 }
1343 @Override
1344 public void onIndexChanged(WebHistoryItem item, int index) {
1345 Object data = item.getCustomData();
1346 if (data != null && data instanceof Intent) {
1347 activateVoiceSearchMode((Intent) data);
1348 }
1349 }
1350 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001351
Grace Kloba22ac16e2009-10-07 18:00:23 -07001352 setWebView(w);
1353 }
1354
1355 /**
1356 * Sets the WebView for this tab, correctly removing the old WebView from
1357 * the container view.
1358 */
1359 void setWebView(WebView w) {
1360 if (mMainView == w) {
1361 return;
1362 }
1363 // If the WebView is changing, the page will be reloaded, so any ongoing
1364 // Geolocation permission requests are void.
1365 mGeolocationPermissionsPrompt.hide();
1366
1367 // Just remove the old one.
1368 FrameLayout wrapper =
1369 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1370 wrapper.removeView(mMainView);
1371
1372 // set the new one
1373 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001374 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001375 if (mMainView != null) {
1376 mMainView.setWebViewClient(mWebViewClient);
1377 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001378 // Attach DownloadManager so that downloads can start in an active
1379 // or a non-active window. This can happen when going to a site that
1380 // does a redirect after a period of time. The user could have
1381 // switched to another tab while waiting for the download to start.
1382 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001383 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001384 }
1385 }
1386
1387 /**
1388 * Destroy the tab's main WebView and subWindow if any
1389 */
1390 void destroy() {
1391 if (mMainView != null) {
1392 dismissSubWindow();
1393 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1394 // save the WebView to call destroy() after detach it from the tab
1395 WebView webView = mMainView;
1396 setWebView(null);
1397 webView.destroy();
1398 }
1399 }
1400
1401 /**
1402 * Remove the tab from the parent
1403 */
1404 void removeFromTree() {
1405 // detach the children
1406 if (mChildTabs != null) {
1407 for(Tab t : mChildTabs) {
1408 t.setParentTab(null);
1409 }
1410 }
1411 // remove itself from the parent list
1412 if (mParentTab != null) {
1413 mParentTab.mChildTabs.remove(this);
1414 }
1415 }
1416
1417 /**
1418 * Create a new subwindow unless a subwindow already exists.
1419 * @return True if a new subwindow was created. False if one already exists.
1420 */
1421 boolean createSubWindow() {
1422 if (mSubView == null) {
1423 mSubViewContainer = mInflateService.inflate(
1424 R.layout.browser_subwindow, null);
1425 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001426 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001427 // use trackball directly
1428 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001429 // Enable the built-in zoom
1430 mSubView.getSettings().setBuiltInZoomControls(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001431 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1432 mSubView.setWebChromeClient(new SubWindowChromeClient(
1433 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001434 // Set a different DownloadListener for the mSubView, since it will
1435 // just need to dismiss the mSubView, rather than close the Tab
1436 mSubView.setDownloadListener(new DownloadListener() {
1437 public void onDownloadStart(String url, String userAgent,
1438 String contentDisposition, String mimetype,
1439 long contentLength) {
1440 mActivity.onDownloadStart(url, userAgent,
1441 contentDisposition, mimetype, contentLength);
1442 if (mSubView.copyBackForwardList().getSize() == 0) {
1443 // This subwindow was opened for the sole purpose of
1444 // downloading a file. Remove it.
1445 dismissSubWindow();
1446 }
1447 }
1448 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001449 mSubView.setOnCreateContextMenuListener(mActivity);
1450 final BrowserSettings s = BrowserSettings.getInstance();
1451 s.addObserver(mSubView.getSettings()).update(s, null);
1452 final ImageButton cancel = (ImageButton) mSubViewContainer
1453 .findViewById(R.id.subwindow_close);
1454 cancel.setOnClickListener(new OnClickListener() {
1455 public void onClick(View v) {
1456 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1457 }
1458 });
1459 return true;
1460 }
1461 return false;
1462 }
1463
1464 /**
1465 * Dismiss the subWindow for the tab.
1466 */
1467 void dismissSubWindow() {
1468 if (mSubView != null) {
1469 BrowserSettings.getInstance().deleteObserver(
1470 mSubView.getSettings());
1471 mSubView.destroy();
1472 mSubView = null;
1473 mSubViewContainer = null;
1474 }
1475 }
1476
1477 /**
1478 * Attach the sub window to the content view.
1479 */
1480 void attachSubWindow(ViewGroup content) {
1481 if (mSubView != null) {
1482 content.addView(mSubViewContainer,
1483 BrowserActivity.COVER_SCREEN_PARAMS);
1484 }
1485 }
1486
1487 /**
1488 * Remove the sub window from the content view.
1489 */
1490 void removeSubWindow(ViewGroup content) {
1491 if (mSubView != null) {
1492 content.removeView(mSubViewContainer);
1493 }
1494 }
1495
1496 /**
1497 * This method attaches both the WebView and any sub window to the
1498 * given content view.
1499 */
1500 void attachTabToContentView(ViewGroup content) {
1501 if (mMainView == null) {
1502 return;
1503 }
1504
1505 // Attach the WebView to the container and then attach the
1506 // container to the content view.
1507 FrameLayout wrapper =
1508 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1509 wrapper.addView(mMainView);
1510 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1511 attachSubWindow(content);
1512 }
1513
1514 /**
1515 * Remove the WebView and any sub window from the given content view.
1516 */
1517 void removeTabFromContentView(ViewGroup content) {
1518 if (mMainView == null) {
1519 return;
1520 }
1521
1522 // Remove the container from the content and then remove the
1523 // WebView from the container. This will trigger a focus change
1524 // needed by WebView.
1525 FrameLayout wrapper =
1526 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1527 wrapper.removeView(mMainView);
1528 content.removeView(mContainer);
1529 removeSubWindow(content);
1530 }
1531
1532 /**
1533 * Set the parent tab of this tab.
1534 */
1535 void setParentTab(Tab parent) {
1536 mParentTab = parent;
1537 // This tab may have been freed due to low memory. If that is the case,
1538 // the parent tab index is already saved. If we are changing that index
1539 // (most likely due to removing the parent tab) we must update the
1540 // parent tab index in the saved Bundle.
1541 if (mSavedState != null) {
1542 if (parent == null) {
1543 mSavedState.remove(PARENTTAB);
1544 } else {
1545 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1546 .getTabIndex(parent));
1547 }
1548 }
1549 }
1550
1551 /**
1552 * When a Tab is created through the content of another Tab, then we
1553 * associate the Tabs.
1554 * @param child the Tab that was created from this Tab
1555 */
1556 void addChildTab(Tab child) {
1557 if (mChildTabs == null) {
1558 mChildTabs = new Vector<Tab>();
1559 }
1560 mChildTabs.add(child);
1561 child.setParentTab(this);
1562 }
1563
1564 Vector<Tab> getChildTabs() {
1565 return mChildTabs;
1566 }
1567
1568 void resume() {
1569 if (mMainView != null) {
1570 mMainView.onResume();
1571 if (mSubView != null) {
1572 mSubView.onResume();
1573 }
1574 }
1575 }
1576
1577 void pause() {
1578 if (mMainView != null) {
1579 mMainView.onPause();
1580 if (mSubView != null) {
1581 mSubView.onPause();
1582 }
1583 }
1584 }
1585
1586 void putInForeground() {
1587 mInForeground = true;
1588 resume();
1589 mMainView.setOnCreateContextMenuListener(mActivity);
1590 if (mSubView != null) {
1591 mSubView.setOnCreateContextMenuListener(mActivity);
1592 }
1593 // Show the pending error dialog if the queue is not empty
1594 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1595 showError(mQueuedErrors.getFirst());
1596 }
1597 }
1598
1599 void putInBackground() {
1600 mInForeground = false;
1601 pause();
1602 mMainView.setOnCreateContextMenuListener(null);
1603 if (mSubView != null) {
1604 mSubView.setOnCreateContextMenuListener(null);
1605 }
1606 }
1607
1608 /**
1609 * Return the top window of this tab; either the subwindow if it is not
1610 * null or the main window.
1611 * @return The top window of this tab.
1612 */
1613 WebView getTopWindow() {
1614 if (mSubView != null) {
1615 return mSubView;
1616 }
1617 return mMainView;
1618 }
1619
1620 /**
1621 * Return the main window of this tab. Note: if a tab is freed in the
1622 * background, this can return null. It is only guaranteed to be
1623 * non-null for the current tab.
1624 * @return The main WebView of this tab.
1625 */
1626 WebView getWebView() {
1627 return mMainView;
1628 }
1629
1630 /**
1631 * Return the subwindow of this tab or null if there is no subwindow.
1632 * @return The subwindow of this tab or null.
1633 */
1634 WebView getSubWebView() {
1635 return mSubView;
1636 }
1637
1638 /**
1639 * @return The geolocation permissions prompt for this tab.
1640 */
1641 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1642 return mGeolocationPermissionsPrompt;
1643 }
1644
1645 /**
1646 * @return The application id string
1647 */
1648 String getAppId() {
1649 return mAppId;
1650 }
1651
1652 /**
1653 * Set the application id string
1654 * @param id
1655 */
1656 void setAppId(String id) {
1657 mAppId = id;
1658 }
1659
1660 /**
1661 * @return The original url associated with this Tab
1662 */
1663 String getOriginalUrl() {
1664 return mOriginalUrl;
1665 }
1666
1667 /**
1668 * Set the original url associated with this tab
1669 */
1670 void setOriginalUrl(String url) {
1671 mOriginalUrl = url;
1672 }
1673
1674 /**
1675 * Get the url of this tab. Valid after calling populatePickerData, but
1676 * before calling wipePickerData, or if the webview has been destroyed.
1677 * @return The WebView's url or null.
1678 */
1679 String getUrl() {
1680 if (mPickerData != null) {
1681 return mPickerData.mUrl;
1682 }
1683 return null;
1684 }
1685
1686 /**
1687 * Get the title of this tab. Valid after calling populatePickerData, but
1688 * before calling wipePickerData, or if the webview has been destroyed. If
1689 * the url has no title, use the url instead.
1690 * @return The WebView's title (or url) or null.
1691 */
1692 String getTitle() {
1693 if (mPickerData != null) {
1694 return mPickerData.mTitle;
1695 }
1696 return null;
1697 }
1698
1699 /**
1700 * Get the favicon of this tab. Valid after calling populatePickerData, but
1701 * before calling wipePickerData, or if the webview has been destroyed.
1702 * @return The WebView's favicon or null.
1703 */
1704 Bitmap getFavicon() {
1705 if (mPickerData != null) {
1706 return mPickerData.mFavicon;
1707 }
1708 return null;
1709 }
1710
1711 /**
1712 * Return the tab's error console. Creates the console if createIfNEcessary
1713 * is true and we haven't already created the console.
1714 * @param createIfNecessary Flag to indicate if the console should be
1715 * created if it has not been already.
1716 * @return The tab's error console, or null if one has not been created and
1717 * createIfNecessary is false.
1718 */
1719 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1720 if (createIfNecessary && mErrorConsole == null) {
1721 mErrorConsole = new ErrorConsoleView(mActivity);
1722 mErrorConsole.setWebView(mMainView);
1723 }
1724 return mErrorConsole;
1725 }
1726
1727 /**
1728 * If this Tab was created through another Tab, then this method returns
1729 * that Tab.
1730 * @return the Tab parent or null
1731 */
1732 public Tab getParentTab() {
1733 return mParentTab;
1734 }
1735
1736 /**
1737 * Return whether this tab should be closed when it is backing out of the
1738 * first page.
1739 * @return TRUE if this tab should be closed when exit.
1740 */
1741 boolean closeOnExit() {
1742 return mCloseOnExit;
1743 }
1744
1745 /**
1746 * Saves the current lock-icon state before resetting the lock icon. If we
1747 * have an error, we may need to roll back to the previous state.
1748 */
1749 void resetLockIcon(String url) {
1750 mPrevLockIconType = mLockIconType;
1751 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1752 if (URLUtil.isHttpsUrl(url)) {
1753 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1754 }
1755 }
1756
1757 /**
1758 * Reverts the lock-icon state to the last saved state, for example, if we
1759 * had an error, and need to cancel the load.
1760 */
1761 void revertLockIcon() {
1762 mLockIconType = mPrevLockIconType;
1763 }
1764
1765 /**
1766 * @return The tab's lock icon type.
1767 */
1768 int getLockIconType() {
1769 return mLockIconType;
1770 }
1771
1772 /**
1773 * @return TRUE if onPageStarted is called while onPageFinished is not
1774 * called yet.
1775 */
1776 boolean inLoad() {
1777 return mInLoad;
1778 }
1779
1780 // force mInLoad to be false. This should only be called before closing the
1781 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1782 void clearInLoad() {
1783 mInLoad = false;
1784 }
1785
1786 void populatePickerData() {
1787 if (mMainView == null) {
1788 populatePickerDataFromSavedState();
1789 return;
1790 }
1791
1792 // FIXME: The only place we cared about subwindow was for
1793 // bookmarking (i.e. not when saving state). Was this deliberate?
1794 final WebBackForwardList list = mMainView.copyBackForwardList();
1795 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1796 populatePickerData(item);
1797 }
1798
1799 // Populate the picker data using the given history item and the current top
1800 // WebView.
1801 private void populatePickerData(WebHistoryItem item) {
1802 mPickerData = new PickerData();
1803 if (item != null) {
1804 mPickerData.mUrl = item.getUrl();
1805 mPickerData.mTitle = item.getTitle();
1806 mPickerData.mFavicon = item.getFavicon();
1807 if (mPickerData.mTitle == null) {
1808 mPickerData.mTitle = mPickerData.mUrl;
1809 }
1810 }
1811 }
1812
1813 // Create the PickerData and populate it using the saved state of the tab.
1814 void populatePickerDataFromSavedState() {
1815 if (mSavedState == null) {
1816 return;
1817 }
1818 mPickerData = new PickerData();
1819 mPickerData.mUrl = mSavedState.getString(CURRURL);
1820 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1821 }
1822
1823 void clearPickerData() {
1824 mPickerData = null;
1825 }
1826
1827 /**
1828 * Get the saved state bundle.
1829 * @return
1830 */
1831 Bundle getSavedState() {
1832 return mSavedState;
1833 }
1834
1835 /**
1836 * Set the saved state.
1837 */
1838 void setSavedState(Bundle state) {
1839 mSavedState = state;
1840 }
1841
1842 /**
1843 * @return TRUE if succeed in saving the state.
1844 */
1845 boolean saveState() {
1846 // If the WebView is null it means we ran low on memory and we already
1847 // stored the saved state in mSavedState.
1848 if (mMainView == null) {
1849 return mSavedState != null;
1850 }
1851
1852 mSavedState = new Bundle();
1853 final WebBackForwardList list = mMainView.saveState(mSavedState);
1854 if (list != null) {
1855 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1856 mMainView.hashCode() + "_pic.save");
1857 if (mMainView.savePicture(mSavedState, f)) {
1858 mSavedState.putString(CURRPICTURE, f.getPath());
Mike Reedd5eee692010-03-05 10:13:34 -05001859 } else {
1860 // if savePicture returned false, we can't trust the contents,
1861 // and it may be large, so we delete it right away
1862 f.delete();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001863 }
1864 }
1865
1866 // Store some extra info for displaying the tab in the picker.
1867 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1868 populatePickerData(item);
1869
1870 if (mPickerData.mUrl != null) {
1871 mSavedState.putString(CURRURL, mPickerData.mUrl);
1872 }
1873 if (mPickerData.mTitle != null) {
1874 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1875 }
1876 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1877 if (mAppId != null) {
1878 mSavedState.putString(APPID, mAppId);
1879 }
1880 if (mOriginalUrl != null) {
1881 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1882 }
1883 // Remember the parent tab so the relationship can be restored.
1884 if (mParentTab != null) {
1885 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1886 mParentTab));
1887 }
1888 return true;
1889 }
1890
1891 /*
1892 * Restore the state of the tab.
1893 */
1894 boolean restoreState(Bundle b) {
1895 if (b == null) {
1896 return false;
1897 }
1898 // Restore the internal state even if the WebView fails to restore.
1899 // This will maintain the app id, original url and close-on-exit values.
1900 mSavedState = null;
1901 mPickerData = null;
1902 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1903 mAppId = b.getString(APPID);
1904 mOriginalUrl = b.getString(ORIGINALURL);
1905
1906 final WebBackForwardList list = mMainView.restoreState(b);
1907 if (list == null) {
1908 return false;
1909 }
1910 if (b.containsKey(CURRPICTURE)) {
1911 final File f = new File(b.getString(CURRPICTURE));
1912 mMainView.restorePicture(b, f);
1913 f.delete();
1914 }
1915 return true;
1916 }
1917}