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