blob: 1d9482bdce1b8735a0aa7031889ba39d8d7ff423 [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
Grace Kloba22ac16e2009-10-07 18:00:23 -070019import android.app.AlertDialog;
Leon Scroggins58d56c62010-01-28 15:12:40 -050020import android.app.SearchManager;
Grace Kloba22ac16e2009-10-07 18:00:23 -070021import android.content.ContentResolver;
22import android.content.ContentValues;
23import android.content.DialogInterface;
Leon Scroggins58d56c62010-01-28 15:12:40 -050024import android.content.Intent;
Michael Kolbfe251992010-07-08 15:41:55 -070025import android.content.DialogInterface.OnCancelListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070026import android.database.Cursor;
27import android.database.sqlite.SQLiteDatabase;
28import android.database.sqlite.SQLiteException;
29import android.graphics.Bitmap;
30import android.net.Uri;
31import android.net.http.SslError;
32import android.os.AsyncTask;
33import android.os.Bundle;
34import android.os.Message;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +000035import android.os.SystemClock;
Grace Kloba22ac16e2009-10-07 18:00:23 -070036import android.provider.Browser;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050037import android.speech.RecognizerResultsIntent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070038import android.util.Log;
39import android.view.KeyEvent;
40import android.view.LayoutInflater;
41import android.view.View;
42import android.view.ViewGroup;
Grace Kloba50c241e2010-04-20 11:07:50 -070043import android.view.ViewStub;
Grace Kloba22ac16e2009-10-07 18:00:23 -070044import android.view.View.OnClickListener;
Ben Murdochc42addf2010-01-28 15:19:59 +000045import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070046import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050047import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070048import android.webkit.GeolocationPermissions;
49import android.webkit.HttpAuthHandler;
50import android.webkit.SslErrorHandler;
51import android.webkit.URLUtil;
52import android.webkit.ValueCallback;
53import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050054import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070055import android.webkit.WebChromeClient;
56import android.webkit.WebHistoryItem;
57import android.webkit.WebIconDatabase;
58import android.webkit.WebStorage;
59import android.webkit.WebView;
60import android.webkit.WebViewClient;
61import android.widget.FrameLayout;
62import android.widget.ImageButton;
63import android.widget.LinearLayout;
64import android.widget.TextView;
65
Michael Kolbfe251992010-07-08 15:41:55 -070066import com.android.browser.TabControl.TabChangeListener;
Leon Scroggins1fe13a52010-02-09 15:31:26 -050067import com.android.common.speech.LoggingEvents;
68
Michael Kolbfe251992010-07-08 15:41:55 -070069import java.io.File;
70import 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";
159
160 // -------------------------------------------------------------------------
161
Leon Scroggins58d56c62010-01-28 15:12:40 -0500162 /**
163 * Private information regarding the latest voice search. If the Tab is not
164 * in voice search mode, this will be null.
165 */
166 private VoiceSearchData mVoiceSearchData;
167 /**
168 * Return whether the tab is in voice search mode.
169 */
170 public boolean isInVoiceSearchMode() {
171 return mVoiceSearchData != null;
172 }
173 /**
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400174 * Return true if the Tab is in voice search mode and the voice search
175 * Intent came with a String identifying that Google provided the Intent.
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500176 */
177 public boolean voiceSearchSourceIsGoogle() {
178 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
179 }
180 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500181 * Get the title to display for the current voice search page. If the Tab
182 * is not in voice search mode, return null.
183 */
184 public String getVoiceDisplayTitle() {
185 if (mVoiceSearchData == null) return null;
186 return mVoiceSearchData.mLastVoiceSearchTitle;
187 }
188 /**
189 * Get the latest array of voice search results, to be passed to the
190 * BrowserProvider. If the Tab is not in voice search mode, return null.
191 */
192 public ArrayList<String> getVoiceSearchResults() {
193 if (mVoiceSearchData == null) return null;
194 return mVoiceSearchData.mVoiceSearchResults;
195 }
196 /**
197 * Activate voice search mode.
198 * @param intent Intent which has the results to use, or an index into the
199 * results when reusing the old results.
200 */
201 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500202 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500203 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500204 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500205 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500206 ArrayList<String> urls = intent.getStringArrayListExtra(
207 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
208 ArrayList<String> htmls = intent.getStringArrayListExtra(
209 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
210 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
211 RecognizerResultsIntent
212 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500213 // This tab is now entering voice search mode for the first time, or
214 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500215 int size = results.size();
216 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500217 throw new AssertionError("improper extras passed in Intent");
218 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500219 if (htmls == null || htmls.size() != size || baseUrls == null ||
220 (baseUrls.size() != size && baseUrls.size() != 1)) {
221 // If either of these arrays are empty/incorrectly sized, ignore
222 // them.
223 htmls = null;
224 baseUrls = null;
225 }
226 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
227 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500228 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
229 RecognizerResultsIntent
230 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500231 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
232 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400233 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500234 }
235 String extraData = intent.getStringExtra(
236 SearchManager.EXTRA_DATA_KEY);
237 if (extraData != null) {
238 index = Integer.parseInt(extraData);
239 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
240 throw new AssertionError("index must be less than "
241 + "size of mVoiceSearchResults");
242 }
243 if (mVoiceSearchData.mSourceIsGoogle) {
244 Intent logIntent = new Intent(
245 LoggingEvents.ACTION_LOG_EVENT);
246 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
247 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
248 logIntent.putExtra(
249 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
250 index);
251 mActivity.sendBroadcast(logIntent);
252 }
253 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400254 // Copy the Intent, so that each history item will have its own
255 // Intent, with different (or none) extra data.
256 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
257 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
258 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500259 }
260 }
261 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500262 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500263 if (mInForeground) {
264 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
265 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500266 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
267 // When index was found it was already ensured that it was valid
268 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
269 if (uriString != null) {
270 Uri dataUri = Uri.parse(uriString);
271 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
272 dataUri.getScheme())) {
273 // If there is only one base URL, use it. If there are
274 // more, there will be one for each index, so use the base
275 // URL corresponding to the index.
276 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
277 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
278 index : 0);
279 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
280 mMainView.loadDataWithBaseURL(baseUrl,
281 uriString.substring(RecognizerResultsIntent
282 .URI_SCHEME_INLINE.length() + 1), "text/html",
283 "utf-8", baseUrl);
284 return;
285 }
286 }
287 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500288 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500289 = mVoiceSearchData.mVoiceSearchUrls.get(index);
290 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
291 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
292 mVoiceSearchData.mLastVoiceSearchTitle);
293 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500294 Map<String, String> headers = null;
295 if (mVoiceSearchData.mHeaders != null) {
296 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
297 : index;
298 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
299 if (bundle != null && !bundle.isEmpty()) {
300 Iterator<String> iter = bundle.keySet().iterator();
301 headers = new HashMap<String, String>();
302 while (iter.hasNext()) {
303 String key = iter.next();
304 headers.put(key, bundle.getString(key));
305 }
306 }
307 }
308 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500309 }
310 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500311 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500312 ArrayList<String> urls, ArrayList<String> htmls,
313 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500314 mVoiceSearchResults = results;
315 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500316 mVoiceSearchHtmls = htmls;
317 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500318 }
319 /*
320 * ArrayList of suggestions to be displayed when opening the
321 * SearchManager
322 */
323 public ArrayList<String> mVoiceSearchResults;
324 /*
325 * ArrayList of urls, associated with the suggestions in
326 * mVoiceSearchResults.
327 */
328 public ArrayList<String> mVoiceSearchUrls;
329 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500330 * ArrayList holding content to load for each item in
331 * mVoiceSearchResults.
332 */
333 public ArrayList<String> mVoiceSearchHtmls;
334 /*
335 * ArrayList holding base urls for the items in mVoiceSearchResults.
336 * If non null, this will either have the same size as
337 * mVoiceSearchResults or have a size of 1, in which case all will use
338 * the same base url
339 */
340 public ArrayList<String> mVoiceSearchBaseUrls;
341 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500342 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500343 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500344 */
345 public String mLastVoiceSearchUrl;
346 /**
347 * The last title used for voice search. Needed to update the title bar
348 * when switching tabs.
349 */
350 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500351 /**
352 * Whether the Intent which turned on voice search mode contained the
353 * String signifying that Google was the source.
354 */
355 public boolean mSourceIsGoogle;
356 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500357 * List of headers to be passed into the WebView containing location
358 * information
359 */
360 public ArrayList<Bundle> mHeaders;
361 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500362 * The Intent used to invoke voice search. Placed on the
363 * WebHistoryItem so that when coming back to a previous voice search
364 * page we can again activate voice search.
365 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500366 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500367 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500368 * String used to identify Google as the source of voice search.
369 */
370 public static String SOURCE_IS_GOOGLE
371 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500372 }
373
Grace Kloba22ac16e2009-10-07 18:00:23 -0700374 // Container class for the next error dialog that needs to be displayed
375 private class ErrorDialog {
376 public final int mTitle;
377 public final String mDescription;
378 public final int mError;
379 ErrorDialog(int title, String desc, int error) {
380 mTitle = title;
381 mDescription = desc;
382 mError = error;
383 }
384 };
385
386 private void processNextError() {
387 if (mQueuedErrors == null) {
388 return;
389 }
390 // The first one is currently displayed so just remove it.
391 mQueuedErrors.removeFirst();
392 if (mQueuedErrors.size() == 0) {
393 mQueuedErrors = null;
394 return;
395 }
396 showError(mQueuedErrors.getFirst());
397 }
398
399 private DialogInterface.OnDismissListener mDialogListener =
400 new DialogInterface.OnDismissListener() {
401 public void onDismiss(DialogInterface d) {
402 processNextError();
403 }
404 };
405 private LinkedList<ErrorDialog> mQueuedErrors;
406
407 private void queueError(int err, String desc) {
408 if (mQueuedErrors == null) {
409 mQueuedErrors = new LinkedList<ErrorDialog>();
410 }
411 for (ErrorDialog d : mQueuedErrors) {
412 if (d.mError == err) {
413 // Already saw a similar error, ignore the new one.
414 return;
415 }
416 }
417 ErrorDialog errDialog = new ErrorDialog(
418 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
419 R.string.browserFrameFileErrorLabel :
420 R.string.browserFrameNetworkErrorLabel,
421 desc, err);
422 mQueuedErrors.addLast(errDialog);
423
424 // Show the dialog now if the queue was empty and it is in foreground
425 if (mQueuedErrors.size() == 1 && mInForeground) {
426 showError(errDialog);
427 }
428 }
429
430 private void showError(ErrorDialog errDialog) {
431 if (mInForeground) {
432 AlertDialog d = new AlertDialog.Builder(mActivity)
433 .setTitle(errDialog.mTitle)
434 .setMessage(errDialog.mDescription)
435 .setPositiveButton(R.string.ok, null)
436 .create();
437 d.setOnDismissListener(mDialogListener);
438 d.show();
439 }
440 }
441
442 // -------------------------------------------------------------------------
443 // WebViewClient implementation for the main WebView
444 // -------------------------------------------------------------------------
445
446 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500447 private Message mDontResend;
448 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700449 @Override
450 public void onPageStarted(WebView view, String url, Bitmap favicon) {
451 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000452 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500453 if (mVoiceSearchData != null
454 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500455 if (mVoiceSearchData.mSourceIsGoogle) {
456 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
457 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
458 mActivity.sendBroadcast(i);
459 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500460 mVoiceSearchData = null;
461 if (mInForeground) {
462 mActivity.revertVoiceTitleBar();
463 }
464 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700465
466 // We've started to load a new page. If there was a pending message
467 // to save a screenshot then we will now take the new page and save
468 // an incorrect screenshot. Therefore, remove any pending thumbnail
469 // messages from the queue.
470 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
471 view);
472
473 // If we start a touch icon load and then load a new page, we don't
474 // want to cancel the current touch icon loader. But, we do want to
475 // create a new one when the touch icon url is known.
476 if (mTouchIconLoader != null) {
477 mTouchIconLoader.mTab = null;
478 mTouchIconLoader = null;
479 }
480
481 // reset the error console
482 if (mErrorConsole != null) {
483 mErrorConsole.clearErrorMessages();
484 if (mActivity.shouldShowErrorConsole()) {
485 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
486 }
487 }
488
489 // update the bookmark database for favicon
490 if (favicon != null) {
491 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
Patrick Scottcc949122010-03-17 16:06:30 -0400492 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700493 }
494
495 // reset sync timer to avoid sync starts during loading a page
496 CookieSyncManager.getInstance().resetSync();
497
498 if (!mActivity.isNetworkUp()) {
499 view.setNetworkAvailable(false);
500 }
501
502 // finally update the UI in the activity if it is in the foreground
503 if (mInForeground) {
504 mActivity.onPageStarted(view, url, favicon);
505 }
Michael Kolbfe251992010-07-08 15:41:55 -0700506 if (getTabChangeListener() != null) {
507 getTabChangeListener().onPageStarted(Tab.this);
508 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700509 }
510
511 @Override
512 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000513 LogTag.logPageFinishedLoading(
514 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700515 mInLoad = false;
516
517 if (mInForeground && !mActivity.didUserStopLoading()
518 || !mInForeground) {
519 // Only update the bookmark screenshot if the user did not
520 // cancel the load early.
521 mActivity.postMessage(
522 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
523 500);
524 }
525
526 // finally update the UI in the activity if it is in the foreground
527 if (mInForeground) {
528 mActivity.onPageFinished(view, url);
529 }
Michael Kolbfe251992010-07-08 15:41:55 -0700530 if (getTabChangeListener() != null) {
531 getTabChangeListener().onPageFinished(Tab.this);
532 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700533 }
534
535 // return true if want to hijack the url to let another app to handle it
536 @Override
537 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400538 if (voiceSearchSourceIsGoogle()) {
539 // This method is called when the user clicks on a link.
540 // VoiceSearchMode is turned off when the user leaves the
541 // Google results page, so at this point the user must be on
542 // that page. If the user clicked a link on that page, assume
543 // that the voice search was effective, and broadcast an Intent
544 // so a receiver can take note of that fact.
545 Intent logIntent = new Intent(LoggingEvents.ACTION_LOG_EVENT);
546 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
547 LoggingEvents.VoiceSearch.RESULT_CLICKED);
548 mActivity.sendBroadcast(logIntent);
549 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700550 if (mInForeground) {
551 return mActivity.shouldOverrideUrlLoading(view, url);
552 } else {
553 return false;
554 }
555 }
556
557 /**
558 * Updates the lock icon. This method is called when we discover another
559 * resource to be loaded for this page (for example, javascript). While
560 * we update the icon type, we do not update the lock icon itself until
561 * we are done loading, it is slightly more secure this way.
562 */
563 @Override
564 public void onLoadResource(WebView view, String url) {
565 if (url != null && url.length() > 0) {
566 // It is only if the page claims to be secure that we may have
567 // to update the lock:
568 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
569 // If NOT a 'safe' url, change the lock to mixed content!
570 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
571 || URLUtil.isAboutUrl(url))) {
572 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
573 }
574 }
575 }
576 }
577
578 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700579 * Show a dialog informing the user of the network error reported by
580 * WebCore if it is in the foreground.
581 */
582 @Override
583 public void onReceivedError(WebView view, int errorCode,
584 String description, String failingUrl) {
585 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
586 errorCode != WebViewClient.ERROR_CONNECT &&
587 errorCode != WebViewClient.ERROR_BAD_URL &&
588 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
589 errorCode != WebViewClient.ERROR_FILE) {
590 queueError(errorCode, description);
591 }
592 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
593 + " " + description);
594
595 // We need to reset the title after an error if it is in foreground.
596 if (mInForeground) {
597 mActivity.resetTitleAndRevertLockIcon();
598 }
599 }
600
601 /**
602 * Check with the user if it is ok to resend POST data as the page they
603 * are trying to navigate to is the result of a POST.
604 */
605 @Override
606 public void onFormResubmission(WebView view, final Message dontResend,
607 final Message resend) {
608 if (!mInForeground) {
609 dontResend.sendToTarget();
610 return;
611 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500612 if (mDontResend != null) {
613 Log.w(LOGTAG, "onFormResubmission should not be called again "
614 + "while dialog is still up");
615 dontResend.sendToTarget();
616 return;
617 }
618 mDontResend = dontResend;
619 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700620 new AlertDialog.Builder(mActivity).setTitle(
621 R.string.browserFrameFormResubmitLabel).setMessage(
622 R.string.browserFrameFormResubmitMessage)
623 .setPositiveButton(R.string.ok,
624 new DialogInterface.OnClickListener() {
625 public void onClick(DialogInterface dialog,
626 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500627 if (mResend != null) {
628 mResend.sendToTarget();
629 mResend = null;
630 mDontResend = null;
631 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700632 }
633 }).setNegativeButton(R.string.cancel,
634 new DialogInterface.OnClickListener() {
635 public void onClick(DialogInterface dialog,
636 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500637 if (mDontResend != null) {
638 mDontResend.sendToTarget();
639 mResend = null;
640 mDontResend = null;
641 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700642 }
643 }).setOnCancelListener(new OnCancelListener() {
644 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500645 if (mDontResend != null) {
646 mDontResend.sendToTarget();
647 mResend = null;
648 mDontResend = null;
649 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700650 }
651 }).show();
652 }
653
654 /**
655 * Insert the url into the visited history database.
656 * @param url The url to be inserted.
657 * @param isReload True if this url is being reloaded.
658 * FIXME: Not sure what to do when reloading the page.
659 */
660 @Override
661 public void doUpdateVisitedHistory(WebView view, String url,
662 boolean isReload) {
663 if (url.regionMatches(true, 0, "about:", 0, 6)) {
664 return;
665 }
666 // remove "client" before updating it to the history so that it wont
667 // show up in the auto-complete list.
668 int index = url.indexOf("client=ms-");
669 if (index > 0 && url.contains(".google.")) {
670 int end = url.indexOf('&', index);
671 if (end > 0) {
672 url = url.substring(0, index)
673 .concat(url.substring(end + 1));
674 } else {
675 // the url.charAt(index-1) should be either '?' or '&'
676 url = url.substring(0, index-1);
677 }
678 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400679 final ContentResolver cr = mActivity.getContentResolver();
680 final String newUrl = url;
681 new AsyncTask<Void, Void, Void>() {
Michael Kolbfe251992010-07-08 15:41:55 -0700682 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400683 protected Void doInBackground(Void... unused) {
684 Browser.updateVisitedHistory(cr, newUrl, true);
685 return null;
686 }
687 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700688 WebIconDatabase.getInstance().retainIconForPageUrl(url);
689 }
690
691 /**
692 * Displays SSL error(s) dialog to the user.
693 */
694 @Override
695 public void onReceivedSslError(final WebView view,
696 final SslErrorHandler handler, final SslError error) {
697 if (!mInForeground) {
698 handler.cancel();
699 return;
700 }
701 if (BrowserSettings.getInstance().showSecurityWarnings()) {
702 final LayoutInflater factory =
703 LayoutInflater.from(mActivity);
704 final View warningsView =
705 factory.inflate(R.layout.ssl_warnings, null);
706 final LinearLayout placeholder =
707 (LinearLayout)warningsView.findViewById(R.id.placeholder);
708
709 if (error.hasError(SslError.SSL_UNTRUSTED)) {
710 LinearLayout ll = (LinearLayout)factory
711 .inflate(R.layout.ssl_warning, null);
712 ((TextView)ll.findViewById(R.id.warning))
713 .setText(R.string.ssl_untrusted);
714 placeholder.addView(ll);
715 }
716
717 if (error.hasError(SslError.SSL_IDMISMATCH)) {
718 LinearLayout ll = (LinearLayout)factory
719 .inflate(R.layout.ssl_warning, null);
720 ((TextView)ll.findViewById(R.id.warning))
721 .setText(R.string.ssl_mismatch);
722 placeholder.addView(ll);
723 }
724
725 if (error.hasError(SslError.SSL_EXPIRED)) {
726 LinearLayout ll = (LinearLayout)factory
727 .inflate(R.layout.ssl_warning, null);
728 ((TextView)ll.findViewById(R.id.warning))
729 .setText(R.string.ssl_expired);
730 placeholder.addView(ll);
731 }
732
733 if (error.hasError(SslError.SSL_NOTYETVALID)) {
734 LinearLayout ll = (LinearLayout)factory
735 .inflate(R.layout.ssl_warning, null);
736 ((TextView)ll.findViewById(R.id.warning))
737 .setText(R.string.ssl_not_yet_valid);
738 placeholder.addView(ll);
739 }
740
741 new AlertDialog.Builder(mActivity).setTitle(
742 R.string.security_warning).setIcon(
743 android.R.drawable.ic_dialog_alert).setView(
744 warningsView).setPositiveButton(R.string.ssl_continue,
745 new DialogInterface.OnClickListener() {
746 public void onClick(DialogInterface dialog,
747 int whichButton) {
748 handler.proceed();
749 }
750 }).setNeutralButton(R.string.view_certificate,
751 new DialogInterface.OnClickListener() {
752 public void onClick(DialogInterface dialog,
753 int whichButton) {
754 mActivity.showSSLCertificateOnError(view,
755 handler, error);
756 }
757 }).setNegativeButton(R.string.cancel,
758 new DialogInterface.OnClickListener() {
759 public void onClick(DialogInterface dialog,
760 int whichButton) {
761 handler.cancel();
762 mActivity.resetTitleAndRevertLockIcon();
763 }
764 }).setOnCancelListener(
765 new DialogInterface.OnCancelListener() {
766 public void onCancel(DialogInterface dialog) {
767 handler.cancel();
768 mActivity.resetTitleAndRevertLockIcon();
769 }
770 }).show();
771 } else {
772 handler.proceed();
773 }
774 }
775
776 /**
777 * Handles an HTTP authentication request.
778 *
779 * @param handler The authentication handler
780 * @param host The host
781 * @param realm The realm
782 */
783 @Override
784 public void onReceivedHttpAuthRequest(WebView view,
785 final HttpAuthHandler handler, final String host,
786 final String realm) {
787 String username = null;
788 String password = null;
789
790 boolean reuseHttpAuthUsernamePassword = handler
791 .useHttpAuthUsernamePassword();
792
Steve Block95a53b22010-03-25 17:24:58 +0000793 if (reuseHttpAuthUsernamePassword && view != null) {
794 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700795 host, realm);
796 if (credentials != null && credentials.length == 2) {
797 username = credentials[0];
798 password = credentials[1];
799 }
800 }
801
802 if (username != null && password != null) {
803 handler.proceed(username, password);
804 } else {
805 if (mInForeground) {
806 mActivity.showHttpAuthentication(handler, host, realm,
807 null, null, null, 0);
808 } else {
809 handler.cancel();
810 }
811 }
812 }
813
814 @Override
815 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
816 if (!mInForeground) {
817 return false;
818 }
819 if (mActivity.isMenuDown()) {
820 // only check shortcut key when MENU is held
821 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
822 event);
823 } else {
824 return false;
825 }
826 }
827
828 @Override
829 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400830 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700831 return;
832 }
833 if (event.isDown()) {
834 mActivity.onKeyDown(event.getKeyCode(), event);
835 } else {
836 mActivity.onKeyUp(event.getKeyCode(), event);
837 }
838 }
839 };
840
841 // -------------------------------------------------------------------------
842 // WebChromeClient implementation for the main WebView
843 // -------------------------------------------------------------------------
844
845 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
846 // Helper method to create a new tab or sub window.
847 private void createWindow(final boolean dialog, final Message msg) {
848 WebView.WebViewTransport transport =
849 (WebView.WebViewTransport) msg.obj;
850 if (dialog) {
851 createSubWindow();
852 mActivity.attachSubWindow(Tab.this);
853 transport.setWebView(mSubView);
854 } else {
855 final Tab newTab = mActivity.openTabAndShow(
856 BrowserActivity.EMPTY_URL_DATA, false, null);
857 if (newTab != Tab.this) {
858 Tab.this.addChildTab(newTab);
859 }
860 transport.setWebView(newTab.getWebView());
861 }
862 msg.sendToTarget();
863 }
864
865 @Override
866 public boolean onCreateWindow(WebView view, final boolean dialog,
867 final boolean userGesture, final Message resultMsg) {
868 // only allow new window or sub window for the foreground case
869 if (!mInForeground) {
870 return false;
871 }
872 // Short-circuit if we can't create any more tabs or sub windows.
873 if (dialog && mSubView != null) {
874 new AlertDialog.Builder(mActivity)
875 .setTitle(R.string.too_many_subwindows_dialog_title)
876 .setIcon(android.R.drawable.ic_dialog_alert)
877 .setMessage(R.string.too_many_subwindows_dialog_message)
878 .setPositiveButton(R.string.ok, null)
879 .show();
880 return false;
881 } else if (!mActivity.getTabControl().canCreateNewTab()) {
882 new AlertDialog.Builder(mActivity)
883 .setTitle(R.string.too_many_windows_dialog_title)
884 .setIcon(android.R.drawable.ic_dialog_alert)
885 .setMessage(R.string.too_many_windows_dialog_message)
886 .setPositiveButton(R.string.ok, null)
887 .show();
888 return false;
889 }
890
891 // Short-circuit if this was a user gesture.
892 if (userGesture) {
893 createWindow(dialog, resultMsg);
894 return true;
895 }
896
897 // Allow the popup and create the appropriate window.
898 final AlertDialog.OnClickListener allowListener =
899 new AlertDialog.OnClickListener() {
900 public void onClick(DialogInterface d,
901 int which) {
902 createWindow(dialog, resultMsg);
903 }
904 };
905
906 // Block the popup by returning a null WebView.
907 final AlertDialog.OnClickListener blockListener =
908 new AlertDialog.OnClickListener() {
909 public void onClick(DialogInterface d, int which) {
910 resultMsg.sendToTarget();
911 }
912 };
913
914 // Build a confirmation dialog to display to the user.
915 final AlertDialog d =
916 new AlertDialog.Builder(mActivity)
917 .setTitle(R.string.attention)
918 .setIcon(android.R.drawable.ic_dialog_alert)
919 .setMessage(R.string.popup_window_attempt)
920 .setPositiveButton(R.string.allow, allowListener)
921 .setNegativeButton(R.string.block, blockListener)
922 .setCancelable(false)
923 .create();
924
925 // Show the confirmation dialog.
926 d.show();
927 return true;
928 }
929
930 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500931 public void onRequestFocus(WebView view) {
932 if (!mInForeground) {
933 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
934 Tab.this));
935 }
936 }
937
938 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 public void onCloseWindow(WebView window) {
940 if (mParentTab != null) {
941 // JavaScript can only close popup window.
942 if (mInForeground) {
943 mActivity.switchToTab(mActivity.getTabControl()
944 .getTabIndex(mParentTab));
945 }
946 mActivity.closeTab(Tab.this);
947 }
948 }
949
950 @Override
951 public void onProgressChanged(WebView view, int newProgress) {
952 if (newProgress == 100) {
953 // sync cookies and cache promptly here.
954 CookieSyncManager.getInstance().sync();
955 }
956 if (mInForeground) {
957 mActivity.onProgressChanged(view, newProgress);
958 }
Michael Kolbfe251992010-07-08 15:41:55 -0700959 if (getTabChangeListener() != null) {
960 getTabChangeListener().onProgress(Tab.this, newProgress);
961 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 }
963
964 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500965 public void onReceivedTitle(WebView view, final String title) {
966 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700967 if (mInForeground) {
968 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500969 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700970 }
Michael Kolbfe251992010-07-08 15:41:55 -0700971 TabChangeListener tcl = getTabChangeListener();
972 if (tcl != null) {
973 tcl.onUrlAndTitle(Tab.this, pageUrl,title);
974 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500975 if (pageUrl == null || pageUrl.length()
976 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700977 return;
978 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500979 new AsyncTask<Void, Void, Void>() {
Michael Kolbfe251992010-07-08 15:41:55 -0700980 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500981 protected Void doInBackground(Void... unused) {
982 // See if we can find the current url in our history
983 // database and add the new title to it.
984 String url = pageUrl;
985 if (url.startsWith("http://www.")) {
986 url = url.substring(11);
987 } else if (url.startsWith("http://")) {
988 url = url.substring(4);
989 }
The Android Open Source Project55e849a2010-05-12 11:06:32 -0700990 // Escape wildcards for LIKE operator.
991 url = url.replace("\\", "\\\\").replace("%", "\\%")
992 .replace("_", "\\_");
Leon Scroggins21d9b902010-03-11 09:33:11 -0500993 Cursor c = null;
994 try {
995 final ContentResolver cr
996 = mActivity.getContentResolver();
997 url = "%" + url;
998 String [] selArgs = new String[] { url };
999 String where = Browser.BookmarkColumns.URL
The Android Open Source Project55e849a2010-05-12 11:06:32 -07001000 + " LIKE ? ESCAPE '\\' AND "
Leon Scroggins21d9b902010-03-11 09:33:11 -05001001 + Browser.BookmarkColumns.BOOKMARK + " = 0";
1002 c = cr.query(Browser.BOOKMARKS_URI, new String[]
1003 { Browser.BookmarkColumns._ID }, where, selArgs,
1004 null);
1005 if (c.moveToFirst()) {
1006 // Current implementation of database only has one
1007 // entry per url.
1008 ContentValues map = new ContentValues();
1009 map.put(Browser.BookmarkColumns.TITLE, title);
1010 String[] projection = new String[]
1011 { Integer.valueOf(c.getInt(0)).toString() };
1012 cr.update(Browser.BOOKMARKS_URI, map, "_id = ?",
1013 projection);
1014 }
1015 } catch (IllegalStateException e) {
1016 Log.e(LOGTAG, "Tab onReceived title", e);
1017 } catch (SQLiteException ex) {
1018 Log.e(LOGTAG,
1019 "onReceivedTitle() caught SQLiteException: ",
1020 ex);
1021 } finally {
1022 if (c != null) c.close();
1023 }
1024 return null;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001025 }
Leon Scroggins21d9b902010-03-11 09:33:11 -05001026 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001027 }
1028
1029 @Override
1030 public void onReceivedIcon(WebView view, Bitmap icon) {
1031 if (icon != null) {
1032 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
1033 .getContentResolver(), view.getOriginalUrl(), view
1034 .getUrl(), icon);
1035 }
1036 if (mInForeground) {
1037 mActivity.setFavicon(icon);
1038 }
Michael Kolbfe251992010-07-08 15:41:55 -07001039 if (getTabChangeListener() != null) {
1040 getTabChangeListener().onFavicon(Tab.this, icon);
1041 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001042 }
1043
1044 @Override
1045 public void onReceivedTouchIconUrl(WebView view, String url,
1046 boolean precomposed) {
1047 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001048 // Let precomposed icons take precedence over non-composed
1049 // icons.
1050 if (precomposed && mTouchIconLoader != null) {
1051 mTouchIconLoader.cancel(false);
1052 mTouchIconLoader = null;
1053 }
1054 // Have only one async task at a time.
1055 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001056 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001057 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001058 }
1059 }
1060
1061 @Override
Leon Clarke30e0ef42010-07-16 15:31:04 +01001062 public void onSelectionDone(WebView view) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001063 if (mInForeground) mActivity.closeDialogs();
1064 }
1065
1066 @Override
Leon Clarke30e0ef42010-07-16 15:31:04 +01001067 public void onSelectionStart(WebView view) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001068 if (mInForeground) mActivity.showSelectDialog();
1069 }
1070
1071 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 public void onShowCustomView(View view,
1073 WebChromeClient.CustomViewCallback callback) {
1074 if (mInForeground) mActivity.onShowCustomView(view, callback);
1075 }
1076
1077 @Override
1078 public void onHideCustomView() {
1079 if (mInForeground) mActivity.onHideCustomView();
1080 }
1081
1082 /**
1083 * The origin has exceeded its database quota.
1084 * @param url the URL that exceeded the quota
1085 * @param databaseIdentifier the identifier of the database on which the
1086 * transaction that caused the quota overflow was run
1087 * @param currentQuota the current quota for the origin.
1088 * @param estimatedSize the estimated size of the database.
1089 * @param totalUsedQuota is the sum of all origins' quota.
1090 * @param quotaUpdater The callback to run when a decision to allow or
1091 * deny quota has been made. Don't forget to call this!
1092 */
1093 @Override
1094 public void onExceededDatabaseQuota(String url,
1095 String databaseIdentifier, long currentQuota, long estimatedSize,
1096 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1097 BrowserSettings.getInstance().getWebStorageSizeManager()
1098 .onExceededDatabaseQuota(url, databaseIdentifier,
1099 currentQuota, estimatedSize, totalUsedQuota,
1100 quotaUpdater);
1101 }
1102
1103 /**
1104 * The Application Cache has exceeded its max size.
1105 * @param spaceNeeded is the amount of disk space that would be needed
1106 * in order for the last appcache operation to succeed.
1107 * @param totalUsedQuota is the sum of all origins' quota.
1108 * @param quotaUpdater A callback to inform the WebCore thread that a
1109 * new app cache size is available. This callback must always
1110 * be executed at some point to ensure that the sleeping
1111 * WebCore thread is woken up.
1112 */
1113 @Override
1114 public void onReachedMaxAppCacheSize(long spaceNeeded,
1115 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1116 BrowserSettings.getInstance().getWebStorageSizeManager()
1117 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1118 quotaUpdater);
1119 }
1120
1121 /**
1122 * Instructs the browser to show a prompt to ask the user to set the
1123 * Geolocation permission state for the specified origin.
1124 * @param origin The origin for which Geolocation permissions are
1125 * requested.
1126 * @param callback The callback to call once the user has set the
1127 * Geolocation permission state.
1128 */
1129 @Override
1130 public void onGeolocationPermissionsShowPrompt(String origin,
1131 GeolocationPermissions.Callback callback) {
1132 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001133 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001134 }
1135 }
1136
1137 /**
1138 * Instructs the browser to hide the Geolocation permissions prompt.
1139 */
1140 @Override
1141 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001142 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001143 mGeolocationPermissionsPrompt.hide();
1144 }
1145 }
1146
Ben Murdoch65acc352009-11-19 18:16:04 +00001147 /* Adds a JavaScript error message to the system log and if the JS
1148 * console is enabled in the about:debug options, to that console
1149 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001150 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001151 */
1152 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001153 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001154 if (mInForeground) {
1155 // call getErrorConsole(true) so it will create one if needed
1156 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001157 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001158 if (mActivity.shouldShowErrorConsole()
1159 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1160 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1161 }
1162 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001163
1164 String message = "Console: " + consoleMessage.message() + " "
1165 + consoleMessage.sourceId() + ":"
1166 + consoleMessage.lineNumber();
1167
1168 switch (consoleMessage.messageLevel()) {
1169 case TIP:
1170 Log.v(CONSOLE_LOGTAG, message);
1171 break;
1172 case LOG:
1173 Log.i(CONSOLE_LOGTAG, message);
1174 break;
1175 case WARNING:
1176 Log.w(CONSOLE_LOGTAG, message);
1177 break;
1178 case ERROR:
1179 Log.e(CONSOLE_LOGTAG, message);
1180 break;
1181 case DEBUG:
1182 Log.d(CONSOLE_LOGTAG, message);
1183 break;
1184 }
1185
1186 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001187 }
1188
1189 /**
1190 * Ask the browser for an icon to represent a <video> element.
1191 * This icon will be used if the Web page did not specify a poster attribute.
1192 * @return Bitmap The icon or null if no such icon is available.
1193 */
1194 @Override
1195 public Bitmap getDefaultVideoPoster() {
1196 if (mInForeground) {
1197 return mActivity.getDefaultVideoPoster();
1198 }
1199 return null;
1200 }
1201
1202 /**
1203 * Ask the host application for a custom progress view to show while
1204 * a <video> is loading.
1205 * @return View The progress view.
1206 */
1207 @Override
1208 public View getVideoLoadingProgressView() {
1209 if (mInForeground) {
1210 return mActivity.getVideoLoadingProgressView();
1211 }
1212 return null;
1213 }
1214
1215 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001216 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001217 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001218 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001219 } else {
1220 uploadMsg.onReceiveValue(null);
1221 }
1222 }
1223
1224 /**
1225 * Deliver a list of already-visited URLs
1226 */
1227 @Override
1228 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1229 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
Michael Kolbfe251992010-07-08 15:41:55 -07001230 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001231 public String[] doInBackground(Void... unused) {
1232 return Browser.getVisitedHistory(mActivity
1233 .getContentResolver());
1234 }
Michael Kolbfe251992010-07-08 15:41:55 -07001235 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001236 public void onPostExecute(String[] result) {
1237 callback.onReceiveValue(result);
1238 };
1239 };
1240 task.execute();
1241 };
1242 };
1243
1244 // -------------------------------------------------------------------------
1245 // WebViewClient implementation for the sub window
1246 // -------------------------------------------------------------------------
1247
1248 // Subclass of WebViewClient used in subwindows to notify the main
1249 // WebViewClient of certain WebView activities.
1250 private static class SubWindowClient extends WebViewClient {
1251 // The main WebViewClient.
1252 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001253 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001254
Leon Scroggins III211ba542010-04-19 13:21:13 -04001255 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001256 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001257 mBrowserActivity = activity;
1258 }
1259 @Override
1260 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1261 // Unlike the others, do not call mClient's version, which would
1262 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001263 // find or select dialog.
1264 mBrowserActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001265 }
1266 @Override
1267 public void doUpdateVisitedHistory(WebView view, String url,
1268 boolean isReload) {
1269 mClient.doUpdateVisitedHistory(view, url, isReload);
1270 }
1271 @Override
1272 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1273 return mClient.shouldOverrideUrlLoading(view, url);
1274 }
1275 @Override
1276 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1277 SslError error) {
1278 mClient.onReceivedSslError(view, handler, error);
1279 }
1280 @Override
1281 public void onReceivedHttpAuthRequest(WebView view,
1282 HttpAuthHandler handler, String host, String realm) {
1283 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1284 }
1285 @Override
1286 public void onFormResubmission(WebView view, Message dontResend,
1287 Message resend) {
1288 mClient.onFormResubmission(view, dontResend, resend);
1289 }
1290 @Override
1291 public void onReceivedError(WebView view, int errorCode,
1292 String description, String failingUrl) {
1293 mClient.onReceivedError(view, errorCode, description, failingUrl);
1294 }
1295 @Override
1296 public boolean shouldOverrideKeyEvent(WebView view,
1297 android.view.KeyEvent event) {
1298 return mClient.shouldOverrideKeyEvent(view, event);
1299 }
1300 @Override
1301 public void onUnhandledKeyEvent(WebView view,
1302 android.view.KeyEvent event) {
1303 mClient.onUnhandledKeyEvent(view, event);
1304 }
1305 }
1306
1307 // -------------------------------------------------------------------------
1308 // WebChromeClient implementation for the sub window
1309 // -------------------------------------------------------------------------
1310
1311 private class SubWindowChromeClient extends WebChromeClient {
1312 // The main WebChromeClient.
1313 private final WebChromeClient mClient;
1314
1315 SubWindowChromeClient(WebChromeClient client) {
1316 mClient = client;
1317 }
1318 @Override
1319 public void onProgressChanged(WebView view, int newProgress) {
1320 mClient.onProgressChanged(view, newProgress);
1321 }
1322 @Override
1323 public boolean onCreateWindow(WebView view, boolean dialog,
1324 boolean userGesture, android.os.Message resultMsg) {
1325 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1326 }
1327 @Override
1328 public void onCloseWindow(WebView window) {
1329 if (window != mSubView) {
1330 Log.e(LOGTAG, "Can't close the window");
1331 }
1332 mActivity.dismissSubWindow(Tab.this);
1333 }
1334 }
1335
1336 // -------------------------------------------------------------------------
1337
1338 // Construct a new tab
1339 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1340 String url) {
1341 mActivity = activity;
1342 mCloseOnExit = closeOnExit;
1343 mAppId = appId;
1344 mOriginalUrl = url;
1345 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1346 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1347 mInLoad = false;
1348 mInForeground = false;
1349
1350 mInflateService = LayoutInflater.from(activity);
1351
1352 // The tab consists of a container view, which contains the main
1353 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001354 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001355
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001356 mDownloadListener = new DownloadListener() {
1357 public void onDownloadStart(String url, String userAgent,
1358 String contentDisposition, String mimetype,
1359 long contentLength) {
1360 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1361 mimetype, contentLength);
1362 if (mMainView.copyBackForwardList().getSize() == 0) {
1363 // This Tab was opened for the sole purpose of downloading a
1364 // file. Remove it.
1365 if (mActivity.getTabControl().getCurrentWebView()
1366 == mMainView) {
1367 // In this case, the Tab is still on top.
1368 mActivity.goBackOnePageOrQuit();
1369 } else {
1370 // In this case, it is not.
1371 mActivity.closeTab(Tab.this);
1372 }
1373 }
1374 }
1375 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001376 mWebBackForwardListClient = new WebBackForwardListClient() {
1377 @Override
1378 public void onNewHistoryItem(WebHistoryItem item) {
1379 if (isInVoiceSearchMode()) {
1380 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1381 }
1382 }
1383 @Override
1384 public void onIndexChanged(WebHistoryItem item, int index) {
1385 Object data = item.getCustomData();
1386 if (data != null && data instanceof Intent) {
1387 activateVoiceSearchMode((Intent) data);
1388 }
1389 }
1390 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001391
Grace Kloba22ac16e2009-10-07 18:00:23 -07001392 setWebView(w);
1393 }
1394
1395 /**
1396 * Sets the WebView for this tab, correctly removing the old WebView from
1397 * the container view.
1398 */
1399 void setWebView(WebView w) {
1400 if (mMainView == w) {
1401 return;
1402 }
1403 // If the WebView is changing, the page will be reloaded, so any ongoing
1404 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001405 if (mGeolocationPermissionsPrompt != null) {
1406 mGeolocationPermissionsPrompt.hide();
1407 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408
1409 // Just remove the old one.
1410 FrameLayout wrapper =
1411 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1412 wrapper.removeView(mMainView);
1413
1414 // set the new one
1415 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001416 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001417 if (mMainView != null) {
1418 mMainView.setWebViewClient(mWebViewClient);
1419 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001420 // Attach DownloadManager so that downloads can start in an active
1421 // or a non-active window. This can happen when going to a site that
1422 // does a redirect after a period of time. The user could have
1423 // switched to another tab while waiting for the download to start.
1424 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001425 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001426 }
1427 }
1428
1429 /**
1430 * Destroy the tab's main WebView and subWindow if any
1431 */
1432 void destroy() {
1433 if (mMainView != null) {
1434 dismissSubWindow();
1435 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1436 // save the WebView to call destroy() after detach it from the tab
1437 WebView webView = mMainView;
1438 setWebView(null);
1439 webView.destroy();
1440 }
1441 }
1442
1443 /**
1444 * Remove the tab from the parent
1445 */
1446 void removeFromTree() {
1447 // detach the children
1448 if (mChildTabs != null) {
1449 for(Tab t : mChildTabs) {
1450 t.setParentTab(null);
1451 }
1452 }
1453 // remove itself from the parent list
1454 if (mParentTab != null) {
1455 mParentTab.mChildTabs.remove(this);
1456 }
1457 }
1458
1459 /**
1460 * Create a new subwindow unless a subwindow already exists.
1461 * @return True if a new subwindow was created. False if one already exists.
1462 */
1463 boolean createSubWindow() {
1464 if (mSubView == null) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001465 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001466 mSubViewContainer = mInflateService.inflate(
1467 R.layout.browser_subwindow, null);
1468 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001469 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001470 // use trackball directly
1471 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001472 // Enable the built-in zoom
1473 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001474 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1475 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001476 mSubView.setWebChromeClient(new SubWindowChromeClient(
1477 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001478 // Set a different DownloadListener for the mSubView, since it will
1479 // just need to dismiss the mSubView, rather than close the Tab
1480 mSubView.setDownloadListener(new DownloadListener() {
1481 public void onDownloadStart(String url, String userAgent,
1482 String contentDisposition, String mimetype,
1483 long contentLength) {
1484 mActivity.onDownloadStart(url, userAgent,
1485 contentDisposition, mimetype, contentLength);
1486 if (mSubView.copyBackForwardList().getSize() == 0) {
1487 // This subwindow was opened for the sole purpose of
1488 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001489 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001490 }
1491 }
1492 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001493 mSubView.setOnCreateContextMenuListener(mActivity);
1494 final BrowserSettings s = BrowserSettings.getInstance();
1495 s.addObserver(mSubView.getSettings()).update(s, null);
1496 final ImageButton cancel = (ImageButton) mSubViewContainer
1497 .findViewById(R.id.subwindow_close);
1498 cancel.setOnClickListener(new OnClickListener() {
1499 public void onClick(View v) {
1500 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1501 }
1502 });
1503 return true;
1504 }
1505 return false;
1506 }
1507
1508 /**
1509 * Dismiss the subWindow for the tab.
1510 */
1511 void dismissSubWindow() {
1512 if (mSubView != null) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001513 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001514 BrowserSettings.getInstance().deleteObserver(
1515 mSubView.getSettings());
1516 mSubView.destroy();
1517 mSubView = null;
1518 mSubViewContainer = null;
1519 }
1520 }
1521
1522 /**
1523 * Attach the sub window to the content view.
1524 */
1525 void attachSubWindow(ViewGroup content) {
1526 if (mSubView != null) {
1527 content.addView(mSubViewContainer,
1528 BrowserActivity.COVER_SCREEN_PARAMS);
1529 }
1530 }
1531
1532 /**
1533 * Remove the sub window from the content view.
1534 */
1535 void removeSubWindow(ViewGroup content) {
1536 if (mSubView != null) {
1537 content.removeView(mSubViewContainer);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001538 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001539 }
1540 }
1541
1542 /**
1543 * This method attaches both the WebView and any sub window to the
1544 * given content view.
1545 */
1546 void attachTabToContentView(ViewGroup content) {
1547 if (mMainView == null) {
1548 return;
1549 }
1550
1551 // Attach the WebView to the container and then attach the
1552 // container to the content view.
1553 FrameLayout wrapper =
1554 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001555 ViewGroup parent = (ViewGroup) mMainView.getParent();
1556 if (parent != wrapper) {
1557 if (parent != null) {
1558 Log.w(LOGTAG, "mMainView already has a parent in"
1559 + " attachTabToContentView!");
1560 parent.removeView(mMainView);
1561 }
1562 wrapper.addView(mMainView);
1563 } else {
1564 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1565 + " attachTabToContentView!");
1566 }
1567 parent = (ViewGroup) mContainer.getParent();
1568 if (parent != content) {
1569 if (parent != null) {
1570 Log.w(LOGTAG, "mContainer already has a parent in"
1571 + " attachTabToContentView!");
1572 parent.removeView(mContainer);
1573 }
1574 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1575 } else {
1576 Log.w(LOGTAG, "mContainer is already attached to content in"
1577 + " attachTabToContentView!");
1578 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001579 attachSubWindow(content);
1580 }
1581
1582 /**
1583 * Remove the WebView and any sub window from the given content view.
1584 */
1585 void removeTabFromContentView(ViewGroup content) {
1586 if (mMainView == null) {
1587 return;
1588 }
1589
1590 // Remove the container from the content and then remove the
1591 // WebView from the container. This will trigger a focus change
1592 // needed by WebView.
1593 FrameLayout wrapper =
1594 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1595 wrapper.removeView(mMainView);
1596 content.removeView(mContainer);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001597 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001598 removeSubWindow(content);
1599 }
1600
1601 /**
1602 * Set the parent tab of this tab.
1603 */
1604 void setParentTab(Tab parent) {
1605 mParentTab = parent;
1606 // This tab may have been freed due to low memory. If that is the case,
1607 // the parent tab index is already saved. If we are changing that index
1608 // (most likely due to removing the parent tab) we must update the
1609 // parent tab index in the saved Bundle.
1610 if (mSavedState != null) {
1611 if (parent == null) {
1612 mSavedState.remove(PARENTTAB);
1613 } else {
1614 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1615 .getTabIndex(parent));
1616 }
1617 }
1618 }
1619
1620 /**
1621 * When a Tab is created through the content of another Tab, then we
1622 * associate the Tabs.
1623 * @param child the Tab that was created from this Tab
1624 */
1625 void addChildTab(Tab child) {
1626 if (mChildTabs == null) {
1627 mChildTabs = new Vector<Tab>();
1628 }
1629 mChildTabs.add(child);
1630 child.setParentTab(this);
1631 }
1632
1633 Vector<Tab> getChildTabs() {
1634 return mChildTabs;
1635 }
1636
1637 void resume() {
1638 if (mMainView != null) {
1639 mMainView.onResume();
1640 if (mSubView != null) {
1641 mSubView.onResume();
1642 }
1643 }
1644 }
1645
1646 void pause() {
1647 if (mMainView != null) {
1648 mMainView.onPause();
1649 if (mSubView != null) {
1650 mSubView.onPause();
1651 }
1652 }
1653 }
1654
1655 void putInForeground() {
1656 mInForeground = true;
1657 resume();
1658 mMainView.setOnCreateContextMenuListener(mActivity);
1659 if (mSubView != null) {
1660 mSubView.setOnCreateContextMenuListener(mActivity);
1661 }
1662 // Show the pending error dialog if the queue is not empty
1663 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1664 showError(mQueuedErrors.getFirst());
1665 }
1666 }
1667
1668 void putInBackground() {
1669 mInForeground = false;
1670 pause();
1671 mMainView.setOnCreateContextMenuListener(null);
1672 if (mSubView != null) {
1673 mSubView.setOnCreateContextMenuListener(null);
1674 }
1675 }
1676
1677 /**
1678 * Return the top window of this tab; either the subwindow if it is not
1679 * null or the main window.
1680 * @return The top window of this tab.
1681 */
1682 WebView getTopWindow() {
1683 if (mSubView != null) {
1684 return mSubView;
1685 }
1686 return mMainView;
1687 }
1688
1689 /**
1690 * Return the main window of this tab. Note: if a tab is freed in the
1691 * background, this can return null. It is only guaranteed to be
1692 * non-null for the current tab.
1693 * @return The main WebView of this tab.
1694 */
1695 WebView getWebView() {
1696 return mMainView;
1697 }
1698
1699 /**
1700 * Return the subwindow of this tab or null if there is no subwindow.
1701 * @return The subwindow of this tab or null.
1702 */
1703 WebView getSubWebView() {
1704 return mSubView;
1705 }
1706
1707 /**
1708 * @return The geolocation permissions prompt for this tab.
1709 */
1710 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001711 if (mGeolocationPermissionsPrompt == null) {
1712 ViewStub stub = (ViewStub) mContainer
1713 .findViewById(R.id.geolocation_permissions_prompt);
1714 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1715 .inflate();
1716 mGeolocationPermissionsPrompt.init();
1717 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001718 return mGeolocationPermissionsPrompt;
1719 }
1720
1721 /**
1722 * @return The application id string
1723 */
1724 String getAppId() {
1725 return mAppId;
1726 }
1727
1728 /**
1729 * Set the application id string
1730 * @param id
1731 */
1732 void setAppId(String id) {
1733 mAppId = id;
1734 }
1735
1736 /**
1737 * @return The original url associated with this Tab
1738 */
1739 String getOriginalUrl() {
1740 return mOriginalUrl;
1741 }
1742
1743 /**
1744 * Set the original url associated with this tab
1745 */
1746 void setOriginalUrl(String url) {
1747 mOriginalUrl = url;
1748 }
1749
1750 /**
1751 * Get the url of this tab. Valid after calling populatePickerData, but
1752 * before calling wipePickerData, or if the webview has been destroyed.
1753 * @return The WebView's url or null.
1754 */
1755 String getUrl() {
1756 if (mPickerData != null) {
1757 return mPickerData.mUrl;
1758 }
1759 return null;
1760 }
1761
1762 /**
1763 * Get the title of this tab. Valid after calling populatePickerData, but
1764 * before calling wipePickerData, or if the webview has been destroyed. If
1765 * the url has no title, use the url instead.
1766 * @return The WebView's title (or url) or null.
1767 */
1768 String getTitle() {
1769 if (mPickerData != null) {
1770 return mPickerData.mTitle;
1771 }
1772 return null;
1773 }
1774
1775 /**
1776 * Get the favicon of this tab. Valid after calling populatePickerData, but
1777 * before calling wipePickerData, or if the webview has been destroyed.
1778 * @return The WebView's favicon or null.
1779 */
1780 Bitmap getFavicon() {
1781 if (mPickerData != null) {
1782 return mPickerData.mFavicon;
1783 }
1784 return null;
1785 }
1786
1787 /**
1788 * Return the tab's error console. Creates the console if createIfNEcessary
1789 * is true and we haven't already created the console.
1790 * @param createIfNecessary Flag to indicate if the console should be
1791 * created if it has not been already.
1792 * @return The tab's error console, or null if one has not been created and
1793 * createIfNecessary is false.
1794 */
1795 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1796 if (createIfNecessary && mErrorConsole == null) {
1797 mErrorConsole = new ErrorConsoleView(mActivity);
1798 mErrorConsole.setWebView(mMainView);
1799 }
1800 return mErrorConsole;
1801 }
1802
1803 /**
1804 * If this Tab was created through another Tab, then this method returns
1805 * that Tab.
1806 * @return the Tab parent or null
1807 */
1808 public Tab getParentTab() {
1809 return mParentTab;
1810 }
1811
1812 /**
1813 * Return whether this tab should be closed when it is backing out of the
1814 * first page.
1815 * @return TRUE if this tab should be closed when exit.
1816 */
1817 boolean closeOnExit() {
1818 return mCloseOnExit;
1819 }
1820
1821 /**
1822 * Saves the current lock-icon state before resetting the lock icon. If we
1823 * have an error, we may need to roll back to the previous state.
1824 */
1825 void resetLockIcon(String url) {
1826 mPrevLockIconType = mLockIconType;
1827 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1828 if (URLUtil.isHttpsUrl(url)) {
1829 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1830 }
1831 }
1832
1833 /**
1834 * Reverts the lock-icon state to the last saved state, for example, if we
1835 * had an error, and need to cancel the load.
1836 */
1837 void revertLockIcon() {
1838 mLockIconType = mPrevLockIconType;
1839 }
1840
1841 /**
1842 * @return The tab's lock icon type.
1843 */
1844 int getLockIconType() {
1845 return mLockIconType;
1846 }
1847
1848 /**
1849 * @return TRUE if onPageStarted is called while onPageFinished is not
1850 * called yet.
1851 */
1852 boolean inLoad() {
1853 return mInLoad;
1854 }
1855
1856 // force mInLoad to be false. This should only be called before closing the
1857 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1858 void clearInLoad() {
1859 mInLoad = false;
1860 }
1861
1862 void populatePickerData() {
1863 if (mMainView == null) {
1864 populatePickerDataFromSavedState();
1865 return;
1866 }
1867
1868 // FIXME: The only place we cared about subwindow was for
1869 // bookmarking (i.e. not when saving state). Was this deliberate?
1870 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001871 if (list == null) {
1872 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1873 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001874 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1875 populatePickerData(item);
1876 }
1877
1878 // Populate the picker data using the given history item and the current top
1879 // WebView.
1880 private void populatePickerData(WebHistoryItem item) {
1881 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001882 if (item == null) {
1883 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1884 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001885 mPickerData.mUrl = item.getUrl();
1886 mPickerData.mTitle = item.getTitle();
1887 mPickerData.mFavicon = item.getFavicon();
1888 if (mPickerData.mTitle == null) {
1889 mPickerData.mTitle = mPickerData.mUrl;
1890 }
1891 }
1892 }
1893
1894 // Create the PickerData and populate it using the saved state of the tab.
1895 void populatePickerDataFromSavedState() {
1896 if (mSavedState == null) {
1897 return;
1898 }
1899 mPickerData = new PickerData();
1900 mPickerData.mUrl = mSavedState.getString(CURRURL);
1901 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1902 }
1903
1904 void clearPickerData() {
1905 mPickerData = null;
1906 }
1907
1908 /**
1909 * Get the saved state bundle.
1910 * @return
1911 */
1912 Bundle getSavedState() {
1913 return mSavedState;
1914 }
1915
1916 /**
1917 * Set the saved state.
1918 */
1919 void setSavedState(Bundle state) {
1920 mSavedState = state;
1921 }
1922
1923 /**
1924 * @return TRUE if succeed in saving the state.
1925 */
1926 boolean saveState() {
1927 // If the WebView is null it means we ran low on memory and we already
1928 // stored the saved state in mSavedState.
1929 if (mMainView == null) {
1930 return mSavedState != null;
1931 }
1932
1933 mSavedState = new Bundle();
1934 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001935
1936 // Store some extra info for displaying the tab in the picker.
1937 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1938 populatePickerData(item);
1939
1940 if (mPickerData.mUrl != null) {
1941 mSavedState.putString(CURRURL, mPickerData.mUrl);
1942 }
1943 if (mPickerData.mTitle != null) {
1944 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1945 }
1946 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1947 if (mAppId != null) {
1948 mSavedState.putString(APPID, mAppId);
1949 }
1950 if (mOriginalUrl != null) {
1951 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1952 }
1953 // Remember the parent tab so the relationship can be restored.
1954 if (mParentTab != null) {
1955 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1956 mParentTab));
1957 }
1958 return true;
1959 }
1960
1961 /*
1962 * Restore the state of the tab.
1963 */
1964 boolean restoreState(Bundle b) {
1965 if (b == null) {
1966 return false;
1967 }
1968 // Restore the internal state even if the WebView fails to restore.
1969 // This will maintain the app id, original url and close-on-exit values.
1970 mSavedState = null;
1971 mPickerData = null;
1972 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1973 mAppId = b.getString(APPID);
1974 mOriginalUrl = b.getString(ORIGINALURL);
1975
1976 final WebBackForwardList list = mMainView.restoreState(b);
1977 if (list == null) {
1978 return false;
1979 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001980 return true;
1981 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001982
1983 /*
Cary Clark01cfcdd2010-06-04 16:36:45 -04001984 * Opens the find and select text dialogs. Called by BrowserActivity.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001985 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001986 WebView showDialog(WebDialog dialog) {
Leon Scroggins III211ba542010-04-19 13:21:13 -04001987 LinearLayout container;
1988 WebView view;
1989 if (mSubView != null) {
1990 view = mSubView;
1991 container = (LinearLayout) mSubViewContainer.findViewById(
1992 R.id.inner_container);
1993 } else {
1994 view = mMainView;
1995 container = mContainer;
1996 }
1997 dialog.show();
Leon Scroggins79e36d92010-04-29 16:01:46 +01001998 container.addView(dialog, 0, new LinearLayout.LayoutParams(
Leon Scroggins III211ba542010-04-19 13:21:13 -04001999 ViewGroup.LayoutParams.MATCH_PARENT,
2000 ViewGroup.LayoutParams.WRAP_CONTENT));
2001 dialog.setWebView(view);
Cary Clark01cfcdd2010-06-04 16:36:45 -04002002 return view;
Leon Scroggins III211ba542010-04-19 13:21:13 -04002003 }
2004
2005 /*
Cary Clark01cfcdd2010-06-04 16:36:45 -04002006 * Close the find or select dialog. Called by BrowserActivity.closeDialog.
Leon Scroggins III211ba542010-04-19 13:21:13 -04002007 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04002008 void closeDialog(WebDialog dialog) {
Leon Scroggins III211ba542010-04-19 13:21:13 -04002009 // The dialog may be attached to the subwindow. Ensure that the
2010 // correct parent has it removed.
2011 LinearLayout parent = (LinearLayout) dialog.getParent();
2012 if (parent != null) parent.removeView(dialog);
2013 }
Michael Kolbfe251992010-07-08 15:41:55 -07002014
2015 /**
2016 * always get the TabChangeListener form the tab control
2017 * @return the TabControl change listener
2018 */
2019 private TabChangeListener getTabChangeListener() {
2020 return mActivity.getTabControl().getTabChangeListener();
2021 }
2022
Grace Kloba22ac16e2009-10-07 18:00:23 -07002023}