blob: 01424e2834df091c314f8ae8dc0f8b4214e7cf8d [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;
Grace Kloba50c241e2010-04-20 11:07:50 -070051import android.view.ViewStub;
Grace Kloba22ac16e2009-10-07 18:00:23 -070052import android.view.View.OnClickListener;
Ben Murdochc42addf2010-01-28 15:19:59 +000053import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070054import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050055import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070056import android.webkit.GeolocationPermissions;
57import android.webkit.HttpAuthHandler;
58import android.webkit.SslErrorHandler;
59import android.webkit.URLUtil;
60import android.webkit.ValueCallback;
61import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050062import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070063import android.webkit.WebChromeClient;
64import android.webkit.WebHistoryItem;
65import android.webkit.WebIconDatabase;
66import android.webkit.WebStorage;
67import android.webkit.WebView;
68import android.webkit.WebViewClient;
69import android.widget.FrameLayout;
70import android.widget.ImageButton;
71import android.widget.LinearLayout;
72import android.widget.TextView;
73
Leon Scroggins1fe13a52010-02-09 15:31:26 -050074import com.android.common.speech.LoggingEvents;
75
Grace Kloba22ac16e2009-10-07 18:00:23 -070076/**
77 * Class for maintaining Tabs with a main WebView and a subwindow.
78 */
79class Tab {
80 // Log Tag
81 private static final String LOGTAG = "Tab";
Ben Murdochc42addf2010-01-28 15:19:59 +000082 // Special case the logtag for messages for the Console to make it easier to
83 // filter them and match the logtag used for these messages in older versions
84 // of the browser.
85 private static final String CONSOLE_LOGTAG = "browser";
86
Grace Kloba22ac16e2009-10-07 18:00:23 -070087 // The Geolocation permissions prompt
88 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
89 // Main WebView wrapper
90 private View mContainer;
91 // Main WebView
92 private WebView mMainView;
93 // Subwindow container
94 private View mSubViewContainer;
95 // Subwindow WebView
96 private WebView mSubView;
97 // Saved bundle for when we are running low on memory. It contains the
98 // information needed to restore the WebView if the user goes back to the
99 // tab.
100 private Bundle mSavedState;
101 // Data used when displaying the tab in the picker.
102 private PickerData mPickerData;
103 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
104 // created by the UI
105 private Tab mParentTab;
106 // Tab that constructed by this Tab. This is used when this Tab is
107 // destroyed, it clears all mParentTab values in the children.
108 private Vector<Tab> mChildTabs;
109 // If true, the tab will be removed when back out of the first page.
110 private boolean mCloseOnExit;
111 // If true, the tab is in the foreground of the current activity.
112 private boolean mInForeground;
113 // If true, the tab is in loading state.
114 private boolean mInLoad;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000115 // The time the load started, used to find load page time
116 private long mLoadStartTime;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700117 // Application identifier used to find tabs that another application wants
118 // to reuse.
119 private String mAppId;
120 // Keep the original url around to avoid killing the old WebView if the url
121 // has not changed.
122 private String mOriginalUrl;
123 // Error console for the tab
124 private ErrorConsoleView mErrorConsole;
125 // the lock icon type and previous lock icon type for the tab
126 private int mLockIconType;
127 private int mPrevLockIconType;
128 // Inflation service for making subwindows.
129 private final LayoutInflater mInflateService;
130 // The BrowserActivity which owners the Tab
131 private final BrowserActivity mActivity;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -0500132 // The listener that gets invoked when a download is started from the
133 // mMainView
134 private final DownloadListener mDownloadListener;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500135 // Listener used to know when we move forward or back in the history list.
136 private final WebBackForwardListClient mWebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700137
138 // AsyncTask for downloading touch icons
139 DownloadTouchIcon mTouchIconLoader;
140
141 // Extra saved information for displaying the tab in the picker.
142 private static class PickerData {
143 String mUrl;
144 String mTitle;
145 Bitmap mFavicon;
146 }
147
148 // Used for saving and restoring each Tab
149 static final String WEBVIEW = "webview";
150 static final String NUMTABS = "numTabs";
151 static final String CURRTAB = "currentTab";
152 static final String CURRURL = "currentUrl";
153 static final String CURRTITLE = "currentTitle";
154 static final String CURRPICTURE = "currentPicture";
155 static final String CLOSEONEXIT = "closeonexit";
156 static final String PARENTTAB = "parentTab";
157 static final String APPID = "appid";
158 static final String ORIGINALURL = "originalUrl";
159
160 // -------------------------------------------------------------------------
161
Leon Scroggins58d56c62010-01-28 15:12:40 -0500162 /**
163 * Private information regarding the latest voice search. If the Tab is not
164 * in voice search mode, this will be null.
165 */
166 private VoiceSearchData mVoiceSearchData;
167 /**
168 * Return whether the tab is in voice search mode.
169 */
170 public boolean isInVoiceSearchMode() {
171 return mVoiceSearchData != null;
172 }
173 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500174 * Return true if the voice search Intent came with a String identifying
175 * that Google provided the Intent.
176 */
177 public boolean voiceSearchSourceIsGoogle() {
178 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
179 }
180 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500181 * Get the title to display for the current voice search page. If the Tab
182 * is not in voice search mode, return null.
183 */
184 public String getVoiceDisplayTitle() {
185 if (mVoiceSearchData == null) return null;
186 return mVoiceSearchData.mLastVoiceSearchTitle;
187 }
188 /**
189 * Get the latest array of voice search results, to be passed to the
190 * BrowserProvider. If the Tab is not in voice search mode, return null.
191 */
192 public ArrayList<String> getVoiceSearchResults() {
193 if (mVoiceSearchData == null) return null;
194 return mVoiceSearchData.mVoiceSearchResults;
195 }
196 /**
197 * Activate voice search mode.
198 * @param intent Intent which has the results to use, or an index into the
199 * results when reusing the old results.
200 */
201 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500202 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500203 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500204 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500205 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500206 ArrayList<String> urls = intent.getStringArrayListExtra(
207 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
208 ArrayList<String> htmls = intent.getStringArrayListExtra(
209 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
210 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
211 RecognizerResultsIntent
212 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500213 // This tab is now entering voice search mode for the first time, or
214 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500215 int size = results.size();
216 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500217 throw new AssertionError("improper extras passed in Intent");
218 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500219 if (htmls == null || htmls.size() != size || baseUrls == null ||
220 (baseUrls.size() != size && baseUrls.size() != 1)) {
221 // If either of these arrays are empty/incorrectly sized, ignore
222 // them.
223 htmls = null;
224 baseUrls = null;
225 }
226 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
227 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500228 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
229 RecognizerResultsIntent
230 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500231 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
232 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400233 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500234 }
235 String extraData = intent.getStringExtra(
236 SearchManager.EXTRA_DATA_KEY);
237 if (extraData != null) {
238 index = Integer.parseInt(extraData);
239 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
240 throw new AssertionError("index must be less than "
241 + "size of mVoiceSearchResults");
242 }
243 if (mVoiceSearchData.mSourceIsGoogle) {
244 Intent logIntent = new Intent(
245 LoggingEvents.ACTION_LOG_EVENT);
246 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
247 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
248 logIntent.putExtra(
249 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
250 index);
251 mActivity.sendBroadcast(logIntent);
252 }
253 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400254 // Copy the Intent, so that each history item will have its own
255 // Intent, with different (or none) extra data.
256 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
257 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
258 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500259 }
260 }
261 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500262 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500263 if (mInForeground) {
264 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
265 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500266 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
267 // When index was found it was already ensured that it was valid
268 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
269 if (uriString != null) {
270 Uri dataUri = Uri.parse(uriString);
271 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
272 dataUri.getScheme())) {
273 // If there is only one base URL, use it. If there are
274 // more, there will be one for each index, so use the base
275 // URL corresponding to the index.
276 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
277 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
278 index : 0);
279 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
280 mMainView.loadDataWithBaseURL(baseUrl,
281 uriString.substring(RecognizerResultsIntent
282 .URI_SCHEME_INLINE.length() + 1), "text/html",
283 "utf-8", baseUrl);
284 return;
285 }
286 }
287 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500288 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500289 = mVoiceSearchData.mVoiceSearchUrls.get(index);
290 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
291 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
292 mVoiceSearchData.mLastVoiceSearchTitle);
293 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500294 Map<String, String> headers = null;
295 if (mVoiceSearchData.mHeaders != null) {
296 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
297 : index;
298 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
299 if (bundle != null && !bundle.isEmpty()) {
300 Iterator<String> iter = bundle.keySet().iterator();
301 headers = new HashMap<String, String>();
302 while (iter.hasNext()) {
303 String key = iter.next();
304 headers.put(key, bundle.getString(key));
305 }
306 }
307 }
308 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500309 }
310 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500311 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500312 ArrayList<String> urls, ArrayList<String> htmls,
313 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500314 mVoiceSearchResults = results;
315 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500316 mVoiceSearchHtmls = htmls;
317 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500318 }
319 /*
320 * ArrayList of suggestions to be displayed when opening the
321 * SearchManager
322 */
323 public ArrayList<String> mVoiceSearchResults;
324 /*
325 * ArrayList of urls, associated with the suggestions in
326 * mVoiceSearchResults.
327 */
328 public ArrayList<String> mVoiceSearchUrls;
329 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500330 * ArrayList holding content to load for each item in
331 * mVoiceSearchResults.
332 */
333 public ArrayList<String> mVoiceSearchHtmls;
334 /*
335 * ArrayList holding base urls for the items in mVoiceSearchResults.
336 * If non null, this will either have the same size as
337 * mVoiceSearchResults or have a size of 1, in which case all will use
338 * the same base url
339 */
340 public ArrayList<String> mVoiceSearchBaseUrls;
341 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500342 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500343 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500344 */
345 public String mLastVoiceSearchUrl;
346 /**
347 * The last title used for voice search. Needed to update the title bar
348 * when switching tabs.
349 */
350 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500351 /**
352 * Whether the Intent which turned on voice search mode contained the
353 * String signifying that Google was the source.
354 */
355 public boolean mSourceIsGoogle;
356 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500357 * List of headers to be passed into the WebView containing location
358 * information
359 */
360 public ArrayList<Bundle> mHeaders;
361 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500362 * The Intent used to invoke voice search. Placed on the
363 * WebHistoryItem so that when coming back to a previous voice search
364 * page we can again activate voice search.
365 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500366 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500367 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500368 * String used to identify Google as the source of voice search.
369 */
370 public static String SOURCE_IS_GOOGLE
371 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500372 }
373
Grace Kloba22ac16e2009-10-07 18:00:23 -0700374 // Container class for the next error dialog that needs to be displayed
375 private class ErrorDialog {
376 public final int mTitle;
377 public final String mDescription;
378 public final int mError;
379 ErrorDialog(int title, String desc, int error) {
380 mTitle = title;
381 mDescription = desc;
382 mError = error;
383 }
384 };
385
386 private void processNextError() {
387 if (mQueuedErrors == null) {
388 return;
389 }
390 // The first one is currently displayed so just remove it.
391 mQueuedErrors.removeFirst();
392 if (mQueuedErrors.size() == 0) {
393 mQueuedErrors = null;
394 return;
395 }
396 showError(mQueuedErrors.getFirst());
397 }
398
399 private DialogInterface.OnDismissListener mDialogListener =
400 new DialogInterface.OnDismissListener() {
401 public void onDismiss(DialogInterface d) {
402 processNextError();
403 }
404 };
405 private LinkedList<ErrorDialog> mQueuedErrors;
406
407 private void queueError(int err, String desc) {
408 if (mQueuedErrors == null) {
409 mQueuedErrors = new LinkedList<ErrorDialog>();
410 }
411 for (ErrorDialog d : mQueuedErrors) {
412 if (d.mError == err) {
413 // Already saw a similar error, ignore the new one.
414 return;
415 }
416 }
417 ErrorDialog errDialog = new ErrorDialog(
418 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
419 R.string.browserFrameFileErrorLabel :
420 R.string.browserFrameNetworkErrorLabel,
421 desc, err);
422 mQueuedErrors.addLast(errDialog);
423
424 // Show the dialog now if the queue was empty and it is in foreground
425 if (mQueuedErrors.size() == 1 && mInForeground) {
426 showError(errDialog);
427 }
428 }
429
430 private void showError(ErrorDialog errDialog) {
431 if (mInForeground) {
432 AlertDialog d = new AlertDialog.Builder(mActivity)
433 .setTitle(errDialog.mTitle)
434 .setMessage(errDialog.mDescription)
435 .setPositiveButton(R.string.ok, null)
436 .create();
437 d.setOnDismissListener(mDialogListener);
438 d.show();
439 }
440 }
441
442 // -------------------------------------------------------------------------
443 // WebViewClient implementation for the main WebView
444 // -------------------------------------------------------------------------
445
446 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500447 private Message mDontResend;
448 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700449 @Override
450 public void onPageStarted(WebView view, String url, Bitmap favicon) {
451 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000452 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500453 if (mVoiceSearchData != null
454 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500455 if (mVoiceSearchData.mSourceIsGoogle) {
456 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
457 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
458 mActivity.sendBroadcast(i);
459 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500460 mVoiceSearchData = null;
461 if (mInForeground) {
462 mActivity.revertVoiceTitleBar();
463 }
464 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700465
466 // We've started to load a new page. If there was a pending message
467 // to save a screenshot then we will now take the new page and save
468 // an incorrect screenshot. Therefore, remove any pending thumbnail
469 // messages from the queue.
470 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
471 view);
472
473 // If we start a touch icon load and then load a new page, we don't
474 // want to cancel the current touch icon loader. But, we do want to
475 // create a new one when the touch icon url is known.
476 if (mTouchIconLoader != null) {
477 mTouchIconLoader.mTab = null;
478 mTouchIconLoader = null;
479 }
480
481 // reset the error console
482 if (mErrorConsole != null) {
483 mErrorConsole.clearErrorMessages();
484 if (mActivity.shouldShowErrorConsole()) {
485 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
486 }
487 }
488
489 // update the bookmark database for favicon
490 if (favicon != null) {
491 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
Patrick Scottcc949122010-03-17 16:06:30 -0400492 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700493 }
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 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400661 final ContentResolver cr = mActivity.getContentResolver();
662 final String newUrl = url;
663 new AsyncTask<Void, Void, Void>() {
664 protected Void doInBackground(Void... unused) {
665 Browser.updateVisitedHistory(cr, newUrl, true);
666 return null;
667 }
668 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700669 WebIconDatabase.getInstance().retainIconForPageUrl(url);
670 }
671
672 /**
673 * Displays SSL error(s) dialog to the user.
674 */
675 @Override
676 public void onReceivedSslError(final WebView view,
677 final SslErrorHandler handler, final SslError error) {
678 if (!mInForeground) {
679 handler.cancel();
680 return;
681 }
682 if (BrowserSettings.getInstance().showSecurityWarnings()) {
683 final LayoutInflater factory =
684 LayoutInflater.from(mActivity);
685 final View warningsView =
686 factory.inflate(R.layout.ssl_warnings, null);
687 final LinearLayout placeholder =
688 (LinearLayout)warningsView.findViewById(R.id.placeholder);
689
690 if (error.hasError(SslError.SSL_UNTRUSTED)) {
691 LinearLayout ll = (LinearLayout)factory
692 .inflate(R.layout.ssl_warning, null);
693 ((TextView)ll.findViewById(R.id.warning))
694 .setText(R.string.ssl_untrusted);
695 placeholder.addView(ll);
696 }
697
698 if (error.hasError(SslError.SSL_IDMISMATCH)) {
699 LinearLayout ll = (LinearLayout)factory
700 .inflate(R.layout.ssl_warning, null);
701 ((TextView)ll.findViewById(R.id.warning))
702 .setText(R.string.ssl_mismatch);
703 placeholder.addView(ll);
704 }
705
706 if (error.hasError(SslError.SSL_EXPIRED)) {
707 LinearLayout ll = (LinearLayout)factory
708 .inflate(R.layout.ssl_warning, null);
709 ((TextView)ll.findViewById(R.id.warning))
710 .setText(R.string.ssl_expired);
711 placeholder.addView(ll);
712 }
713
714 if (error.hasError(SslError.SSL_NOTYETVALID)) {
715 LinearLayout ll = (LinearLayout)factory
716 .inflate(R.layout.ssl_warning, null);
717 ((TextView)ll.findViewById(R.id.warning))
718 .setText(R.string.ssl_not_yet_valid);
719 placeholder.addView(ll);
720 }
721
722 new AlertDialog.Builder(mActivity).setTitle(
723 R.string.security_warning).setIcon(
724 android.R.drawable.ic_dialog_alert).setView(
725 warningsView).setPositiveButton(R.string.ssl_continue,
726 new DialogInterface.OnClickListener() {
727 public void onClick(DialogInterface dialog,
728 int whichButton) {
729 handler.proceed();
730 }
731 }).setNeutralButton(R.string.view_certificate,
732 new DialogInterface.OnClickListener() {
733 public void onClick(DialogInterface dialog,
734 int whichButton) {
735 mActivity.showSSLCertificateOnError(view,
736 handler, error);
737 }
738 }).setNegativeButton(R.string.cancel,
739 new DialogInterface.OnClickListener() {
740 public void onClick(DialogInterface dialog,
741 int whichButton) {
742 handler.cancel();
743 mActivity.resetTitleAndRevertLockIcon();
744 }
745 }).setOnCancelListener(
746 new DialogInterface.OnCancelListener() {
747 public void onCancel(DialogInterface dialog) {
748 handler.cancel();
749 mActivity.resetTitleAndRevertLockIcon();
750 }
751 }).show();
752 } else {
753 handler.proceed();
754 }
755 }
756
757 /**
758 * Handles an HTTP authentication request.
759 *
760 * @param handler The authentication handler
761 * @param host The host
762 * @param realm The realm
763 */
764 @Override
765 public void onReceivedHttpAuthRequest(WebView view,
766 final HttpAuthHandler handler, final String host,
767 final String realm) {
768 String username = null;
769 String password = null;
770
771 boolean reuseHttpAuthUsernamePassword = handler
772 .useHttpAuthUsernamePassword();
773
Steve Block95a53b22010-03-25 17:24:58 +0000774 if (reuseHttpAuthUsernamePassword && view != null) {
775 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700776 host, realm);
777 if (credentials != null && credentials.length == 2) {
778 username = credentials[0];
779 password = credentials[1];
780 }
781 }
782
783 if (username != null && password != null) {
784 handler.proceed(username, password);
785 } else {
786 if (mInForeground) {
787 mActivity.showHttpAuthentication(handler, host, realm,
788 null, null, null, 0);
789 } else {
790 handler.cancel();
791 }
792 }
793 }
794
795 @Override
796 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
797 if (!mInForeground) {
798 return false;
799 }
800 if (mActivity.isMenuDown()) {
801 // only check shortcut key when MENU is held
802 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
803 event);
804 } else {
805 return false;
806 }
807 }
808
809 @Override
810 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400811 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700812 return;
813 }
814 if (event.isDown()) {
815 mActivity.onKeyDown(event.getKeyCode(), event);
816 } else {
817 mActivity.onKeyUp(event.getKeyCode(), event);
818 }
819 }
820 };
821
822 // -------------------------------------------------------------------------
823 // WebChromeClient implementation for the main WebView
824 // -------------------------------------------------------------------------
825
826 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
827 // Helper method to create a new tab or sub window.
828 private void createWindow(final boolean dialog, final Message msg) {
829 WebView.WebViewTransport transport =
830 (WebView.WebViewTransport) msg.obj;
831 if (dialog) {
832 createSubWindow();
833 mActivity.attachSubWindow(Tab.this);
834 transport.setWebView(mSubView);
835 } else {
836 final Tab newTab = mActivity.openTabAndShow(
837 BrowserActivity.EMPTY_URL_DATA, false, null);
838 if (newTab != Tab.this) {
839 Tab.this.addChildTab(newTab);
840 }
841 transport.setWebView(newTab.getWebView());
842 }
843 msg.sendToTarget();
844 }
845
846 @Override
847 public boolean onCreateWindow(WebView view, final boolean dialog,
848 final boolean userGesture, final Message resultMsg) {
849 // only allow new window or sub window for the foreground case
850 if (!mInForeground) {
851 return false;
852 }
853 // Short-circuit if we can't create any more tabs or sub windows.
854 if (dialog && mSubView != null) {
855 new AlertDialog.Builder(mActivity)
856 .setTitle(R.string.too_many_subwindows_dialog_title)
857 .setIcon(android.R.drawable.ic_dialog_alert)
858 .setMessage(R.string.too_many_subwindows_dialog_message)
859 .setPositiveButton(R.string.ok, null)
860 .show();
861 return false;
862 } else if (!mActivity.getTabControl().canCreateNewTab()) {
863 new AlertDialog.Builder(mActivity)
864 .setTitle(R.string.too_many_windows_dialog_title)
865 .setIcon(android.R.drawable.ic_dialog_alert)
866 .setMessage(R.string.too_many_windows_dialog_message)
867 .setPositiveButton(R.string.ok, null)
868 .show();
869 return false;
870 }
871
872 // Short-circuit if this was a user gesture.
873 if (userGesture) {
874 createWindow(dialog, resultMsg);
875 return true;
876 }
877
878 // Allow the popup and create the appropriate window.
879 final AlertDialog.OnClickListener allowListener =
880 new AlertDialog.OnClickListener() {
881 public void onClick(DialogInterface d,
882 int which) {
883 createWindow(dialog, resultMsg);
884 }
885 };
886
887 // Block the popup by returning a null WebView.
888 final AlertDialog.OnClickListener blockListener =
889 new AlertDialog.OnClickListener() {
890 public void onClick(DialogInterface d, int which) {
891 resultMsg.sendToTarget();
892 }
893 };
894
895 // Build a confirmation dialog to display to the user.
896 final AlertDialog d =
897 new AlertDialog.Builder(mActivity)
898 .setTitle(R.string.attention)
899 .setIcon(android.R.drawable.ic_dialog_alert)
900 .setMessage(R.string.popup_window_attempt)
901 .setPositiveButton(R.string.allow, allowListener)
902 .setNegativeButton(R.string.block, blockListener)
903 .setCancelable(false)
904 .create();
905
906 // Show the confirmation dialog.
907 d.show();
908 return true;
909 }
910
911 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500912 public void onRequestFocus(WebView view) {
913 if (!mInForeground) {
914 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
915 Tab.this));
916 }
917 }
918
919 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700920 public void onCloseWindow(WebView window) {
921 if (mParentTab != null) {
922 // JavaScript can only close popup window.
923 if (mInForeground) {
924 mActivity.switchToTab(mActivity.getTabControl()
925 .getTabIndex(mParentTab));
926 }
927 mActivity.closeTab(Tab.this);
928 }
929 }
930
931 @Override
932 public void onProgressChanged(WebView view, int newProgress) {
933 if (newProgress == 100) {
934 // sync cookies and cache promptly here.
935 CookieSyncManager.getInstance().sync();
936 }
937 if (mInForeground) {
938 mActivity.onProgressChanged(view, newProgress);
939 }
940 }
941
942 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500943 public void onReceivedTitle(WebView view, final String title) {
944 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700945 if (mInForeground) {
946 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500947 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700948 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500949 if (pageUrl == null || pageUrl.length()
950 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700951 return;
952 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500953 new AsyncTask<Void, Void, Void>() {
954 protected Void doInBackground(Void... unused) {
955 // See if we can find the current url in our history
956 // database and add the new title to it.
957 String url = pageUrl;
958 if (url.startsWith("http://www.")) {
959 url = url.substring(11);
960 } else if (url.startsWith("http://")) {
961 url = url.substring(4);
962 }
963 Cursor c = null;
964 try {
965 final ContentResolver cr
966 = mActivity.getContentResolver();
967 url = "%" + url;
968 String [] selArgs = new String[] { url };
969 String where = Browser.BookmarkColumns.URL
970 + " LIKE ? AND "
971 + Browser.BookmarkColumns.BOOKMARK + " = 0";
972 c = cr.query(Browser.BOOKMARKS_URI, new String[]
973 { Browser.BookmarkColumns._ID }, where, selArgs,
974 null);
975 if (c.moveToFirst()) {
976 // Current implementation of database only has one
977 // entry per url.
978 ContentValues map = new ContentValues();
979 map.put(Browser.BookmarkColumns.TITLE, title);
980 String[] projection = new String[]
981 { Integer.valueOf(c.getInt(0)).toString() };
982 cr.update(Browser.BOOKMARKS_URI, map, "_id = ?",
983 projection);
984 }
985 } catch (IllegalStateException e) {
986 Log.e(LOGTAG, "Tab onReceived title", e);
987 } catch (SQLiteException ex) {
988 Log.e(LOGTAG,
989 "onReceivedTitle() caught SQLiteException: ",
990 ex);
991 } finally {
992 if (c != null) c.close();
993 }
994 return null;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700995 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500996 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700997 }
998
999 @Override
1000 public void onReceivedIcon(WebView view, Bitmap icon) {
1001 if (icon != null) {
1002 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
1003 .getContentResolver(), view.getOriginalUrl(), view
1004 .getUrl(), icon);
1005 }
1006 if (mInForeground) {
1007 mActivity.setFavicon(icon);
1008 }
1009 }
1010
1011 @Override
1012 public void onReceivedTouchIconUrl(WebView view, String url,
1013 boolean precomposed) {
1014 final ContentResolver cr = mActivity.getContentResolver();
1015 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
1016 view.getOriginalUrl(), view.getUrl(), true);
1017 if (c != null) {
1018 if (c.getCount() > 0) {
1019 // Let precomposed icons take precedence over non-composed
1020 // icons.
1021 if (precomposed && mTouchIconLoader != null) {
1022 mTouchIconLoader.cancel(false);
1023 mTouchIconLoader = null;
1024 }
1025 // Have only one async task at a time.
1026 if (mTouchIconLoader == null) {
1027 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
1028 c, view);
1029 mTouchIconLoader.execute(url);
Patrick Scott8e9fe322010-03-04 14:29:31 -05001030 } else {
1031 c.close();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 }
1033 } else {
1034 c.close();
1035 }
1036 }
1037 }
1038
1039 @Override
1040 public void onShowCustomView(View view,
1041 WebChromeClient.CustomViewCallback callback) {
1042 if (mInForeground) mActivity.onShowCustomView(view, callback);
1043 }
1044
1045 @Override
1046 public void onHideCustomView() {
1047 if (mInForeground) mActivity.onHideCustomView();
1048 }
1049
1050 /**
1051 * The origin has exceeded its database quota.
1052 * @param url the URL that exceeded the quota
1053 * @param databaseIdentifier the identifier of the database on which the
1054 * transaction that caused the quota overflow was run
1055 * @param currentQuota the current quota for the origin.
1056 * @param estimatedSize the estimated size of the database.
1057 * @param totalUsedQuota is the sum of all origins' quota.
1058 * @param quotaUpdater The callback to run when a decision to allow or
1059 * deny quota has been made. Don't forget to call this!
1060 */
1061 @Override
1062 public void onExceededDatabaseQuota(String url,
1063 String databaseIdentifier, long currentQuota, long estimatedSize,
1064 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1065 BrowserSettings.getInstance().getWebStorageSizeManager()
1066 .onExceededDatabaseQuota(url, databaseIdentifier,
1067 currentQuota, estimatedSize, totalUsedQuota,
1068 quotaUpdater);
1069 }
1070
1071 /**
1072 * The Application Cache has exceeded its max size.
1073 * @param spaceNeeded is the amount of disk space that would be needed
1074 * in order for the last appcache operation to succeed.
1075 * @param totalUsedQuota is the sum of all origins' quota.
1076 * @param quotaUpdater A callback to inform the WebCore thread that a
1077 * new app cache size is available. This callback must always
1078 * be executed at some point to ensure that the sleeping
1079 * WebCore thread is woken up.
1080 */
1081 @Override
1082 public void onReachedMaxAppCacheSize(long spaceNeeded,
1083 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1084 BrowserSettings.getInstance().getWebStorageSizeManager()
1085 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1086 quotaUpdater);
1087 }
1088
1089 /**
1090 * Instructs the browser to show a prompt to ask the user to set the
1091 * Geolocation permission state for the specified origin.
1092 * @param origin The origin for which Geolocation permissions are
1093 * requested.
1094 * @param callback The callback to call once the user has set the
1095 * Geolocation permission state.
1096 */
1097 @Override
1098 public void onGeolocationPermissionsShowPrompt(String origin,
1099 GeolocationPermissions.Callback callback) {
1100 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001101 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 }
1103 }
1104
1105 /**
1106 * Instructs the browser to hide the Geolocation permissions prompt.
1107 */
1108 @Override
1109 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001110 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001111 mGeolocationPermissionsPrompt.hide();
1112 }
1113 }
1114
Ben Murdoch65acc352009-11-19 18:16:04 +00001115 /* Adds a JavaScript error message to the system log and if the JS
1116 * console is enabled in the about:debug options, to that console
1117 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001118 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001119 */
1120 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001121 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 if (mInForeground) {
1123 // call getErrorConsole(true) so it will create one if needed
1124 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001125 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001126 if (mActivity.shouldShowErrorConsole()
1127 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1128 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1129 }
1130 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001131
1132 String message = "Console: " + consoleMessage.message() + " "
1133 + consoleMessage.sourceId() + ":"
1134 + consoleMessage.lineNumber();
1135
1136 switch (consoleMessage.messageLevel()) {
1137 case TIP:
1138 Log.v(CONSOLE_LOGTAG, message);
1139 break;
1140 case LOG:
1141 Log.i(CONSOLE_LOGTAG, message);
1142 break;
1143 case WARNING:
1144 Log.w(CONSOLE_LOGTAG, message);
1145 break;
1146 case ERROR:
1147 Log.e(CONSOLE_LOGTAG, message);
1148 break;
1149 case DEBUG:
1150 Log.d(CONSOLE_LOGTAG, message);
1151 break;
1152 }
1153
1154 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001155 }
1156
1157 /**
1158 * Ask the browser for an icon to represent a <video> element.
1159 * This icon will be used if the Web page did not specify a poster attribute.
1160 * @return Bitmap The icon or null if no such icon is available.
1161 */
1162 @Override
1163 public Bitmap getDefaultVideoPoster() {
1164 if (mInForeground) {
1165 return mActivity.getDefaultVideoPoster();
1166 }
1167 return null;
1168 }
1169
1170 /**
1171 * Ask the host application for a custom progress view to show while
1172 * a <video> is loading.
1173 * @return View The progress view.
1174 */
1175 @Override
1176 public View getVideoLoadingProgressView() {
1177 if (mInForeground) {
1178 return mActivity.getVideoLoadingProgressView();
1179 }
1180 return null;
1181 }
1182
1183 @Override
1184 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
1185 if (mInForeground) {
1186 mActivity.openFileChooser(uploadMsg);
1187 } else {
1188 uploadMsg.onReceiveValue(null);
1189 }
1190 }
1191
1192 /**
1193 * Deliver a list of already-visited URLs
1194 */
1195 @Override
1196 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1197 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
1198 public String[] doInBackground(Void... unused) {
1199 return Browser.getVisitedHistory(mActivity
1200 .getContentResolver());
1201 }
1202 public void onPostExecute(String[] result) {
1203 callback.onReceiveValue(result);
1204 };
1205 };
1206 task.execute();
1207 };
1208 };
1209
1210 // -------------------------------------------------------------------------
1211 // WebViewClient implementation for the sub window
1212 // -------------------------------------------------------------------------
1213
1214 // Subclass of WebViewClient used in subwindows to notify the main
1215 // WebViewClient of certain WebView activities.
1216 private static class SubWindowClient extends WebViewClient {
1217 // The main WebViewClient.
1218 private final WebViewClient mClient;
1219
1220 SubWindowClient(WebViewClient client) {
1221 mClient = client;
1222 }
1223 @Override
1224 public void doUpdateVisitedHistory(WebView view, String url,
1225 boolean isReload) {
1226 mClient.doUpdateVisitedHistory(view, url, isReload);
1227 }
1228 @Override
1229 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1230 return mClient.shouldOverrideUrlLoading(view, url);
1231 }
1232 @Override
1233 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1234 SslError error) {
1235 mClient.onReceivedSslError(view, handler, error);
1236 }
1237 @Override
1238 public void onReceivedHttpAuthRequest(WebView view,
1239 HttpAuthHandler handler, String host, String realm) {
1240 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1241 }
1242 @Override
1243 public void onFormResubmission(WebView view, Message dontResend,
1244 Message resend) {
1245 mClient.onFormResubmission(view, dontResend, resend);
1246 }
1247 @Override
1248 public void onReceivedError(WebView view, int errorCode,
1249 String description, String failingUrl) {
1250 mClient.onReceivedError(view, errorCode, description, failingUrl);
1251 }
1252 @Override
1253 public boolean shouldOverrideKeyEvent(WebView view,
1254 android.view.KeyEvent event) {
1255 return mClient.shouldOverrideKeyEvent(view, event);
1256 }
1257 @Override
1258 public void onUnhandledKeyEvent(WebView view,
1259 android.view.KeyEvent event) {
1260 mClient.onUnhandledKeyEvent(view, event);
1261 }
1262 }
1263
1264 // -------------------------------------------------------------------------
1265 // WebChromeClient implementation for the sub window
1266 // -------------------------------------------------------------------------
1267
1268 private class SubWindowChromeClient extends WebChromeClient {
1269 // The main WebChromeClient.
1270 private final WebChromeClient mClient;
1271
1272 SubWindowChromeClient(WebChromeClient client) {
1273 mClient = client;
1274 }
1275 @Override
1276 public void onProgressChanged(WebView view, int newProgress) {
1277 mClient.onProgressChanged(view, newProgress);
1278 }
1279 @Override
1280 public boolean onCreateWindow(WebView view, boolean dialog,
1281 boolean userGesture, android.os.Message resultMsg) {
1282 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1283 }
1284 @Override
1285 public void onCloseWindow(WebView window) {
1286 if (window != mSubView) {
1287 Log.e(LOGTAG, "Can't close the window");
1288 }
1289 mActivity.dismissSubWindow(Tab.this);
1290 }
1291 }
1292
1293 // -------------------------------------------------------------------------
1294
1295 // Construct a new tab
1296 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1297 String url) {
1298 mActivity = activity;
1299 mCloseOnExit = closeOnExit;
1300 mAppId = appId;
1301 mOriginalUrl = url;
1302 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1303 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1304 mInLoad = false;
1305 mInForeground = false;
1306
1307 mInflateService = LayoutInflater.from(activity);
1308
1309 // The tab consists of a container view, which contains the main
1310 // WebView, as well as any other UI elements associated with the tab.
1311 mContainer = mInflateService.inflate(R.layout.tab, null);
1312
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001313 mDownloadListener = new DownloadListener() {
1314 public void onDownloadStart(String url, String userAgent,
1315 String contentDisposition, String mimetype,
1316 long contentLength) {
1317 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1318 mimetype, contentLength);
1319 if (mMainView.copyBackForwardList().getSize() == 0) {
1320 // This Tab was opened for the sole purpose of downloading a
1321 // file. Remove it.
1322 if (mActivity.getTabControl().getCurrentWebView()
1323 == mMainView) {
1324 // In this case, the Tab is still on top.
1325 mActivity.goBackOnePageOrQuit();
1326 } else {
1327 // In this case, it is not.
1328 mActivity.closeTab(Tab.this);
1329 }
1330 }
1331 }
1332 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001333 mWebBackForwardListClient = new WebBackForwardListClient() {
1334 @Override
1335 public void onNewHistoryItem(WebHistoryItem item) {
1336 if (isInVoiceSearchMode()) {
1337 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1338 }
1339 }
1340 @Override
1341 public void onIndexChanged(WebHistoryItem item, int index) {
1342 Object data = item.getCustomData();
1343 if (data != null && data instanceof Intent) {
1344 activateVoiceSearchMode((Intent) data);
1345 }
1346 }
1347 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001348
Grace Kloba22ac16e2009-10-07 18:00:23 -07001349 setWebView(w);
1350 }
1351
1352 /**
1353 * Sets the WebView for this tab, correctly removing the old WebView from
1354 * the container view.
1355 */
1356 void setWebView(WebView w) {
1357 if (mMainView == w) {
1358 return;
1359 }
1360 // If the WebView is changing, the page will be reloaded, so any ongoing
1361 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001362 if (mGeolocationPermissionsPrompt != null) {
1363 mGeolocationPermissionsPrompt.hide();
1364 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001365
1366 // Just remove the old one.
1367 FrameLayout wrapper =
1368 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1369 wrapper.removeView(mMainView);
1370
1371 // set the new one
1372 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001373 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001374 if (mMainView != null) {
1375 mMainView.setWebViewClient(mWebViewClient);
1376 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001377 // Attach DownloadManager so that downloads can start in an active
1378 // or a non-active window. This can happen when going to a site that
1379 // does a redirect after a period of time. The user could have
1380 // switched to another tab while waiting for the download to start.
1381 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001382 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001383 }
1384 }
1385
1386 /**
1387 * Destroy the tab's main WebView and subWindow if any
1388 */
1389 void destroy() {
1390 if (mMainView != null) {
1391 dismissSubWindow();
1392 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1393 // save the WebView to call destroy() after detach it from the tab
1394 WebView webView = mMainView;
1395 setWebView(null);
1396 webView.destroy();
1397 }
1398 }
1399
1400 /**
1401 * Remove the tab from the parent
1402 */
1403 void removeFromTree() {
1404 // detach the children
1405 if (mChildTabs != null) {
1406 for(Tab t : mChildTabs) {
1407 t.setParentTab(null);
1408 }
1409 }
1410 // remove itself from the parent list
1411 if (mParentTab != null) {
1412 mParentTab.mChildTabs.remove(this);
1413 }
1414 }
1415
1416 /**
1417 * Create a new subwindow unless a subwindow already exists.
1418 * @return True if a new subwindow was created. False if one already exists.
1419 */
1420 boolean createSubWindow() {
1421 if (mSubView == null) {
1422 mSubViewContainer = mInflateService.inflate(
1423 R.layout.browser_subwindow, null);
1424 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001425 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001426 // use trackball directly
1427 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001428 // Enable the built-in zoom
1429 mSubView.getSettings().setBuiltInZoomControls(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001430 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1431 mSubView.setWebChromeClient(new SubWindowChromeClient(
1432 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001433 // Set a different DownloadListener for the mSubView, since it will
1434 // just need to dismiss the mSubView, rather than close the Tab
1435 mSubView.setDownloadListener(new DownloadListener() {
1436 public void onDownloadStart(String url, String userAgent,
1437 String contentDisposition, String mimetype,
1438 long contentLength) {
1439 mActivity.onDownloadStart(url, userAgent,
1440 contentDisposition, mimetype, contentLength);
1441 if (mSubView.copyBackForwardList().getSize() == 0) {
1442 // This subwindow was opened for the sole purpose of
1443 // downloading a file. Remove it.
1444 dismissSubWindow();
1445 }
1446 }
1447 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001448 mSubView.setOnCreateContextMenuListener(mActivity);
1449 final BrowserSettings s = BrowserSettings.getInstance();
1450 s.addObserver(mSubView.getSettings()).update(s, null);
1451 final ImageButton cancel = (ImageButton) mSubViewContainer
1452 .findViewById(R.id.subwindow_close);
1453 cancel.setOnClickListener(new OnClickListener() {
1454 public void onClick(View v) {
1455 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1456 }
1457 });
1458 return true;
1459 }
1460 return false;
1461 }
1462
1463 /**
1464 * Dismiss the subWindow for the tab.
1465 */
1466 void dismissSubWindow() {
1467 if (mSubView != null) {
1468 BrowserSettings.getInstance().deleteObserver(
1469 mSubView.getSettings());
1470 mSubView.destroy();
1471 mSubView = null;
1472 mSubViewContainer = null;
1473 }
1474 }
1475
1476 /**
1477 * Attach the sub window to the content view.
1478 */
1479 void attachSubWindow(ViewGroup content) {
1480 if (mSubView != null) {
1481 content.addView(mSubViewContainer,
1482 BrowserActivity.COVER_SCREEN_PARAMS);
1483 }
1484 }
1485
1486 /**
1487 * Remove the sub window from the content view.
1488 */
1489 void removeSubWindow(ViewGroup content) {
1490 if (mSubView != null) {
1491 content.removeView(mSubViewContainer);
1492 }
1493 }
1494
1495 /**
1496 * This method attaches both the WebView and any sub window to the
1497 * given content view.
1498 */
1499 void attachTabToContentView(ViewGroup content) {
1500 if (mMainView == null) {
1501 return;
1502 }
1503
1504 // Attach the WebView to the container and then attach the
1505 // container to the content view.
1506 FrameLayout wrapper =
1507 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001508 ViewGroup parent = (ViewGroup) mMainView.getParent();
1509 if (parent != wrapper) {
1510 if (parent != null) {
1511 Log.w(LOGTAG, "mMainView already has a parent in"
1512 + " attachTabToContentView!");
1513 parent.removeView(mMainView);
1514 }
1515 wrapper.addView(mMainView);
1516 } else {
1517 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1518 + " attachTabToContentView!");
1519 }
1520 parent = (ViewGroup) mContainer.getParent();
1521 if (parent != content) {
1522 if (parent != null) {
1523 Log.w(LOGTAG, "mContainer already has a parent in"
1524 + " attachTabToContentView!");
1525 parent.removeView(mContainer);
1526 }
1527 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1528 } else {
1529 Log.w(LOGTAG, "mContainer is already attached to content in"
1530 + " attachTabToContentView!");
1531 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001532 attachSubWindow(content);
1533 }
1534
1535 /**
1536 * Remove the WebView and any sub window from the given content view.
1537 */
1538 void removeTabFromContentView(ViewGroup content) {
1539 if (mMainView == null) {
1540 return;
1541 }
1542
1543 // Remove the container from the content and then remove the
1544 // WebView from the container. This will trigger a focus change
1545 // needed by WebView.
1546 FrameLayout wrapper =
1547 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1548 wrapper.removeView(mMainView);
1549 content.removeView(mContainer);
1550 removeSubWindow(content);
1551 }
1552
1553 /**
1554 * Set the parent tab of this tab.
1555 */
1556 void setParentTab(Tab parent) {
1557 mParentTab = parent;
1558 // This tab may have been freed due to low memory. If that is the case,
1559 // the parent tab index is already saved. If we are changing that index
1560 // (most likely due to removing the parent tab) we must update the
1561 // parent tab index in the saved Bundle.
1562 if (mSavedState != null) {
1563 if (parent == null) {
1564 mSavedState.remove(PARENTTAB);
1565 } else {
1566 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1567 .getTabIndex(parent));
1568 }
1569 }
1570 }
1571
1572 /**
1573 * When a Tab is created through the content of another Tab, then we
1574 * associate the Tabs.
1575 * @param child the Tab that was created from this Tab
1576 */
1577 void addChildTab(Tab child) {
1578 if (mChildTabs == null) {
1579 mChildTabs = new Vector<Tab>();
1580 }
1581 mChildTabs.add(child);
1582 child.setParentTab(this);
1583 }
1584
1585 Vector<Tab> getChildTabs() {
1586 return mChildTabs;
1587 }
1588
1589 void resume() {
1590 if (mMainView != null) {
1591 mMainView.onResume();
1592 if (mSubView != null) {
1593 mSubView.onResume();
1594 }
1595 }
1596 }
1597
1598 void pause() {
1599 if (mMainView != null) {
1600 mMainView.onPause();
1601 if (mSubView != null) {
1602 mSubView.onPause();
1603 }
1604 }
1605 }
1606
1607 void putInForeground() {
1608 mInForeground = true;
1609 resume();
1610 mMainView.setOnCreateContextMenuListener(mActivity);
1611 if (mSubView != null) {
1612 mSubView.setOnCreateContextMenuListener(mActivity);
1613 }
1614 // Show the pending error dialog if the queue is not empty
1615 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1616 showError(mQueuedErrors.getFirst());
1617 }
1618 }
1619
1620 void putInBackground() {
1621 mInForeground = false;
1622 pause();
1623 mMainView.setOnCreateContextMenuListener(null);
1624 if (mSubView != null) {
1625 mSubView.setOnCreateContextMenuListener(null);
1626 }
1627 }
1628
1629 /**
1630 * Return the top window of this tab; either the subwindow if it is not
1631 * null or the main window.
1632 * @return The top window of this tab.
1633 */
1634 WebView getTopWindow() {
1635 if (mSubView != null) {
1636 return mSubView;
1637 }
1638 return mMainView;
1639 }
1640
1641 /**
1642 * Return the main window of this tab. Note: if a tab is freed in the
1643 * background, this can return null. It is only guaranteed to be
1644 * non-null for the current tab.
1645 * @return The main WebView of this tab.
1646 */
1647 WebView getWebView() {
1648 return mMainView;
1649 }
1650
1651 /**
1652 * Return the subwindow of this tab or null if there is no subwindow.
1653 * @return The subwindow of this tab or null.
1654 */
1655 WebView getSubWebView() {
1656 return mSubView;
1657 }
1658
1659 /**
1660 * @return The geolocation permissions prompt for this tab.
1661 */
1662 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001663 if (mGeolocationPermissionsPrompt == null) {
1664 ViewStub stub = (ViewStub) mContainer
1665 .findViewById(R.id.geolocation_permissions_prompt);
1666 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1667 .inflate();
1668 mGeolocationPermissionsPrompt.init();
1669 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001670 return mGeolocationPermissionsPrompt;
1671 }
1672
1673 /**
1674 * @return The application id string
1675 */
1676 String getAppId() {
1677 return mAppId;
1678 }
1679
1680 /**
1681 * Set the application id string
1682 * @param id
1683 */
1684 void setAppId(String id) {
1685 mAppId = id;
1686 }
1687
1688 /**
1689 * @return The original url associated with this Tab
1690 */
1691 String getOriginalUrl() {
1692 return mOriginalUrl;
1693 }
1694
1695 /**
1696 * Set the original url associated with this tab
1697 */
1698 void setOriginalUrl(String url) {
1699 mOriginalUrl = url;
1700 }
1701
1702 /**
1703 * Get the url of this tab. Valid after calling populatePickerData, but
1704 * before calling wipePickerData, or if the webview has been destroyed.
1705 * @return The WebView's url or null.
1706 */
1707 String getUrl() {
1708 if (mPickerData != null) {
1709 return mPickerData.mUrl;
1710 }
1711 return null;
1712 }
1713
1714 /**
1715 * Get the title of this tab. Valid after calling populatePickerData, but
1716 * before calling wipePickerData, or if the webview has been destroyed. If
1717 * the url has no title, use the url instead.
1718 * @return The WebView's title (or url) or null.
1719 */
1720 String getTitle() {
1721 if (mPickerData != null) {
1722 return mPickerData.mTitle;
1723 }
1724 return null;
1725 }
1726
1727 /**
1728 * Get the favicon of this tab. Valid after calling populatePickerData, but
1729 * before calling wipePickerData, or if the webview has been destroyed.
1730 * @return The WebView's favicon or null.
1731 */
1732 Bitmap getFavicon() {
1733 if (mPickerData != null) {
1734 return mPickerData.mFavicon;
1735 }
1736 return null;
1737 }
1738
1739 /**
1740 * Return the tab's error console. Creates the console if createIfNEcessary
1741 * is true and we haven't already created the console.
1742 * @param createIfNecessary Flag to indicate if the console should be
1743 * created if it has not been already.
1744 * @return The tab's error console, or null if one has not been created and
1745 * createIfNecessary is false.
1746 */
1747 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1748 if (createIfNecessary && mErrorConsole == null) {
1749 mErrorConsole = new ErrorConsoleView(mActivity);
1750 mErrorConsole.setWebView(mMainView);
1751 }
1752 return mErrorConsole;
1753 }
1754
1755 /**
1756 * If this Tab was created through another Tab, then this method returns
1757 * that Tab.
1758 * @return the Tab parent or null
1759 */
1760 public Tab getParentTab() {
1761 return mParentTab;
1762 }
1763
1764 /**
1765 * Return whether this tab should be closed when it is backing out of the
1766 * first page.
1767 * @return TRUE if this tab should be closed when exit.
1768 */
1769 boolean closeOnExit() {
1770 return mCloseOnExit;
1771 }
1772
1773 /**
1774 * Saves the current lock-icon state before resetting the lock icon. If we
1775 * have an error, we may need to roll back to the previous state.
1776 */
1777 void resetLockIcon(String url) {
1778 mPrevLockIconType = mLockIconType;
1779 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1780 if (URLUtil.isHttpsUrl(url)) {
1781 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1782 }
1783 }
1784
1785 /**
1786 * Reverts the lock-icon state to the last saved state, for example, if we
1787 * had an error, and need to cancel the load.
1788 */
1789 void revertLockIcon() {
1790 mLockIconType = mPrevLockIconType;
1791 }
1792
1793 /**
1794 * @return The tab's lock icon type.
1795 */
1796 int getLockIconType() {
1797 return mLockIconType;
1798 }
1799
1800 /**
1801 * @return TRUE if onPageStarted is called while onPageFinished is not
1802 * called yet.
1803 */
1804 boolean inLoad() {
1805 return mInLoad;
1806 }
1807
1808 // force mInLoad to be false. This should only be called before closing the
1809 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1810 void clearInLoad() {
1811 mInLoad = false;
1812 }
1813
1814 void populatePickerData() {
1815 if (mMainView == null) {
1816 populatePickerDataFromSavedState();
1817 return;
1818 }
1819
1820 // FIXME: The only place we cared about subwindow was for
1821 // bookmarking (i.e. not when saving state). Was this deliberate?
1822 final WebBackForwardList list = mMainView.copyBackForwardList();
1823 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1824 populatePickerData(item);
1825 }
1826
1827 // Populate the picker data using the given history item and the current top
1828 // WebView.
1829 private void populatePickerData(WebHistoryItem item) {
1830 mPickerData = new PickerData();
1831 if (item != null) {
1832 mPickerData.mUrl = item.getUrl();
1833 mPickerData.mTitle = item.getTitle();
1834 mPickerData.mFavicon = item.getFavicon();
1835 if (mPickerData.mTitle == null) {
1836 mPickerData.mTitle = mPickerData.mUrl;
1837 }
1838 }
1839 }
1840
1841 // Create the PickerData and populate it using the saved state of the tab.
1842 void populatePickerDataFromSavedState() {
1843 if (mSavedState == null) {
1844 return;
1845 }
1846 mPickerData = new PickerData();
1847 mPickerData.mUrl = mSavedState.getString(CURRURL);
1848 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1849 }
1850
1851 void clearPickerData() {
1852 mPickerData = null;
1853 }
1854
1855 /**
1856 * Get the saved state bundle.
1857 * @return
1858 */
1859 Bundle getSavedState() {
1860 return mSavedState;
1861 }
1862
1863 /**
1864 * Set the saved state.
1865 */
1866 void setSavedState(Bundle state) {
1867 mSavedState = state;
1868 }
1869
1870 /**
1871 * @return TRUE if succeed in saving the state.
1872 */
1873 boolean saveState() {
1874 // If the WebView is null it means we ran low on memory and we already
1875 // stored the saved state in mSavedState.
1876 if (mMainView == null) {
1877 return mSavedState != null;
1878 }
1879
1880 mSavedState = new Bundle();
1881 final WebBackForwardList list = mMainView.saveState(mSavedState);
1882 if (list != null) {
1883 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1884 mMainView.hashCode() + "_pic.save");
1885 if (mMainView.savePicture(mSavedState, f)) {
1886 mSavedState.putString(CURRPICTURE, f.getPath());
Mike Reedd5eee692010-03-05 10:13:34 -05001887 } else {
1888 // if savePicture returned false, we can't trust the contents,
1889 // and it may be large, so we delete it right away
1890 f.delete();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001891 }
1892 }
1893
1894 // Store some extra info for displaying the tab in the picker.
1895 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1896 populatePickerData(item);
1897
1898 if (mPickerData.mUrl != null) {
1899 mSavedState.putString(CURRURL, mPickerData.mUrl);
1900 }
1901 if (mPickerData.mTitle != null) {
1902 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1903 }
1904 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1905 if (mAppId != null) {
1906 mSavedState.putString(APPID, mAppId);
1907 }
1908 if (mOriginalUrl != null) {
1909 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1910 }
1911 // Remember the parent tab so the relationship can be restored.
1912 if (mParentTab != null) {
1913 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1914 mParentTab));
1915 }
1916 return true;
1917 }
1918
1919 /*
1920 * Restore the state of the tab.
1921 */
1922 boolean restoreState(Bundle b) {
1923 if (b == null) {
1924 return false;
1925 }
1926 // Restore the internal state even if the WebView fails to restore.
1927 // This will maintain the app id, original url and close-on-exit values.
1928 mSavedState = null;
1929 mPickerData = null;
1930 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1931 mAppId = b.getString(APPID);
1932 mOriginalUrl = b.getString(ORIGINALURL);
1933
1934 final WebBackForwardList list = mMainView.restoreState(b);
1935 if (list == null) {
1936 return false;
1937 }
1938 if (b.containsKey(CURRPICTURE)) {
1939 final File f = new File(b.getString(CURRPICTURE));
1940 mMainView.restorePicture(b, f);
1941 f.delete();
1942 }
1943 return true;
1944 }
1945}