blob: dc424289208325b7a173316990078db67dc1e9bb [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 /**
Leon Scroggins III95d9bfd2010-09-14 14:02:36 -0400169 * Remove voice search mode from this tab.
170 */
171 public void revertVoiceSearchMode() {
172 if (mVoiceSearchData != null) {
173 mVoiceSearchData = null;
174 if (mInForeground) {
175 mActivity.revertVoiceTitleBar();
176 }
177 }
178 }
179 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500180 * Return whether the tab is in voice search mode.
181 */
182 public boolean isInVoiceSearchMode() {
183 return mVoiceSearchData != null;
184 }
185 /**
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400186 * Return true if the Tab is in voice search mode and the voice search
187 * Intent came with a String identifying that Google provided the Intent.
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500188 */
189 public boolean voiceSearchSourceIsGoogle() {
190 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
191 }
192 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500193 * Get the title to display for the current voice search page. If the Tab
194 * is not in voice search mode, return null.
195 */
196 public String getVoiceDisplayTitle() {
197 if (mVoiceSearchData == null) return null;
198 return mVoiceSearchData.mLastVoiceSearchTitle;
199 }
200 /**
201 * Get the latest array of voice search results, to be passed to the
202 * BrowserProvider. If the Tab is not in voice search mode, return null.
203 */
204 public ArrayList<String> getVoiceSearchResults() {
205 if (mVoiceSearchData == null) return null;
206 return mVoiceSearchData.mVoiceSearchResults;
207 }
208 /**
209 * Activate voice search mode.
210 * @param intent Intent which has the results to use, or an index into the
211 * results when reusing the old results.
212 */
213 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500214 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500215 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500216 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500217 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500218 ArrayList<String> urls = intent.getStringArrayListExtra(
219 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
220 ArrayList<String> htmls = intent.getStringArrayListExtra(
221 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
222 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
223 RecognizerResultsIntent
224 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500225 // This tab is now entering voice search mode for the first time, or
226 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500227 int size = results.size();
228 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500229 throw new AssertionError("improper extras passed in Intent");
230 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500231 if (htmls == null || htmls.size() != size || baseUrls == null ||
232 (baseUrls.size() != size && baseUrls.size() != 1)) {
233 // If either of these arrays are empty/incorrectly sized, ignore
234 // them.
235 htmls = null;
236 baseUrls = null;
237 }
238 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
239 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500240 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
241 RecognizerResultsIntent
242 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500243 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
244 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400245 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500246 }
247 String extraData = intent.getStringExtra(
248 SearchManager.EXTRA_DATA_KEY);
249 if (extraData != null) {
250 index = Integer.parseInt(extraData);
251 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
252 throw new AssertionError("index must be less than "
253 + "size of mVoiceSearchResults");
254 }
255 if (mVoiceSearchData.mSourceIsGoogle) {
256 Intent logIntent = new Intent(
257 LoggingEvents.ACTION_LOG_EVENT);
258 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
259 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
260 logIntent.putExtra(
261 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
262 index);
263 mActivity.sendBroadcast(logIntent);
264 }
265 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400266 // Copy the Intent, so that each history item will have its own
267 // Intent, with different (or none) extra data.
268 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
269 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
270 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500271 }
272 }
273 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500274 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500275 if (mInForeground) {
276 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
277 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500278 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
279 // When index was found it was already ensured that it was valid
280 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
281 if (uriString != null) {
282 Uri dataUri = Uri.parse(uriString);
283 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
284 dataUri.getScheme())) {
285 // If there is only one base URL, use it. If there are
286 // more, there will be one for each index, so use the base
287 // URL corresponding to the index.
288 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
289 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
290 index : 0);
291 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
292 mMainView.loadDataWithBaseURL(baseUrl,
293 uriString.substring(RecognizerResultsIntent
294 .URI_SCHEME_INLINE.length() + 1), "text/html",
295 "utf-8", baseUrl);
296 return;
297 }
298 }
299 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500300 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500301 = mVoiceSearchData.mVoiceSearchUrls.get(index);
302 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
303 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
304 mVoiceSearchData.mLastVoiceSearchTitle);
305 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500306 Map<String, String> headers = null;
307 if (mVoiceSearchData.mHeaders != null) {
308 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
309 : index;
310 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
311 if (bundle != null && !bundle.isEmpty()) {
312 Iterator<String> iter = bundle.keySet().iterator();
313 headers = new HashMap<String, String>();
314 while (iter.hasNext()) {
315 String key = iter.next();
316 headers.put(key, bundle.getString(key));
317 }
318 }
319 }
320 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500321 }
322 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500323 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500324 ArrayList<String> urls, ArrayList<String> htmls,
325 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500326 mVoiceSearchResults = results;
327 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500328 mVoiceSearchHtmls = htmls;
329 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500330 }
331 /*
332 * ArrayList of suggestions to be displayed when opening the
333 * SearchManager
334 */
335 public ArrayList<String> mVoiceSearchResults;
336 /*
337 * ArrayList of urls, associated with the suggestions in
338 * mVoiceSearchResults.
339 */
340 public ArrayList<String> mVoiceSearchUrls;
341 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500342 * ArrayList holding content to load for each item in
343 * mVoiceSearchResults.
344 */
345 public ArrayList<String> mVoiceSearchHtmls;
346 /*
347 * ArrayList holding base urls for the items in mVoiceSearchResults.
348 * If non null, this will either have the same size as
349 * mVoiceSearchResults or have a size of 1, in which case all will use
350 * the same base url
351 */
352 public ArrayList<String> mVoiceSearchBaseUrls;
353 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500354 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500355 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500356 */
357 public String mLastVoiceSearchUrl;
358 /**
359 * The last title used for voice search. Needed to update the title bar
360 * when switching tabs.
361 */
362 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500363 /**
364 * Whether the Intent which turned on voice search mode contained the
365 * String signifying that Google was the source.
366 */
367 public boolean mSourceIsGoogle;
368 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500369 * List of headers to be passed into the WebView containing location
370 * information
371 */
372 public ArrayList<Bundle> mHeaders;
373 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500374 * The Intent used to invoke voice search. Placed on the
375 * WebHistoryItem so that when coming back to a previous voice search
376 * page we can again activate voice search.
377 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500378 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500379 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500380 * String used to identify Google as the source of voice search.
381 */
382 public static String SOURCE_IS_GOOGLE
383 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500384 }
385
Grace Kloba22ac16e2009-10-07 18:00:23 -0700386 // Container class for the next error dialog that needs to be displayed
387 private class ErrorDialog {
388 public final int mTitle;
389 public final String mDescription;
390 public final int mError;
391 ErrorDialog(int title, String desc, int error) {
392 mTitle = title;
393 mDescription = desc;
394 mError = error;
395 }
396 };
397
398 private void processNextError() {
399 if (mQueuedErrors == null) {
400 return;
401 }
402 // The first one is currently displayed so just remove it.
403 mQueuedErrors.removeFirst();
404 if (mQueuedErrors.size() == 0) {
405 mQueuedErrors = null;
406 return;
407 }
408 showError(mQueuedErrors.getFirst());
409 }
410
411 private DialogInterface.OnDismissListener mDialogListener =
412 new DialogInterface.OnDismissListener() {
413 public void onDismiss(DialogInterface d) {
414 processNextError();
415 }
416 };
417 private LinkedList<ErrorDialog> mQueuedErrors;
418
419 private void queueError(int err, String desc) {
420 if (mQueuedErrors == null) {
421 mQueuedErrors = new LinkedList<ErrorDialog>();
422 }
423 for (ErrorDialog d : mQueuedErrors) {
424 if (d.mError == err) {
425 // Already saw a similar error, ignore the new one.
426 return;
427 }
428 }
429 ErrorDialog errDialog = new ErrorDialog(
430 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
431 R.string.browserFrameFileErrorLabel :
432 R.string.browserFrameNetworkErrorLabel,
433 desc, err);
434 mQueuedErrors.addLast(errDialog);
435
436 // Show the dialog now if the queue was empty and it is in foreground
437 if (mQueuedErrors.size() == 1 && mInForeground) {
438 showError(errDialog);
439 }
440 }
441
442 private void showError(ErrorDialog errDialog) {
443 if (mInForeground) {
444 AlertDialog d = new AlertDialog.Builder(mActivity)
445 .setTitle(errDialog.mTitle)
446 .setMessage(errDialog.mDescription)
447 .setPositiveButton(R.string.ok, null)
448 .create();
449 d.setOnDismissListener(mDialogListener);
450 d.show();
451 }
452 }
453
454 // -------------------------------------------------------------------------
455 // WebViewClient implementation for the main WebView
456 // -------------------------------------------------------------------------
457
458 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500459 private Message mDontResend;
460 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700461 @Override
462 public void onPageStarted(WebView view, String url, Bitmap favicon) {
463 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000464 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500465 if (mVoiceSearchData != null
466 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500467 if (mVoiceSearchData.mSourceIsGoogle) {
468 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
469 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
470 mActivity.sendBroadcast(i);
471 }
Leon Scroggins III95d9bfd2010-09-14 14:02:36 -0400472 revertVoiceSearchMode();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500473 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700474
475 // We've started to load a new page. If there was a pending message
476 // to save a screenshot then we will now take the new page and save
477 // an incorrect screenshot. Therefore, remove any pending thumbnail
478 // messages from the queue.
479 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
480 view);
481
482 // If we start a touch icon load and then load a new page, we don't
483 // want to cancel the current touch icon loader. But, we do want to
484 // create a new one when the touch icon url is known.
485 if (mTouchIconLoader != null) {
486 mTouchIconLoader.mTab = null;
487 mTouchIconLoader = null;
488 }
489
490 // reset the error console
491 if (mErrorConsole != null) {
492 mErrorConsole.clearErrorMessages();
493 if (mActivity.shouldShowErrorConsole()) {
494 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
495 }
496 }
497
498 // update the bookmark database for favicon
499 if (favicon != null) {
Jeff Hamilton1a805652010-09-07 12:36:30 -0700500 Bookmarks.updateFavicon(mActivity
Patrick Scottcc949122010-03-17 16:06:30 -0400501 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700502 }
503
504 // reset sync timer to avoid sync starts during loading a page
505 CookieSyncManager.getInstance().resetSync();
506
507 if (!mActivity.isNetworkUp()) {
508 view.setNetworkAvailable(false);
509 }
510
511 // finally update the UI in the activity if it is in the foreground
512 if (mInForeground) {
513 mActivity.onPageStarted(view, url, favicon);
514 }
Michael Kolbfe251992010-07-08 15:41:55 -0700515 if (getTabChangeListener() != null) {
516 getTabChangeListener().onPageStarted(Tab.this);
517 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700518 }
519
520 @Override
521 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000522 LogTag.logPageFinishedLoading(
523 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700524 mInLoad = false;
525
526 if (mInForeground && !mActivity.didUserStopLoading()
527 || !mInForeground) {
528 // Only update the bookmark screenshot if the user did not
529 // cancel the load early.
530 mActivity.postMessage(
531 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
532 500);
533 }
534
535 // finally update the UI in the activity if it is in the foreground
536 if (mInForeground) {
537 mActivity.onPageFinished(view, url);
538 }
Michael Kolbfe251992010-07-08 15:41:55 -0700539 if (getTabChangeListener() != null) {
540 getTabChangeListener().onPageFinished(Tab.this);
541 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700542 }
543
544 // return true if want to hijack the url to let another app to handle it
545 @Override
546 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400547 if (voiceSearchSourceIsGoogle()) {
548 // This method is called when the user clicks on a link.
549 // VoiceSearchMode is turned off when the user leaves the
550 // Google results page, so at this point the user must be on
551 // that page. If the user clicked a link on that page, assume
552 // that the voice search was effective, and broadcast an Intent
553 // so a receiver can take note of that fact.
554 Intent logIntent = new Intent(LoggingEvents.ACTION_LOG_EVENT);
555 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
556 LoggingEvents.VoiceSearch.RESULT_CLICKED);
557 mActivity.sendBroadcast(logIntent);
558 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700559 if (mInForeground) {
560 return mActivity.shouldOverrideUrlLoading(view, url);
561 } else {
562 return false;
563 }
564 }
565
566 /**
567 * Updates the lock icon. This method is called when we discover another
568 * resource to be loaded for this page (for example, javascript). While
569 * we update the icon type, we do not update the lock icon itself until
570 * we are done loading, it is slightly more secure this way.
571 */
572 @Override
573 public void onLoadResource(WebView view, String url) {
574 if (url != null && url.length() > 0) {
575 // It is only if the page claims to be secure that we may have
576 // to update the lock:
577 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
578 // If NOT a 'safe' url, change the lock to mixed content!
579 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
580 || URLUtil.isAboutUrl(url))) {
581 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
582 }
583 }
584 }
585 }
586
587 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700588 * Show a dialog informing the user of the network error reported by
589 * WebCore if it is in the foreground.
590 */
591 @Override
592 public void onReceivedError(WebView view, int errorCode,
593 String description, String failingUrl) {
594 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
595 errorCode != WebViewClient.ERROR_CONNECT &&
596 errorCode != WebViewClient.ERROR_BAD_URL &&
597 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
598 errorCode != WebViewClient.ERROR_FILE) {
599 queueError(errorCode, description);
600 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500601
602 // Don't log URLs when in private browsing mode
603 if (!getWebView().isPrivateBrowsingEnabled()) {
604 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
605 + " " + description);
606 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700607
608 // We need to reset the title after an error if it is in foreground.
609 if (mInForeground) {
610 mActivity.resetTitleAndRevertLockIcon();
611 }
612 }
613
614 /**
615 * Check with the user if it is ok to resend POST data as the page they
616 * are trying to navigate to is the result of a POST.
617 */
618 @Override
619 public void onFormResubmission(WebView view, final Message dontResend,
620 final Message resend) {
621 if (!mInForeground) {
622 dontResend.sendToTarget();
623 return;
624 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500625 if (mDontResend != null) {
626 Log.w(LOGTAG, "onFormResubmission should not be called again "
627 + "while dialog is still up");
628 dontResend.sendToTarget();
629 return;
630 }
631 mDontResend = dontResend;
632 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700633 new AlertDialog.Builder(mActivity).setTitle(
634 R.string.browserFrameFormResubmitLabel).setMessage(
635 R.string.browserFrameFormResubmitMessage)
636 .setPositiveButton(R.string.ok,
637 new DialogInterface.OnClickListener() {
638 public void onClick(DialogInterface dialog,
639 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500640 if (mResend != null) {
641 mResend.sendToTarget();
642 mResend = null;
643 mDontResend = null;
644 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700645 }
646 }).setNegativeButton(R.string.cancel,
647 new DialogInterface.OnClickListener() {
648 public void onClick(DialogInterface dialog,
649 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500650 if (mDontResend != null) {
651 mDontResend.sendToTarget();
652 mResend = null;
653 mDontResend = null;
654 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700655 }
656 }).setOnCancelListener(new OnCancelListener() {
657 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500658 if (mDontResend != null) {
659 mDontResend.sendToTarget();
660 mResend = null;
661 mDontResend = null;
662 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700663 }
664 }).show();
665 }
666
667 /**
668 * Insert the url into the visited history database.
669 * @param url The url to be inserted.
670 * @param isReload True if this url is being reloaded.
671 * FIXME: Not sure what to do when reloading the page.
672 */
673 @Override
674 public void doUpdateVisitedHistory(WebView view, String url,
675 boolean isReload) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500676 // Don't save anything in private browsing mode
677 if (getWebView().isPrivateBrowsingEnabled()) return;
678
Grace Kloba22ac16e2009-10-07 18:00:23 -0700679 if (url.regionMatches(true, 0, "about:", 0, 6)) {
680 return;
681 }
682 // remove "client" before updating it to the history so that it wont
683 // show up in the auto-complete list.
684 int index = url.indexOf("client=ms-");
685 if (index > 0 && url.contains(".google.")) {
686 int end = url.indexOf('&', index);
687 if (end > 0) {
688 url = url.substring(0, index)
689 .concat(url.substring(end + 1));
690 } else {
691 // the url.charAt(index-1) should be either '?' or '&'
692 url = url.substring(0, index-1);
693 }
694 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400695 final ContentResolver cr = mActivity.getContentResolver();
696 final String newUrl = url;
697 new AsyncTask<Void, Void, Void>() {
Michael Kolbfe251992010-07-08 15:41:55 -0700698 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400699 protected Void doInBackground(Void... unused) {
700 Browser.updateVisitedHistory(cr, newUrl, true);
701 return null;
702 }
703 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700704 WebIconDatabase.getInstance().retainIconForPageUrl(url);
705 }
706
707 /**
708 * Displays SSL error(s) dialog to the user.
709 */
710 @Override
711 public void onReceivedSslError(final WebView view,
712 final SslErrorHandler handler, final SslError error) {
713 if (!mInForeground) {
714 handler.cancel();
715 return;
716 }
717 if (BrowserSettings.getInstance().showSecurityWarnings()) {
718 final LayoutInflater factory =
719 LayoutInflater.from(mActivity);
720 final View warningsView =
721 factory.inflate(R.layout.ssl_warnings, null);
722 final LinearLayout placeholder =
723 (LinearLayout)warningsView.findViewById(R.id.placeholder);
724
725 if (error.hasError(SslError.SSL_UNTRUSTED)) {
726 LinearLayout ll = (LinearLayout)factory
727 .inflate(R.layout.ssl_warning, null);
728 ((TextView)ll.findViewById(R.id.warning))
729 .setText(R.string.ssl_untrusted);
730 placeholder.addView(ll);
731 }
732
733 if (error.hasError(SslError.SSL_IDMISMATCH)) {
734 LinearLayout ll = (LinearLayout)factory
735 .inflate(R.layout.ssl_warning, null);
736 ((TextView)ll.findViewById(R.id.warning))
737 .setText(R.string.ssl_mismatch);
738 placeholder.addView(ll);
739 }
740
741 if (error.hasError(SslError.SSL_EXPIRED)) {
742 LinearLayout ll = (LinearLayout)factory
743 .inflate(R.layout.ssl_warning, null);
744 ((TextView)ll.findViewById(R.id.warning))
745 .setText(R.string.ssl_expired);
746 placeholder.addView(ll);
747 }
748
749 if (error.hasError(SslError.SSL_NOTYETVALID)) {
750 LinearLayout ll = (LinearLayout)factory
751 .inflate(R.layout.ssl_warning, null);
752 ((TextView)ll.findViewById(R.id.warning))
753 .setText(R.string.ssl_not_yet_valid);
754 placeholder.addView(ll);
755 }
756
757 new AlertDialog.Builder(mActivity).setTitle(
758 R.string.security_warning).setIcon(
759 android.R.drawable.ic_dialog_alert).setView(
760 warningsView).setPositiveButton(R.string.ssl_continue,
761 new DialogInterface.OnClickListener() {
762 public void onClick(DialogInterface dialog,
763 int whichButton) {
764 handler.proceed();
765 }
766 }).setNeutralButton(R.string.view_certificate,
767 new DialogInterface.OnClickListener() {
768 public void onClick(DialogInterface dialog,
769 int whichButton) {
770 mActivity.showSSLCertificateOnError(view,
771 handler, error);
772 }
773 }).setNegativeButton(R.string.cancel,
774 new DialogInterface.OnClickListener() {
775 public void onClick(DialogInterface dialog,
776 int whichButton) {
777 handler.cancel();
778 mActivity.resetTitleAndRevertLockIcon();
779 }
780 }).setOnCancelListener(
781 new DialogInterface.OnCancelListener() {
782 public void onCancel(DialogInterface dialog) {
783 handler.cancel();
784 mActivity.resetTitleAndRevertLockIcon();
785 }
786 }).show();
787 } else {
788 handler.proceed();
789 }
790 }
791
792 /**
793 * Handles an HTTP authentication request.
794 *
795 * @param handler The authentication handler
796 * @param host The host
797 * @param realm The realm
798 */
799 @Override
800 public void onReceivedHttpAuthRequest(WebView view,
801 final HttpAuthHandler handler, final String host,
802 final String realm) {
803 String username = null;
804 String password = null;
805
806 boolean reuseHttpAuthUsernamePassword = handler
807 .useHttpAuthUsernamePassword();
808
Steve Block95a53b22010-03-25 17:24:58 +0000809 if (reuseHttpAuthUsernamePassword && view != null) {
810 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700811 host, realm);
812 if (credentials != null && credentials.length == 2) {
813 username = credentials[0];
814 password = credentials[1];
815 }
816 }
817
818 if (username != null && password != null) {
819 handler.proceed(username, password);
820 } else {
821 if (mInForeground) {
822 mActivity.showHttpAuthentication(handler, host, realm,
823 null, null, null, 0);
824 } else {
825 handler.cancel();
826 }
827 }
828 }
829
830 @Override
831 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
832 if (!mInForeground) {
833 return false;
834 }
835 if (mActivity.isMenuDown()) {
836 // only check shortcut key when MENU is held
837 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
838 event);
839 } else {
840 return false;
841 }
842 }
843
844 @Override
845 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400846 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700847 return;
848 }
849 if (event.isDown()) {
850 mActivity.onKeyDown(event.getKeyCode(), event);
851 } else {
852 mActivity.onKeyUp(event.getKeyCode(), event);
853 }
854 }
855 };
856
857 // -------------------------------------------------------------------------
858 // WebChromeClient implementation for the main WebView
859 // -------------------------------------------------------------------------
860
861 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
862 // Helper method to create a new tab or sub window.
863 private void createWindow(final boolean dialog, final Message msg) {
864 WebView.WebViewTransport transport =
865 (WebView.WebViewTransport) msg.obj;
866 if (dialog) {
867 createSubWindow();
868 mActivity.attachSubWindow(Tab.this);
869 transport.setWebView(mSubView);
870 } else {
871 final Tab newTab = mActivity.openTabAndShow(
872 BrowserActivity.EMPTY_URL_DATA, false, null);
873 if (newTab != Tab.this) {
874 Tab.this.addChildTab(newTab);
875 }
876 transport.setWebView(newTab.getWebView());
877 }
878 msg.sendToTarget();
879 }
880
881 @Override
882 public boolean onCreateWindow(WebView view, final boolean dialog,
883 final boolean userGesture, final Message resultMsg) {
884 // only allow new window or sub window for the foreground case
885 if (!mInForeground) {
886 return false;
887 }
888 // Short-circuit if we can't create any more tabs or sub windows.
889 if (dialog && mSubView != null) {
890 new AlertDialog.Builder(mActivity)
891 .setTitle(R.string.too_many_subwindows_dialog_title)
892 .setIcon(android.R.drawable.ic_dialog_alert)
893 .setMessage(R.string.too_many_subwindows_dialog_message)
894 .setPositiveButton(R.string.ok, null)
895 .show();
896 return false;
897 } else if (!mActivity.getTabControl().canCreateNewTab()) {
898 new AlertDialog.Builder(mActivity)
899 .setTitle(R.string.too_many_windows_dialog_title)
900 .setIcon(android.R.drawable.ic_dialog_alert)
901 .setMessage(R.string.too_many_windows_dialog_message)
902 .setPositiveButton(R.string.ok, null)
903 .show();
904 return false;
905 }
906
907 // Short-circuit if this was a user gesture.
908 if (userGesture) {
909 createWindow(dialog, resultMsg);
910 return true;
911 }
912
913 // Allow the popup and create the appropriate window.
914 final AlertDialog.OnClickListener allowListener =
915 new AlertDialog.OnClickListener() {
916 public void onClick(DialogInterface d,
917 int which) {
918 createWindow(dialog, resultMsg);
919 }
920 };
921
922 // Block the popup by returning a null WebView.
923 final AlertDialog.OnClickListener blockListener =
924 new AlertDialog.OnClickListener() {
925 public void onClick(DialogInterface d, int which) {
926 resultMsg.sendToTarget();
927 }
928 };
929
930 // Build a confirmation dialog to display to the user.
931 final AlertDialog d =
932 new AlertDialog.Builder(mActivity)
933 .setTitle(R.string.attention)
934 .setIcon(android.R.drawable.ic_dialog_alert)
935 .setMessage(R.string.popup_window_attempt)
936 .setPositiveButton(R.string.allow, allowListener)
937 .setNegativeButton(R.string.block, blockListener)
938 .setCancelable(false)
939 .create();
940
941 // Show the confirmation dialog.
942 d.show();
943 return true;
944 }
945
946 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500947 public void onRequestFocus(WebView view) {
948 if (!mInForeground) {
949 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
950 Tab.this));
951 }
952 }
953
954 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700955 public void onCloseWindow(WebView window) {
956 if (mParentTab != null) {
957 // JavaScript can only close popup window.
958 if (mInForeground) {
959 mActivity.switchToTab(mActivity.getTabControl()
960 .getTabIndex(mParentTab));
961 }
962 mActivity.closeTab(Tab.this);
963 }
964 }
965
966 @Override
967 public void onProgressChanged(WebView view, int newProgress) {
968 if (newProgress == 100) {
969 // sync cookies and cache promptly here.
970 CookieSyncManager.getInstance().sync();
971 }
972 if (mInForeground) {
973 mActivity.onProgressChanged(view, newProgress);
974 }
Michael Kolbfe251992010-07-08 15:41:55 -0700975 if (getTabChangeListener() != null) {
976 getTabChangeListener().onProgress(Tab.this, newProgress);
977 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700978 }
979
980 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500981 public void onReceivedTitle(WebView view, final String title) {
982 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700983 if (mInForeground) {
984 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500985 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700986 }
Michael Kolbfe251992010-07-08 15:41:55 -0700987 TabChangeListener tcl = getTabChangeListener();
988 if (tcl != null) {
989 tcl.onUrlAndTitle(Tab.this, pageUrl,title);
990 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500991 if (pageUrl == null || pageUrl.length()
992 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700993 return;
994 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500995
996 // Update the title in the history database if not in private browsing mode
997 if (!getWebView().isPrivateBrowsingEnabled()) {
998 new AsyncTask<Void, Void, Void>() {
999 @Override
1000 protected Void doInBackground(Void... unused) {
1001 // See if we can find the current url in our history
1002 // database and add the new title to it.
1003 String url = pageUrl;
1004 if (url.startsWith("http://www.")) {
1005 url = url.substring(11);
1006 } else if (url.startsWith("http://")) {
1007 url = url.substring(4);
1008 }
1009 // Escape wildcards for LIKE operator.
1010 url = url.replace("\\", "\\\\").replace("%", "\\%")
1011 .replace("_", "\\_");
1012 Cursor c = null;
1013 try {
1014 final ContentResolver cr = mActivity.getContentResolver();
1015 String selection = History.URL + " LIKE ? ESCAPE '\\'";
1016 String [] selectionArgs = new String[] { "%" + url };
1017 ContentValues values = new ContentValues();
1018 values.put(History.TITLE, title);
1019 cr.update(History.CONTENT_URI, values, selection, selectionArgs);
1020 } catch (IllegalStateException e) {
1021 Log.e(LOGTAG, "Tab onReceived title", e);
1022 } catch (SQLiteException ex) {
1023 Log.e(LOGTAG,
1024 "onReceivedTitle() caught SQLiteException: ",
1025 ex);
1026 } finally {
1027 if (c != null) c.close();
1028 }
1029 return null;
Leon Scroggins21d9b902010-03-11 09:33:11 -05001030 }
Jeff Hamilton47654f42010-09-07 09:57:51 -05001031 }.execute();
1032 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001033 }
1034
1035 @Override
1036 public void onReceivedIcon(WebView view, Bitmap icon) {
1037 if (icon != null) {
Jeff Hamilton1a805652010-09-07 12:36:30 -07001038 Bookmarks.updateFavicon(mActivity
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 .getContentResolver(), view.getOriginalUrl(), view
1040 .getUrl(), icon);
1041 }
1042 if (mInForeground) {
1043 mActivity.setFavicon(icon);
1044 }
Michael Kolbfe251992010-07-08 15:41:55 -07001045 if (getTabChangeListener() != null) {
1046 getTabChangeListener().onFavicon(Tab.this, icon);
1047 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001048 }
1049
1050 @Override
1051 public void onReceivedTouchIconUrl(WebView view, String url,
1052 boolean precomposed) {
1053 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001054 // Let precomposed icons take precedence over non-composed
1055 // icons.
1056 if (precomposed && mTouchIconLoader != null) {
1057 mTouchIconLoader.cancel(false);
1058 mTouchIconLoader = null;
1059 }
1060 // Have only one async task at a time.
1061 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001062 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001063 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 }
1065 }
1066
1067 @Override
1068 public void onShowCustomView(View view,
1069 WebChromeClient.CustomViewCallback callback) {
1070 if (mInForeground) mActivity.onShowCustomView(view, callback);
1071 }
1072
1073 @Override
1074 public void onHideCustomView() {
1075 if (mInForeground) mActivity.onHideCustomView();
1076 }
1077
1078 /**
1079 * The origin has exceeded its database quota.
1080 * @param url the URL that exceeded the quota
1081 * @param databaseIdentifier the identifier of the database on which the
1082 * transaction that caused the quota overflow was run
1083 * @param currentQuota the current quota for the origin.
1084 * @param estimatedSize the estimated size of the database.
1085 * @param totalUsedQuota is the sum of all origins' quota.
1086 * @param quotaUpdater The callback to run when a decision to allow or
1087 * deny quota has been made. Don't forget to call this!
1088 */
1089 @Override
1090 public void onExceededDatabaseQuota(String url,
1091 String databaseIdentifier, long currentQuota, long estimatedSize,
1092 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1093 BrowserSettings.getInstance().getWebStorageSizeManager()
1094 .onExceededDatabaseQuota(url, databaseIdentifier,
1095 currentQuota, estimatedSize, totalUsedQuota,
1096 quotaUpdater);
1097 }
1098
1099 /**
1100 * The Application Cache has exceeded its max size.
1101 * @param spaceNeeded is the amount of disk space that would be needed
1102 * in order for the last appcache operation to succeed.
1103 * @param totalUsedQuota is the sum of all origins' quota.
1104 * @param quotaUpdater A callback to inform the WebCore thread that a
1105 * new app cache size is available. This callback must always
1106 * be executed at some point to ensure that the sleeping
1107 * WebCore thread is woken up.
1108 */
1109 @Override
1110 public void onReachedMaxAppCacheSize(long spaceNeeded,
1111 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1112 BrowserSettings.getInstance().getWebStorageSizeManager()
1113 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1114 quotaUpdater);
1115 }
1116
1117 /**
1118 * Instructs the browser to show a prompt to ask the user to set the
1119 * Geolocation permission state for the specified origin.
1120 * @param origin The origin for which Geolocation permissions are
1121 * requested.
1122 * @param callback The callback to call once the user has set the
1123 * Geolocation permission state.
1124 */
1125 @Override
1126 public void onGeolocationPermissionsShowPrompt(String origin,
1127 GeolocationPermissions.Callback callback) {
1128 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001129 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001130 }
1131 }
1132
1133 /**
1134 * Instructs the browser to hide the Geolocation permissions prompt.
1135 */
1136 @Override
1137 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001138 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001139 mGeolocationPermissionsPrompt.hide();
1140 }
1141 }
1142
Ben Murdoch65acc352009-11-19 18:16:04 +00001143 /* Adds a JavaScript error message to the system log and if the JS
1144 * console is enabled in the about:debug options, to that console
1145 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001146 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001147 */
1148 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001149 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001150 if (mInForeground) {
1151 // call getErrorConsole(true) so it will create one if needed
1152 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001153 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001154 if (mActivity.shouldShowErrorConsole()
1155 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1156 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1157 }
1158 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001159
Jeff Hamilton47654f42010-09-07 09:57:51 -05001160 // Don't log console messages in private browsing mode
1161 if (getWebView().isPrivateBrowsingEnabled()) return true;
1162
Ben Murdochc42addf2010-01-28 15:19:59 +00001163 String message = "Console: " + consoleMessage.message() + " "
1164 + consoleMessage.sourceId() + ":"
1165 + consoleMessage.lineNumber();
1166
1167 switch (consoleMessage.messageLevel()) {
1168 case TIP:
1169 Log.v(CONSOLE_LOGTAG, message);
1170 break;
1171 case LOG:
1172 Log.i(CONSOLE_LOGTAG, message);
1173 break;
1174 case WARNING:
1175 Log.w(CONSOLE_LOGTAG, message);
1176 break;
1177 case ERROR:
1178 Log.e(CONSOLE_LOGTAG, message);
1179 break;
1180 case DEBUG:
1181 Log.d(CONSOLE_LOGTAG, message);
1182 break;
1183 }
1184
1185 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001186 }
1187
1188 /**
1189 * Ask the browser for an icon to represent a <video> element.
1190 * This icon will be used if the Web page did not specify a poster attribute.
1191 * @return Bitmap The icon or null if no such icon is available.
1192 */
1193 @Override
1194 public Bitmap getDefaultVideoPoster() {
1195 if (mInForeground) {
1196 return mActivity.getDefaultVideoPoster();
1197 }
1198 return null;
1199 }
1200
1201 /**
1202 * Ask the host application for a custom progress view to show while
1203 * a <video> is loading.
1204 * @return View The progress view.
1205 */
1206 @Override
1207 public View getVideoLoadingProgressView() {
1208 if (mInForeground) {
1209 return mActivity.getVideoLoadingProgressView();
1210 }
1211 return null;
1212 }
1213
1214 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001215 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001216 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001217 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001218 } else {
1219 uploadMsg.onReceiveValue(null);
1220 }
1221 }
1222
1223 /**
1224 * Deliver a list of already-visited URLs
1225 */
1226 @Override
1227 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1228 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
Michael Kolbfe251992010-07-08 15:41:55 -07001229 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001230 public String[] doInBackground(Void... unused) {
1231 return Browser.getVisitedHistory(mActivity
1232 .getContentResolver());
1233 }
Michael Kolbfe251992010-07-08 15:41:55 -07001234 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001235 public void onPostExecute(String[] result) {
1236 callback.onReceiveValue(result);
1237 };
1238 };
1239 task.execute();
1240 };
1241 };
1242
1243 // -------------------------------------------------------------------------
1244 // WebViewClient implementation for the sub window
1245 // -------------------------------------------------------------------------
1246
1247 // Subclass of WebViewClient used in subwindows to notify the main
1248 // WebViewClient of certain WebView activities.
1249 private static class SubWindowClient extends WebViewClient {
1250 // The main WebViewClient.
1251 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001252 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001253
Leon Scroggins III211ba542010-04-19 13:21:13 -04001254 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001255 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001256 mBrowserActivity = activity;
1257 }
1258 @Override
1259 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1260 // Unlike the others, do not call mClient's version, which would
1261 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001262 // find or select dialog.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001263 mBrowserActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001264 }
1265 @Override
1266 public void doUpdateVisitedHistory(WebView view, String url,
1267 boolean isReload) {
1268 mClient.doUpdateVisitedHistory(view, url, isReload);
1269 }
1270 @Override
1271 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1272 return mClient.shouldOverrideUrlLoading(view, url);
1273 }
1274 @Override
1275 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1276 SslError error) {
1277 mClient.onReceivedSslError(view, handler, error);
1278 }
1279 @Override
1280 public void onReceivedHttpAuthRequest(WebView view,
1281 HttpAuthHandler handler, String host, String realm) {
1282 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1283 }
1284 @Override
1285 public void onFormResubmission(WebView view, Message dontResend,
1286 Message resend) {
1287 mClient.onFormResubmission(view, dontResend, resend);
1288 }
1289 @Override
1290 public void onReceivedError(WebView view, int errorCode,
1291 String description, String failingUrl) {
1292 mClient.onReceivedError(view, errorCode, description, failingUrl);
1293 }
1294 @Override
1295 public boolean shouldOverrideKeyEvent(WebView view,
1296 android.view.KeyEvent event) {
1297 return mClient.shouldOverrideKeyEvent(view, event);
1298 }
1299 @Override
1300 public void onUnhandledKeyEvent(WebView view,
1301 android.view.KeyEvent event) {
1302 mClient.onUnhandledKeyEvent(view, event);
1303 }
1304 }
1305
1306 // -------------------------------------------------------------------------
1307 // WebChromeClient implementation for the sub window
1308 // -------------------------------------------------------------------------
1309
1310 private class SubWindowChromeClient extends WebChromeClient {
1311 // The main WebChromeClient.
1312 private final WebChromeClient mClient;
1313
1314 SubWindowChromeClient(WebChromeClient client) {
1315 mClient = client;
1316 }
1317 @Override
1318 public void onProgressChanged(WebView view, int newProgress) {
1319 mClient.onProgressChanged(view, newProgress);
1320 }
1321 @Override
1322 public boolean onCreateWindow(WebView view, boolean dialog,
1323 boolean userGesture, android.os.Message resultMsg) {
1324 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1325 }
1326 @Override
1327 public void onCloseWindow(WebView window) {
1328 if (window != mSubView) {
1329 Log.e(LOGTAG, "Can't close the window");
1330 }
1331 mActivity.dismissSubWindow(Tab.this);
1332 }
1333 }
1334
1335 // -------------------------------------------------------------------------
1336
1337 // Construct a new tab
1338 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1339 String url) {
1340 mActivity = activity;
1341 mCloseOnExit = closeOnExit;
1342 mAppId = appId;
1343 mOriginalUrl = url;
1344 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1345 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1346 mInLoad = false;
1347 mInForeground = false;
1348
1349 mInflateService = LayoutInflater.from(activity);
1350
1351 // The tab consists of a container view, which contains the main
1352 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001353 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001354
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001355 mDownloadListener = new DownloadListener() {
1356 public void onDownloadStart(String url, String userAgent,
1357 String contentDisposition, String mimetype,
1358 long contentLength) {
1359 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1360 mimetype, contentLength);
1361 if (mMainView.copyBackForwardList().getSize() == 0) {
1362 // This Tab was opened for the sole purpose of downloading a
1363 // file. Remove it.
1364 if (mActivity.getTabControl().getCurrentWebView()
1365 == mMainView) {
1366 // In this case, the Tab is still on top.
1367 mActivity.goBackOnePageOrQuit();
1368 } else {
1369 // In this case, it is not.
1370 mActivity.closeTab(Tab.this);
1371 }
1372 }
1373 }
1374 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001375 mWebBackForwardListClient = new WebBackForwardListClient() {
1376 @Override
1377 public void onNewHistoryItem(WebHistoryItem item) {
1378 if (isInVoiceSearchMode()) {
1379 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1380 }
1381 }
1382 @Override
1383 public void onIndexChanged(WebHistoryItem item, int index) {
1384 Object data = item.getCustomData();
1385 if (data != null && data instanceof Intent) {
1386 activateVoiceSearchMode((Intent) data);
1387 }
1388 }
1389 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001390
Grace Kloba22ac16e2009-10-07 18:00:23 -07001391 setWebView(w);
1392 }
1393
1394 /**
1395 * Sets the WebView for this tab, correctly removing the old WebView from
1396 * the container view.
1397 */
1398 void setWebView(WebView w) {
1399 if (mMainView == w) {
1400 return;
1401 }
1402 // If the WebView is changing, the page will be reloaded, so any ongoing
1403 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001404 if (mGeolocationPermissionsPrompt != null) {
1405 mGeolocationPermissionsPrompt.hide();
1406 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001407
1408 // Just remove the old one.
1409 FrameLayout wrapper =
1410 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1411 wrapper.removeView(mMainView);
1412
1413 // set the new one
1414 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001415 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001416 if (mMainView != null) {
1417 mMainView.setWebViewClient(mWebViewClient);
1418 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001419 // Attach DownloadManager so that downloads can start in an active
1420 // or a non-active window. This can happen when going to a site that
1421 // does a redirect after a period of time. The user could have
1422 // switched to another tab while waiting for the download to start.
1423 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001424 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001425 }
1426 }
1427
1428 /**
1429 * Destroy the tab's main WebView and subWindow if any
1430 */
1431 void destroy() {
1432 if (mMainView != null) {
1433 dismissSubWindow();
1434 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1435 // save the WebView to call destroy() after detach it from the tab
1436 WebView webView = mMainView;
1437 setWebView(null);
1438 webView.destroy();
1439 }
1440 }
1441
1442 /**
1443 * Remove the tab from the parent
1444 */
1445 void removeFromTree() {
1446 // detach the children
1447 if (mChildTabs != null) {
1448 for(Tab t : mChildTabs) {
1449 t.setParentTab(null);
1450 }
1451 }
1452 // remove itself from the parent list
1453 if (mParentTab != null) {
1454 mParentTab.mChildTabs.remove(this);
1455 }
1456 }
1457
1458 /**
1459 * Create a new subwindow unless a subwindow already exists.
1460 * @return True if a new subwindow was created. False if one already exists.
1461 */
1462 boolean createSubWindow() {
1463 if (mSubView == null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001464 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001465 mSubViewContainer = mInflateService.inflate(
1466 R.layout.browser_subwindow, null);
1467 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001468 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001469 // use trackball directly
1470 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001471 // Enable the built-in zoom
1472 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001473 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1474 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001475 mSubView.setWebChromeClient(new SubWindowChromeClient(
1476 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001477 // Set a different DownloadListener for the mSubView, since it will
1478 // just need to dismiss the mSubView, rather than close the Tab
1479 mSubView.setDownloadListener(new DownloadListener() {
1480 public void onDownloadStart(String url, String userAgent,
1481 String contentDisposition, String mimetype,
1482 long contentLength) {
1483 mActivity.onDownloadStart(url, userAgent,
1484 contentDisposition, mimetype, contentLength);
1485 if (mSubView.copyBackForwardList().getSize() == 0) {
1486 // This subwindow was opened for the sole purpose of
1487 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001488 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001489 }
1490 }
1491 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001492 mSubView.setOnCreateContextMenuListener(mActivity);
1493 final BrowserSettings s = BrowserSettings.getInstance();
1494 s.addObserver(mSubView.getSettings()).update(s, null);
1495 final ImageButton cancel = (ImageButton) mSubViewContainer
1496 .findViewById(R.id.subwindow_close);
1497 cancel.setOnClickListener(new OnClickListener() {
1498 public void onClick(View v) {
1499 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1500 }
1501 });
1502 return true;
1503 }
1504 return false;
1505 }
1506
1507 /**
1508 * Dismiss the subWindow for the tab.
1509 */
1510 void dismissSubWindow() {
1511 if (mSubView != null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001512 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001513 BrowserSettings.getInstance().deleteObserver(
1514 mSubView.getSettings());
1515 mSubView.destroy();
1516 mSubView = null;
1517 mSubViewContainer = null;
1518 }
1519 }
1520
1521 /**
1522 * Attach the sub window to the content view.
1523 */
1524 void attachSubWindow(ViewGroup content) {
1525 if (mSubView != null) {
1526 content.addView(mSubViewContainer,
1527 BrowserActivity.COVER_SCREEN_PARAMS);
1528 }
1529 }
1530
1531 /**
1532 * Remove the sub window from the content view.
1533 */
1534 void removeSubWindow(ViewGroup content) {
1535 if (mSubView != null) {
1536 content.removeView(mSubViewContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001537 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001538 }
1539 }
1540
1541 /**
1542 * This method attaches both the WebView and any sub window to the
1543 * given content view.
1544 */
1545 void attachTabToContentView(ViewGroup content) {
1546 if (mMainView == null) {
1547 return;
1548 }
1549
1550 // Attach the WebView to the container and then attach the
1551 // container to the content view.
1552 FrameLayout wrapper =
1553 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001554 ViewGroup parent = (ViewGroup) mMainView.getParent();
1555 if (parent != wrapper) {
1556 if (parent != null) {
1557 Log.w(LOGTAG, "mMainView already has a parent in"
1558 + " attachTabToContentView!");
1559 parent.removeView(mMainView);
1560 }
1561 wrapper.addView(mMainView);
1562 } else {
1563 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1564 + " attachTabToContentView!");
1565 }
1566 parent = (ViewGroup) mContainer.getParent();
1567 if (parent != content) {
1568 if (parent != null) {
1569 Log.w(LOGTAG, "mContainer already has a parent in"
1570 + " attachTabToContentView!");
1571 parent.removeView(mContainer);
1572 }
1573 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1574 } else {
1575 Log.w(LOGTAG, "mContainer is already attached to content in"
1576 + " attachTabToContentView!");
1577 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001578 attachSubWindow(content);
1579 }
1580
1581 /**
1582 * Remove the WebView and any sub window from the given content view.
1583 */
1584 void removeTabFromContentView(ViewGroup content) {
1585 if (mMainView == null) {
1586 return;
1587 }
1588
1589 // Remove the container from the content and then remove the
1590 // WebView from the container. This will trigger a focus change
1591 // needed by WebView.
1592 FrameLayout wrapper =
1593 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1594 wrapper.removeView(mMainView);
1595 content.removeView(mContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001596 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001597 removeSubWindow(content);
1598 }
1599
1600 /**
1601 * Set the parent tab of this tab.
1602 */
1603 void setParentTab(Tab parent) {
1604 mParentTab = parent;
1605 // This tab may have been freed due to low memory. If that is the case,
1606 // the parent tab index is already saved. If we are changing that index
1607 // (most likely due to removing the parent tab) we must update the
1608 // parent tab index in the saved Bundle.
1609 if (mSavedState != null) {
1610 if (parent == null) {
1611 mSavedState.remove(PARENTTAB);
1612 } else {
1613 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1614 .getTabIndex(parent));
1615 }
1616 }
1617 }
1618
1619 /**
1620 * When a Tab is created through the content of another Tab, then we
1621 * associate the Tabs.
1622 * @param child the Tab that was created from this Tab
1623 */
1624 void addChildTab(Tab child) {
1625 if (mChildTabs == null) {
1626 mChildTabs = new Vector<Tab>();
1627 }
1628 mChildTabs.add(child);
1629 child.setParentTab(this);
1630 }
1631
1632 Vector<Tab> getChildTabs() {
1633 return mChildTabs;
1634 }
1635
1636 void resume() {
1637 if (mMainView != null) {
1638 mMainView.onResume();
1639 if (mSubView != null) {
1640 mSubView.onResume();
1641 }
1642 }
1643 }
1644
1645 void pause() {
1646 if (mMainView != null) {
1647 mMainView.onPause();
1648 if (mSubView != null) {
1649 mSubView.onPause();
1650 }
1651 }
1652 }
1653
1654 void putInForeground() {
1655 mInForeground = true;
1656 resume();
1657 mMainView.setOnCreateContextMenuListener(mActivity);
1658 if (mSubView != null) {
1659 mSubView.setOnCreateContextMenuListener(mActivity);
1660 }
1661 // Show the pending error dialog if the queue is not empty
1662 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1663 showError(mQueuedErrors.getFirst());
1664 }
1665 }
1666
1667 void putInBackground() {
1668 mInForeground = false;
1669 pause();
1670 mMainView.setOnCreateContextMenuListener(null);
1671 if (mSubView != null) {
1672 mSubView.setOnCreateContextMenuListener(null);
1673 }
1674 }
1675
1676 /**
1677 * Return the top window of this tab; either the subwindow if it is not
1678 * null or the main window.
1679 * @return The top window of this tab.
1680 */
1681 WebView getTopWindow() {
1682 if (mSubView != null) {
1683 return mSubView;
1684 }
1685 return mMainView;
1686 }
1687
1688 /**
1689 * Return the main window of this tab. Note: if a tab is freed in the
1690 * background, this can return null. It is only guaranteed to be
1691 * non-null for the current tab.
1692 * @return The main WebView of this tab.
1693 */
1694 WebView getWebView() {
1695 return mMainView;
1696 }
1697
1698 /**
1699 * Return the subwindow of this tab or null if there is no subwindow.
1700 * @return The subwindow of this tab or null.
1701 */
1702 WebView getSubWebView() {
1703 return mSubView;
1704 }
1705
1706 /**
1707 * @return The geolocation permissions prompt for this tab.
1708 */
1709 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001710 if (mGeolocationPermissionsPrompt == null) {
1711 ViewStub stub = (ViewStub) mContainer
1712 .findViewById(R.id.geolocation_permissions_prompt);
1713 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1714 .inflate();
1715 mGeolocationPermissionsPrompt.init();
1716 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001717 return mGeolocationPermissionsPrompt;
1718 }
1719
1720 /**
1721 * @return The application id string
1722 */
1723 String getAppId() {
1724 return mAppId;
1725 }
1726
1727 /**
1728 * Set the application id string
1729 * @param id
1730 */
1731 void setAppId(String id) {
1732 mAppId = id;
1733 }
1734
1735 /**
1736 * @return The original url associated with this Tab
1737 */
1738 String getOriginalUrl() {
1739 return mOriginalUrl;
1740 }
1741
1742 /**
1743 * Set the original url associated with this tab
1744 */
1745 void setOriginalUrl(String url) {
1746 mOriginalUrl = url;
1747 }
1748
1749 /**
1750 * Get the url of this tab. Valid after calling populatePickerData, but
1751 * before calling wipePickerData, or if the webview has been destroyed.
1752 * @return The WebView's url or null.
1753 */
1754 String getUrl() {
1755 if (mPickerData != null) {
1756 return mPickerData.mUrl;
1757 }
1758 return null;
1759 }
1760
1761 /**
1762 * Get the title of this tab. Valid after calling populatePickerData, but
1763 * before calling wipePickerData, or if the webview has been destroyed. If
1764 * the url has no title, use the url instead.
1765 * @return The WebView's title (or url) or null.
1766 */
1767 String getTitle() {
1768 if (mPickerData != null) {
1769 return mPickerData.mTitle;
1770 }
1771 return null;
1772 }
1773
1774 /**
1775 * Get the favicon of this tab. Valid after calling populatePickerData, but
1776 * before calling wipePickerData, or if the webview has been destroyed.
1777 * @return The WebView's favicon or null.
1778 */
1779 Bitmap getFavicon() {
1780 if (mPickerData != null) {
1781 return mPickerData.mFavicon;
1782 }
1783 return null;
1784 }
1785
1786 /**
1787 * Return the tab's error console. Creates the console if createIfNEcessary
1788 * is true and we haven't already created the console.
1789 * @param createIfNecessary Flag to indicate if the console should be
1790 * created if it has not been already.
1791 * @return The tab's error console, or null if one has not been created and
1792 * createIfNecessary is false.
1793 */
1794 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1795 if (createIfNecessary && mErrorConsole == null) {
1796 mErrorConsole = new ErrorConsoleView(mActivity);
1797 mErrorConsole.setWebView(mMainView);
1798 }
1799 return mErrorConsole;
1800 }
1801
1802 /**
1803 * If this Tab was created through another Tab, then this method returns
1804 * that Tab.
1805 * @return the Tab parent or null
1806 */
1807 public Tab getParentTab() {
1808 return mParentTab;
1809 }
1810
1811 /**
1812 * Return whether this tab should be closed when it is backing out of the
1813 * first page.
1814 * @return TRUE if this tab should be closed when exit.
1815 */
1816 boolean closeOnExit() {
1817 return mCloseOnExit;
1818 }
1819
1820 /**
1821 * Saves the current lock-icon state before resetting the lock icon. If we
1822 * have an error, we may need to roll back to the previous state.
1823 */
1824 void resetLockIcon(String url) {
1825 mPrevLockIconType = mLockIconType;
1826 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1827 if (URLUtil.isHttpsUrl(url)) {
1828 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1829 }
1830 }
1831
1832 /**
1833 * Reverts the lock-icon state to the last saved state, for example, if we
1834 * had an error, and need to cancel the load.
1835 */
1836 void revertLockIcon() {
1837 mLockIconType = mPrevLockIconType;
1838 }
1839
1840 /**
1841 * @return The tab's lock icon type.
1842 */
1843 int getLockIconType() {
1844 return mLockIconType;
1845 }
1846
1847 /**
1848 * @return TRUE if onPageStarted is called while onPageFinished is not
1849 * called yet.
1850 */
1851 boolean inLoad() {
1852 return mInLoad;
1853 }
1854
1855 // force mInLoad to be false. This should only be called before closing the
1856 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1857 void clearInLoad() {
1858 mInLoad = false;
1859 }
1860
1861 void populatePickerData() {
1862 if (mMainView == null) {
1863 populatePickerDataFromSavedState();
1864 return;
1865 }
1866
1867 // FIXME: The only place we cared about subwindow was for
1868 // bookmarking (i.e. not when saving state). Was this deliberate?
1869 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001870 if (list == null) {
1871 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1872 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001873 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1874 populatePickerData(item);
1875 }
1876
1877 // Populate the picker data using the given history item and the current top
1878 // WebView.
1879 private void populatePickerData(WebHistoryItem item) {
1880 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001881 if (item == null) {
1882 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1883 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001884 mPickerData.mUrl = item.getUrl();
1885 mPickerData.mTitle = item.getTitle();
1886 mPickerData.mFavicon = item.getFavicon();
1887 if (mPickerData.mTitle == null) {
1888 mPickerData.mTitle = mPickerData.mUrl;
1889 }
1890 }
1891 }
1892
1893 // Create the PickerData and populate it using the saved state of the tab.
1894 void populatePickerDataFromSavedState() {
1895 if (mSavedState == null) {
1896 return;
1897 }
1898 mPickerData = new PickerData();
1899 mPickerData.mUrl = mSavedState.getString(CURRURL);
1900 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1901 }
1902
1903 void clearPickerData() {
1904 mPickerData = null;
1905 }
1906
1907 /**
1908 * Get the saved state bundle.
1909 * @return
1910 */
1911 Bundle getSavedState() {
1912 return mSavedState;
1913 }
1914
1915 /**
1916 * Set the saved state.
1917 */
1918 void setSavedState(Bundle state) {
1919 mSavedState = state;
1920 }
1921
1922 /**
1923 * @return TRUE if succeed in saving the state.
1924 */
1925 boolean saveState() {
1926 // If the WebView is null it means we ran low on memory and we already
1927 // stored the saved state in mSavedState.
1928 if (mMainView == null) {
1929 return mSavedState != null;
1930 }
1931
1932 mSavedState = new Bundle();
1933 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001934
1935 // Store some extra info for displaying the tab in the picker.
1936 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1937 populatePickerData(item);
1938
1939 if (mPickerData.mUrl != null) {
1940 mSavedState.putString(CURRURL, mPickerData.mUrl);
1941 }
1942 if (mPickerData.mTitle != null) {
1943 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1944 }
1945 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1946 if (mAppId != null) {
1947 mSavedState.putString(APPID, mAppId);
1948 }
1949 if (mOriginalUrl != null) {
1950 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1951 }
1952 // Remember the parent tab so the relationship can be restored.
1953 if (mParentTab != null) {
1954 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1955 mParentTab));
1956 }
1957 return true;
1958 }
1959
1960 /*
1961 * Restore the state of the tab.
1962 */
1963 boolean restoreState(Bundle b) {
1964 if (b == null) {
1965 return false;
1966 }
1967 // Restore the internal state even if the WebView fails to restore.
1968 // This will maintain the app id, original url and close-on-exit values.
1969 mSavedState = null;
1970 mPickerData = null;
1971 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1972 mAppId = b.getString(APPID);
1973 mOriginalUrl = b.getString(ORIGINALURL);
1974
1975 final WebBackForwardList list = mMainView.restoreState(b);
1976 if (list == null) {
1977 return false;
1978 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001979 return true;
1980 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001981
Michael Kolbfe251992010-07-08 15:41:55 -07001982 /**
1983 * always get the TabChangeListener form the tab control
1984 * @return the TabControl change listener
1985 */
1986 private TabChangeListener getTabChangeListener() {
1987 return mActivity.getTabControl().getTabChangeListener();
1988 }
1989
Grace Kloba22ac16e2009-10-07 18:00:23 -07001990}