blob: 36566c14649496360699b1967b848d1fcf564c24 [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
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700499 maybeUpdateFavicon(null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700500
501 // reset sync timer to avoid sync starts during loading a page
502 CookieSyncManager.getInstance().resetSync();
503
504 if (!mActivity.isNetworkUp()) {
505 view.setNetworkAvailable(false);
506 }
507
508 // finally update the UI in the activity if it is in the foreground
509 if (mInForeground) {
510 mActivity.onPageStarted(view, url, favicon);
511 }
Michael Kolbfe251992010-07-08 15:41:55 -0700512 if (getTabChangeListener() != null) {
513 getTabChangeListener().onPageStarted(Tab.this);
514 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700515 }
516
517 @Override
518 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000519 LogTag.logPageFinishedLoading(
520 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700521 mInLoad = false;
522
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700523 if (!isPrivateBrowsingEnabled()) {
524 if (mInForeground && !mActivity.didUserStopLoading()
525 || !mInForeground) {
526 // Only update the bookmark screenshot if the user did not
527 // cancel the load early.
528 mActivity.postMessage(
529 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
530 500);
531 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700532 }
533
534 // finally update the UI in the activity if it is in the foreground
535 if (mInForeground) {
536 mActivity.onPageFinished(view, url);
537 }
Michael Kolbfe251992010-07-08 15:41:55 -0700538 if (getTabChangeListener() != null) {
539 getTabChangeListener().onPageFinished(Tab.this);
540 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700541 }
542
543 // return true if want to hijack the url to let another app to handle it
544 @Override
545 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400546 if (voiceSearchSourceIsGoogle()) {
547 // This method is called when the user clicks on a link.
548 // VoiceSearchMode is turned off when the user leaves the
549 // Google results page, so at this point the user must be on
550 // that page. If the user clicked a link on that page, assume
551 // that the voice search was effective, and broadcast an Intent
552 // so a receiver can take note of that fact.
553 Intent logIntent = new Intent(LoggingEvents.ACTION_LOG_EVENT);
554 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
555 LoggingEvents.VoiceSearch.RESULT_CLICKED);
556 mActivity.sendBroadcast(logIntent);
557 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700558 if (mInForeground) {
559 return mActivity.shouldOverrideUrlLoading(view, url);
560 } else {
561 return false;
562 }
563 }
564
565 /**
566 * Updates the lock icon. This method is called when we discover another
567 * resource to be loaded for this page (for example, javascript). While
568 * we update the icon type, we do not update the lock icon itself until
569 * we are done loading, it is slightly more secure this way.
570 */
571 @Override
572 public void onLoadResource(WebView view, String url) {
573 if (url != null && url.length() > 0) {
574 // It is only if the page claims to be secure that we may have
575 // to update the lock:
576 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
577 // If NOT a 'safe' url, change the lock to mixed content!
578 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
579 || URLUtil.isAboutUrl(url))) {
580 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
581 }
582 }
583 }
584 }
585
586 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700587 * Show a dialog informing the user of the network error reported by
588 * WebCore if it is in the foreground.
589 */
590 @Override
591 public void onReceivedError(WebView view, int errorCode,
592 String description, String failingUrl) {
593 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
594 errorCode != WebViewClient.ERROR_CONNECT &&
595 errorCode != WebViewClient.ERROR_BAD_URL &&
596 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
597 errorCode != WebViewClient.ERROR_FILE) {
598 queueError(errorCode, description);
599 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500600
601 // Don't log URLs when in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700602 if (!isPrivateBrowsingEnabled()) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500603 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
604 + " " + description);
605 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700606
607 // We need to reset the title after an error if it is in foreground.
608 if (mInForeground) {
609 mActivity.resetTitleAndRevertLockIcon();
610 }
611 }
612
613 /**
614 * Check with the user if it is ok to resend POST data as the page they
615 * are trying to navigate to is the result of a POST.
616 */
617 @Override
618 public void onFormResubmission(WebView view, final Message dontResend,
619 final Message resend) {
620 if (!mInForeground) {
621 dontResend.sendToTarget();
622 return;
623 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500624 if (mDontResend != null) {
625 Log.w(LOGTAG, "onFormResubmission should not be called again "
626 + "while dialog is still up");
627 dontResend.sendToTarget();
628 return;
629 }
630 mDontResend = dontResend;
631 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700632 new AlertDialog.Builder(mActivity).setTitle(
633 R.string.browserFrameFormResubmitLabel).setMessage(
634 R.string.browserFrameFormResubmitMessage)
635 .setPositiveButton(R.string.ok,
636 new DialogInterface.OnClickListener() {
637 public void onClick(DialogInterface dialog,
638 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500639 if (mResend != null) {
640 mResend.sendToTarget();
641 mResend = null;
642 mDontResend = null;
643 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700644 }
645 }).setNegativeButton(R.string.cancel,
646 new DialogInterface.OnClickListener() {
647 public void onClick(DialogInterface dialog,
648 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500649 if (mDontResend != null) {
650 mDontResend.sendToTarget();
651 mResend = null;
652 mDontResend = null;
653 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700654 }
655 }).setOnCancelListener(new OnCancelListener() {
656 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500657 if (mDontResend != null) {
658 mDontResend.sendToTarget();
659 mResend = null;
660 mDontResend = null;
661 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700662 }
663 }).show();
664 }
665
666 /**
667 * Insert the url into the visited history database.
668 * @param url The url to be inserted.
669 * @param isReload True if this url is being reloaded.
670 * FIXME: Not sure what to do when reloading the page.
671 */
672 @Override
673 public void doUpdateVisitedHistory(WebView view, String url,
674 boolean isReload) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500675 // Don't save anything in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700676 if (isPrivateBrowsingEnabled()) return;
Jeff Hamilton47654f42010-09-07 09:57:51 -0500677
Grace Kloba22ac16e2009-10-07 18:00:23 -0700678 if (url.regionMatches(true, 0, "about:", 0, 6)) {
679 return;
680 }
681 // remove "client" before updating it to the history so that it wont
682 // show up in the auto-complete list.
683 int index = url.indexOf("client=ms-");
684 if (index > 0 && url.contains(".google.")) {
685 int end = url.indexOf('&', index);
686 if (end > 0) {
687 url = url.substring(0, index)
688 .concat(url.substring(end + 1));
689 } else {
690 // the url.charAt(index-1) should be either '?' or '&'
691 url = url.substring(0, index-1);
692 }
693 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400694 final ContentResolver cr = mActivity.getContentResolver();
695 final String newUrl = url;
696 new AsyncTask<Void, Void, Void>() {
Michael Kolbfe251992010-07-08 15:41:55 -0700697 @Override
Leon Scroggins8d06e362010-03-24 14:45:57 -0400698 protected Void doInBackground(Void... unused) {
699 Browser.updateVisitedHistory(cr, newUrl, true);
700 return null;
701 }
702 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700703 WebIconDatabase.getInstance().retainIconForPageUrl(url);
704 }
705
706 /**
707 * Displays SSL error(s) dialog to the user.
708 */
709 @Override
710 public void onReceivedSslError(final WebView view,
711 final SslErrorHandler handler, final SslError error) {
712 if (!mInForeground) {
713 handler.cancel();
714 return;
715 }
716 if (BrowserSettings.getInstance().showSecurityWarnings()) {
717 final LayoutInflater factory =
718 LayoutInflater.from(mActivity);
719 final View warningsView =
720 factory.inflate(R.layout.ssl_warnings, null);
721 final LinearLayout placeholder =
722 (LinearLayout)warningsView.findViewById(R.id.placeholder);
723
724 if (error.hasError(SslError.SSL_UNTRUSTED)) {
725 LinearLayout ll = (LinearLayout)factory
726 .inflate(R.layout.ssl_warning, null);
727 ((TextView)ll.findViewById(R.id.warning))
728 .setText(R.string.ssl_untrusted);
729 placeholder.addView(ll);
730 }
731
732 if (error.hasError(SslError.SSL_IDMISMATCH)) {
733 LinearLayout ll = (LinearLayout)factory
734 .inflate(R.layout.ssl_warning, null);
735 ((TextView)ll.findViewById(R.id.warning))
736 .setText(R.string.ssl_mismatch);
737 placeholder.addView(ll);
738 }
739
740 if (error.hasError(SslError.SSL_EXPIRED)) {
741 LinearLayout ll = (LinearLayout)factory
742 .inflate(R.layout.ssl_warning, null);
743 ((TextView)ll.findViewById(R.id.warning))
744 .setText(R.string.ssl_expired);
745 placeholder.addView(ll);
746 }
747
748 if (error.hasError(SslError.SSL_NOTYETVALID)) {
749 LinearLayout ll = (LinearLayout)factory
750 .inflate(R.layout.ssl_warning, null);
751 ((TextView)ll.findViewById(R.id.warning))
752 .setText(R.string.ssl_not_yet_valid);
753 placeholder.addView(ll);
754 }
755
756 new AlertDialog.Builder(mActivity).setTitle(
757 R.string.security_warning).setIcon(
758 android.R.drawable.ic_dialog_alert).setView(
759 warningsView).setPositiveButton(R.string.ssl_continue,
760 new DialogInterface.OnClickListener() {
761 public void onClick(DialogInterface dialog,
762 int whichButton) {
763 handler.proceed();
764 }
765 }).setNeutralButton(R.string.view_certificate,
766 new DialogInterface.OnClickListener() {
767 public void onClick(DialogInterface dialog,
768 int whichButton) {
769 mActivity.showSSLCertificateOnError(view,
770 handler, error);
771 }
772 }).setNegativeButton(R.string.cancel,
773 new DialogInterface.OnClickListener() {
774 public void onClick(DialogInterface dialog,
775 int whichButton) {
776 handler.cancel();
777 mActivity.resetTitleAndRevertLockIcon();
778 }
779 }).setOnCancelListener(
780 new DialogInterface.OnCancelListener() {
781 public void onCancel(DialogInterface dialog) {
782 handler.cancel();
783 mActivity.resetTitleAndRevertLockIcon();
784 }
785 }).show();
786 } else {
787 handler.proceed();
788 }
789 }
790
791 /**
792 * Handles an HTTP authentication request.
793 *
794 * @param handler The authentication handler
795 * @param host The host
796 * @param realm The realm
797 */
798 @Override
799 public void onReceivedHttpAuthRequest(WebView view,
800 final HttpAuthHandler handler, final String host,
801 final String realm) {
802 String username = null;
803 String password = null;
804
805 boolean reuseHttpAuthUsernamePassword = handler
806 .useHttpAuthUsernamePassword();
807
Steve Block95a53b22010-03-25 17:24:58 +0000808 if (reuseHttpAuthUsernamePassword && view != null) {
809 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700810 host, realm);
811 if (credentials != null && credentials.length == 2) {
812 username = credentials[0];
813 password = credentials[1];
814 }
815 }
816
817 if (username != null && password != null) {
818 handler.proceed(username, password);
819 } else {
820 if (mInForeground) {
Bjorn Bringert25738922010-10-12 10:56:20 +0100821 mActivity.showHttpAuthentication(handler, host, realm);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700822 } else {
823 handler.cancel();
824 }
825 }
826 }
827
828 @Override
829 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
830 if (!mInForeground) {
831 return false;
832 }
833 if (mActivity.isMenuDown()) {
834 // only check shortcut key when MENU is held
835 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
836 event);
837 } else {
838 return false;
839 }
840 }
841
842 @Override
843 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400844 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700845 return;
846 }
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100847 if (event.getAction() == KeyEvent.ACTION_DOWN) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700848 mActivity.onKeyDown(event.getKeyCode(), event);
849 } else {
850 mActivity.onKeyUp(event.getKeyCode(), event);
851 }
852 }
853 };
854
855 // -------------------------------------------------------------------------
856 // WebChromeClient implementation for the main WebView
857 // -------------------------------------------------------------------------
858
859 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
860 // Helper method to create a new tab or sub window.
861 private void createWindow(final boolean dialog, final Message msg) {
862 WebView.WebViewTransport transport =
863 (WebView.WebViewTransport) msg.obj;
864 if (dialog) {
865 createSubWindow();
866 mActivity.attachSubWindow(Tab.this);
867 transport.setWebView(mSubView);
868 } else {
869 final Tab newTab = mActivity.openTabAndShow(
870 BrowserActivity.EMPTY_URL_DATA, false, null);
871 if (newTab != Tab.this) {
872 Tab.this.addChildTab(newTab);
873 }
874 transport.setWebView(newTab.getWebView());
875 }
876 msg.sendToTarget();
877 }
878
879 @Override
880 public boolean onCreateWindow(WebView view, final boolean dialog,
881 final boolean userGesture, final Message resultMsg) {
882 // only allow new window or sub window for the foreground case
883 if (!mInForeground) {
884 return false;
885 }
886 // Short-circuit if we can't create any more tabs or sub windows.
887 if (dialog && mSubView != null) {
888 new AlertDialog.Builder(mActivity)
889 .setTitle(R.string.too_many_subwindows_dialog_title)
890 .setIcon(android.R.drawable.ic_dialog_alert)
891 .setMessage(R.string.too_many_subwindows_dialog_message)
892 .setPositiveButton(R.string.ok, null)
893 .show();
894 return false;
895 } else if (!mActivity.getTabControl().canCreateNewTab()) {
896 new AlertDialog.Builder(mActivity)
897 .setTitle(R.string.too_many_windows_dialog_title)
898 .setIcon(android.R.drawable.ic_dialog_alert)
899 .setMessage(R.string.too_many_windows_dialog_message)
900 .setPositiveButton(R.string.ok, null)
901 .show();
902 return false;
903 }
904
905 // Short-circuit if this was a user gesture.
906 if (userGesture) {
907 createWindow(dialog, resultMsg);
908 return true;
909 }
910
911 // Allow the popup and create the appropriate window.
912 final AlertDialog.OnClickListener allowListener =
913 new AlertDialog.OnClickListener() {
914 public void onClick(DialogInterface d,
915 int which) {
916 createWindow(dialog, resultMsg);
917 }
918 };
919
920 // Block the popup by returning a null WebView.
921 final AlertDialog.OnClickListener blockListener =
922 new AlertDialog.OnClickListener() {
923 public void onClick(DialogInterface d, int which) {
924 resultMsg.sendToTarget();
925 }
926 };
927
928 // Build a confirmation dialog to display to the user.
929 final AlertDialog d =
930 new AlertDialog.Builder(mActivity)
931 .setTitle(R.string.attention)
932 .setIcon(android.R.drawable.ic_dialog_alert)
933 .setMessage(R.string.popup_window_attempt)
934 .setPositiveButton(R.string.allow, allowListener)
935 .setNegativeButton(R.string.block, blockListener)
936 .setCancelable(false)
937 .create();
938
939 // Show the confirmation dialog.
940 d.show();
941 return true;
942 }
943
944 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500945 public void onRequestFocus(WebView view) {
946 if (!mInForeground) {
947 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
948 Tab.this));
949 }
950 }
951
952 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700953 public void onCloseWindow(WebView window) {
954 if (mParentTab != null) {
955 // JavaScript can only close popup window.
956 if (mInForeground) {
957 mActivity.switchToTab(mActivity.getTabControl()
958 .getTabIndex(mParentTab));
959 }
960 mActivity.closeTab(Tab.this);
961 }
962 }
963
964 @Override
965 public void onProgressChanged(WebView view, int newProgress) {
966 if (newProgress == 100) {
967 // sync cookies and cache promptly here.
968 CookieSyncManager.getInstance().sync();
969 }
970 if (mInForeground) {
971 mActivity.onProgressChanged(view, newProgress);
972 }
Michael Kolbfe251992010-07-08 15:41:55 -0700973 if (getTabChangeListener() != null) {
974 getTabChangeListener().onProgress(Tab.this, newProgress);
975 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700976 }
977
978 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500979 public void onReceivedTitle(WebView view, final String title) {
980 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700981 if (mInForeground) {
982 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500983 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 }
Michael Kolbfe251992010-07-08 15:41:55 -0700985 TabChangeListener tcl = getTabChangeListener();
986 if (tcl != null) {
987 tcl.onUrlAndTitle(Tab.this, pageUrl,title);
988 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500989 if (pageUrl == null || pageUrl.length()
990 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700991 return;
992 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500993
994 // Update the title in the history database if not in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700995 if (!isPrivateBrowsingEnabled()) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500996 new AsyncTask<Void, Void, Void>() {
997 @Override
998 protected Void doInBackground(Void... unused) {
999 // See if we can find the current url in our history
1000 // database and add the new title to it.
1001 String url = pageUrl;
1002 if (url.startsWith("http://www.")) {
1003 url = url.substring(11);
1004 } else if (url.startsWith("http://")) {
1005 url = url.substring(4);
1006 }
1007 // Escape wildcards for LIKE operator.
1008 url = url.replace("\\", "\\\\").replace("%", "\\%")
1009 .replace("_", "\\_");
1010 Cursor c = null;
1011 try {
1012 final ContentResolver cr = mActivity.getContentResolver();
1013 String selection = History.URL + " LIKE ? ESCAPE '\\'";
1014 String [] selectionArgs = new String[] { "%" + url };
1015 ContentValues values = new ContentValues();
1016 values.put(History.TITLE, title);
1017 cr.update(History.CONTENT_URI, values, selection, selectionArgs);
1018 } catch (IllegalStateException e) {
1019 Log.e(LOGTAG, "Tab onReceived title", e);
1020 } catch (SQLiteException ex) {
1021 Log.e(LOGTAG,
1022 "onReceivedTitle() caught SQLiteException: ",
1023 ex);
1024 } finally {
1025 if (c != null) c.close();
1026 }
1027 return null;
Leon Scroggins21d9b902010-03-11 09:33:11 -05001028 }
Jeff Hamilton47654f42010-09-07 09:57:51 -05001029 }.execute();
1030 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 }
1032
1033 @Override
1034 public void onReceivedIcon(WebView view, Bitmap icon) {
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001035 maybeUpdateFavicon(view.getOriginalUrl(), view.getUrl(), icon);
1036
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 if (mInForeground) {
1038 mActivity.setFavicon(icon);
1039 }
Michael Kolbfe251992010-07-08 15:41:55 -07001040 if (getTabChangeListener() != null) {
1041 getTabChangeListener().onFavicon(Tab.this, icon);
1042 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 }
1044
1045 @Override
1046 public void onReceivedTouchIconUrl(WebView view, String url,
1047 boolean precomposed) {
1048 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001049 // Let precomposed icons take precedence over non-composed
1050 // icons.
1051 if (precomposed && mTouchIconLoader != null) {
1052 mTouchIconLoader.cancel(false);
1053 mTouchIconLoader = null;
1054 }
1055 // Have only one async task at a time.
1056 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001057 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001058 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001059 }
1060 }
1061
1062 @Override
1063 public void onShowCustomView(View view,
1064 WebChromeClient.CustomViewCallback callback) {
1065 if (mInForeground) mActivity.onShowCustomView(view, callback);
1066 }
1067
1068 @Override
1069 public void onHideCustomView() {
1070 if (mInForeground) mActivity.onHideCustomView();
1071 }
1072
1073 /**
1074 * The origin has exceeded its database quota.
1075 * @param url the URL that exceeded the quota
1076 * @param databaseIdentifier the identifier of the database on which the
1077 * transaction that caused the quota overflow was run
1078 * @param currentQuota the current quota for the origin.
1079 * @param estimatedSize the estimated size of the database.
1080 * @param totalUsedQuota is the sum of all origins' quota.
1081 * @param quotaUpdater The callback to run when a decision to allow or
1082 * deny quota has been made. Don't forget to call this!
1083 */
1084 @Override
1085 public void onExceededDatabaseQuota(String url,
1086 String databaseIdentifier, long currentQuota, long estimatedSize,
1087 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1088 BrowserSettings.getInstance().getWebStorageSizeManager()
1089 .onExceededDatabaseQuota(url, databaseIdentifier,
1090 currentQuota, estimatedSize, totalUsedQuota,
1091 quotaUpdater);
1092 }
1093
1094 /**
1095 * The Application Cache has exceeded its max size.
1096 * @param spaceNeeded is the amount of disk space that would be needed
1097 * in order for the last appcache operation to succeed.
1098 * @param totalUsedQuota is the sum of all origins' quota.
1099 * @param quotaUpdater A callback to inform the WebCore thread that a
1100 * new app cache size is available. This callback must always
1101 * be executed at some point to ensure that the sleeping
1102 * WebCore thread is woken up.
1103 */
1104 @Override
1105 public void onReachedMaxAppCacheSize(long spaceNeeded,
1106 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1107 BrowserSettings.getInstance().getWebStorageSizeManager()
1108 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1109 quotaUpdater);
1110 }
1111
1112 /**
1113 * Instructs the browser to show a prompt to ask the user to set the
1114 * Geolocation permission state for the specified origin.
1115 * @param origin The origin for which Geolocation permissions are
1116 * requested.
1117 * @param callback The callback to call once the user has set the
1118 * Geolocation permission state.
1119 */
1120 @Override
1121 public void onGeolocationPermissionsShowPrompt(String origin,
1122 GeolocationPermissions.Callback callback) {
1123 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001124 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001125 }
1126 }
1127
1128 /**
1129 * Instructs the browser to hide the Geolocation permissions prompt.
1130 */
1131 @Override
1132 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001133 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001134 mGeolocationPermissionsPrompt.hide();
1135 }
1136 }
1137
Ben Murdoch65acc352009-11-19 18:16:04 +00001138 /* Adds a JavaScript error message to the system log and if the JS
1139 * console is enabled in the about:debug options, to that console
1140 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001141 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001142 */
1143 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001144 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001145 if (mInForeground) {
1146 // call getErrorConsole(true) so it will create one if needed
1147 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001148 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001149 if (mActivity.shouldShowErrorConsole()
1150 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1151 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1152 }
1153 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001154
Jeff Hamilton47654f42010-09-07 09:57:51 -05001155 // Don't log console messages in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001156 if (isPrivateBrowsingEnabled()) return true;
Jeff Hamilton47654f42010-09-07 09:57:51 -05001157
Ben Murdochc42addf2010-01-28 15:19:59 +00001158 String message = "Console: " + consoleMessage.message() + " "
1159 + consoleMessage.sourceId() + ":"
1160 + consoleMessage.lineNumber();
1161
1162 switch (consoleMessage.messageLevel()) {
1163 case TIP:
1164 Log.v(CONSOLE_LOGTAG, message);
1165 break;
1166 case LOG:
1167 Log.i(CONSOLE_LOGTAG, message);
1168 break;
1169 case WARNING:
1170 Log.w(CONSOLE_LOGTAG, message);
1171 break;
1172 case ERROR:
1173 Log.e(CONSOLE_LOGTAG, message);
1174 break;
1175 case DEBUG:
1176 Log.d(CONSOLE_LOGTAG, message);
1177 break;
1178 }
1179
1180 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001181 }
1182
1183 /**
1184 * Ask the browser for an icon to represent a <video> element.
1185 * This icon will be used if the Web page did not specify a poster attribute.
1186 * @return Bitmap The icon or null if no such icon is available.
1187 */
1188 @Override
1189 public Bitmap getDefaultVideoPoster() {
1190 if (mInForeground) {
1191 return mActivity.getDefaultVideoPoster();
1192 }
1193 return null;
1194 }
1195
1196 /**
1197 * Ask the host application for a custom progress view to show while
1198 * a <video> is loading.
1199 * @return View The progress view.
1200 */
1201 @Override
1202 public View getVideoLoadingProgressView() {
1203 if (mInForeground) {
1204 return mActivity.getVideoLoadingProgressView();
1205 }
1206 return null;
1207 }
1208
1209 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001210 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001211 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001212 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001213 } else {
1214 uploadMsg.onReceiveValue(null);
1215 }
1216 }
1217
1218 /**
1219 * Deliver a list of already-visited URLs
1220 */
1221 @Override
1222 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1223 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
Michael Kolbfe251992010-07-08 15:41:55 -07001224 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001225 public String[] doInBackground(Void... unused) {
1226 return Browser.getVisitedHistory(mActivity
1227 .getContentResolver());
1228 }
Michael Kolbfe251992010-07-08 15:41:55 -07001229 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001230 public void onPostExecute(String[] result) {
1231 callback.onReceiveValue(result);
1232 };
1233 };
1234 task.execute();
1235 };
1236 };
1237
1238 // -------------------------------------------------------------------------
1239 // WebViewClient implementation for the sub window
1240 // -------------------------------------------------------------------------
1241
1242 // Subclass of WebViewClient used in subwindows to notify the main
1243 // WebViewClient of certain WebView activities.
1244 private static class SubWindowClient extends WebViewClient {
1245 // The main WebViewClient.
1246 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001247 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001248
Leon Scroggins III211ba542010-04-19 13:21:13 -04001249 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001250 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001251 mBrowserActivity = activity;
1252 }
1253 @Override
1254 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1255 // Unlike the others, do not call mClient's version, which would
1256 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001257 // find or select dialog.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001258 mBrowserActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001259 }
1260 @Override
1261 public void doUpdateVisitedHistory(WebView view, String url,
1262 boolean isReload) {
1263 mClient.doUpdateVisitedHistory(view, url, isReload);
1264 }
1265 @Override
1266 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1267 return mClient.shouldOverrideUrlLoading(view, url);
1268 }
1269 @Override
1270 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1271 SslError error) {
1272 mClient.onReceivedSslError(view, handler, error);
1273 }
1274 @Override
1275 public void onReceivedHttpAuthRequest(WebView view,
1276 HttpAuthHandler handler, String host, String realm) {
1277 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1278 }
1279 @Override
1280 public void onFormResubmission(WebView view, Message dontResend,
1281 Message resend) {
1282 mClient.onFormResubmission(view, dontResend, resend);
1283 }
1284 @Override
1285 public void onReceivedError(WebView view, int errorCode,
1286 String description, String failingUrl) {
1287 mClient.onReceivedError(view, errorCode, description, failingUrl);
1288 }
1289 @Override
1290 public boolean shouldOverrideKeyEvent(WebView view,
1291 android.view.KeyEvent event) {
1292 return mClient.shouldOverrideKeyEvent(view, event);
1293 }
1294 @Override
1295 public void onUnhandledKeyEvent(WebView view,
1296 android.view.KeyEvent event) {
1297 mClient.onUnhandledKeyEvent(view, event);
1298 }
1299 }
1300
1301 // -------------------------------------------------------------------------
1302 // WebChromeClient implementation for the sub window
1303 // -------------------------------------------------------------------------
1304
1305 private class SubWindowChromeClient extends WebChromeClient {
1306 // The main WebChromeClient.
1307 private final WebChromeClient mClient;
1308
1309 SubWindowChromeClient(WebChromeClient client) {
1310 mClient = client;
1311 }
1312 @Override
1313 public void onProgressChanged(WebView view, int newProgress) {
1314 mClient.onProgressChanged(view, newProgress);
1315 }
1316 @Override
1317 public boolean onCreateWindow(WebView view, boolean dialog,
1318 boolean userGesture, android.os.Message resultMsg) {
1319 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1320 }
1321 @Override
1322 public void onCloseWindow(WebView window) {
1323 if (window != mSubView) {
1324 Log.e(LOGTAG, "Can't close the window");
1325 }
1326 mActivity.dismissSubWindow(Tab.this);
1327 }
1328 }
1329
1330 // -------------------------------------------------------------------------
1331
1332 // Construct a new tab
1333 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1334 String url) {
1335 mActivity = activity;
1336 mCloseOnExit = closeOnExit;
1337 mAppId = appId;
1338 mOriginalUrl = url;
1339 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1340 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1341 mInLoad = false;
1342 mInForeground = false;
1343
1344 mInflateService = LayoutInflater.from(activity);
1345
1346 // The tab consists of a container view, which contains the main
1347 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001348 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001349
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001350 mDownloadListener = new DownloadListener() {
1351 public void onDownloadStart(String url, String userAgent,
1352 String contentDisposition, String mimetype,
1353 long contentLength) {
1354 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1355 mimetype, contentLength);
1356 if (mMainView.copyBackForwardList().getSize() == 0) {
1357 // This Tab was opened for the sole purpose of downloading a
1358 // file. Remove it.
1359 if (mActivity.getTabControl().getCurrentWebView()
1360 == mMainView) {
1361 // In this case, the Tab is still on top.
1362 mActivity.goBackOnePageOrQuit();
1363 } else {
1364 // In this case, it is not.
1365 mActivity.closeTab(Tab.this);
1366 }
1367 }
1368 }
1369 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001370 mWebBackForwardListClient = new WebBackForwardListClient() {
1371 @Override
1372 public void onNewHistoryItem(WebHistoryItem item) {
1373 if (isInVoiceSearchMode()) {
1374 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1375 }
1376 }
1377 @Override
1378 public void onIndexChanged(WebHistoryItem item, int index) {
1379 Object data = item.getCustomData();
1380 if (data != null && data instanceof Intent) {
1381 activateVoiceSearchMode((Intent) data);
1382 }
1383 }
1384 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001385
Grace Kloba22ac16e2009-10-07 18:00:23 -07001386 setWebView(w);
1387 }
1388
1389 /**
1390 * Sets the WebView for this tab, correctly removing the old WebView from
1391 * the container view.
1392 */
1393 void setWebView(WebView w) {
1394 if (mMainView == w) {
1395 return;
1396 }
1397 // If the WebView is changing, the page will be reloaded, so any ongoing
1398 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001399 if (mGeolocationPermissionsPrompt != null) {
1400 mGeolocationPermissionsPrompt.hide();
1401 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001402
1403 // Just remove the old one.
1404 FrameLayout wrapper =
1405 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1406 wrapper.removeView(mMainView);
1407
1408 // set the new one
1409 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001410 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001411 if (mMainView != null) {
1412 mMainView.setWebViewClient(mWebViewClient);
1413 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001414 // Attach DownloadManager so that downloads can start in an active
1415 // or a non-active window. This can happen when going to a site that
1416 // does a redirect after a period of time. The user could have
1417 // switched to another tab while waiting for the download to start.
1418 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001419 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001420 }
1421 }
1422
1423 /**
1424 * Destroy the tab's main WebView and subWindow if any
1425 */
1426 void destroy() {
1427 if (mMainView != null) {
1428 dismissSubWindow();
1429 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1430 // save the WebView to call destroy() after detach it from the tab
1431 WebView webView = mMainView;
1432 setWebView(null);
1433 webView.destroy();
1434 }
1435 }
1436
1437 /**
1438 * Remove the tab from the parent
1439 */
1440 void removeFromTree() {
1441 // detach the children
1442 if (mChildTabs != null) {
1443 for(Tab t : mChildTabs) {
1444 t.setParentTab(null);
1445 }
1446 }
1447 // remove itself from the parent list
1448 if (mParentTab != null) {
1449 mParentTab.mChildTabs.remove(this);
1450 }
1451 }
1452
1453 /**
1454 * Create a new subwindow unless a subwindow already exists.
1455 * @return True if a new subwindow was created. False if one already exists.
1456 */
1457 boolean createSubWindow() {
1458 if (mSubView == null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001459 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001460 mSubViewContainer = mInflateService.inflate(
1461 R.layout.browser_subwindow, null);
1462 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001463 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001464 // use trackball directly
1465 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001466 // Enable the built-in zoom
1467 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001468 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1469 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001470 mSubView.setWebChromeClient(new SubWindowChromeClient(
1471 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001472 // Set a different DownloadListener for the mSubView, since it will
1473 // just need to dismiss the mSubView, rather than close the Tab
1474 mSubView.setDownloadListener(new DownloadListener() {
1475 public void onDownloadStart(String url, String userAgent,
1476 String contentDisposition, String mimetype,
1477 long contentLength) {
1478 mActivity.onDownloadStart(url, userAgent,
1479 contentDisposition, mimetype, contentLength);
1480 if (mSubView.copyBackForwardList().getSize() == 0) {
1481 // This subwindow was opened for the sole purpose of
1482 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001483 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001484 }
1485 }
1486 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001487 mSubView.setOnCreateContextMenuListener(mActivity);
1488 final BrowserSettings s = BrowserSettings.getInstance();
1489 s.addObserver(mSubView.getSettings()).update(s, null);
1490 final ImageButton cancel = (ImageButton) mSubViewContainer
1491 .findViewById(R.id.subwindow_close);
1492 cancel.setOnClickListener(new OnClickListener() {
1493 public void onClick(View v) {
1494 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1495 }
1496 });
1497 return true;
1498 }
1499 return false;
1500 }
1501
1502 /**
1503 * Dismiss the subWindow for the tab.
1504 */
1505 void dismissSubWindow() {
1506 if (mSubView != null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001507 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001508 BrowserSettings.getInstance().deleteObserver(
1509 mSubView.getSettings());
1510 mSubView.destroy();
1511 mSubView = null;
1512 mSubViewContainer = null;
1513 }
1514 }
1515
1516 /**
1517 * Attach the sub window to the content view.
1518 */
1519 void attachSubWindow(ViewGroup content) {
1520 if (mSubView != null) {
1521 content.addView(mSubViewContainer,
1522 BrowserActivity.COVER_SCREEN_PARAMS);
1523 }
1524 }
1525
1526 /**
1527 * Remove the sub window from the content view.
1528 */
1529 void removeSubWindow(ViewGroup content) {
1530 if (mSubView != null) {
1531 content.removeView(mSubViewContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001532 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001533 }
1534 }
1535
1536 /**
1537 * This method attaches both the WebView and any sub window to the
1538 * given content view.
1539 */
1540 void attachTabToContentView(ViewGroup content) {
1541 if (mMainView == null) {
1542 return;
1543 }
1544
1545 // Attach the WebView to the container and then attach the
1546 // container to the content view.
1547 FrameLayout wrapper =
1548 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001549 ViewGroup parent = (ViewGroup) mMainView.getParent();
1550 if (parent != wrapper) {
1551 if (parent != null) {
1552 Log.w(LOGTAG, "mMainView already has a parent in"
1553 + " attachTabToContentView!");
1554 parent.removeView(mMainView);
1555 }
1556 wrapper.addView(mMainView);
1557 } else {
1558 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1559 + " attachTabToContentView!");
1560 }
1561 parent = (ViewGroup) mContainer.getParent();
1562 if (parent != content) {
1563 if (parent != null) {
1564 Log.w(LOGTAG, "mContainer already has a parent in"
1565 + " attachTabToContentView!");
1566 parent.removeView(mContainer);
1567 }
1568 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1569 } else {
1570 Log.w(LOGTAG, "mContainer is already attached to content in"
1571 + " attachTabToContentView!");
1572 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001573 attachSubWindow(content);
1574 }
1575
1576 /**
1577 * Remove the WebView and any sub window from the given content view.
1578 */
1579 void removeTabFromContentView(ViewGroup content) {
1580 if (mMainView == null) {
1581 return;
1582 }
1583
1584 // Remove the container from the content and then remove the
1585 // WebView from the container. This will trigger a focus change
1586 // needed by WebView.
1587 FrameLayout wrapper =
1588 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1589 wrapper.removeView(mMainView);
1590 content.removeView(mContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001591 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001592 removeSubWindow(content);
1593 }
1594
1595 /**
1596 * Set the parent tab of this tab.
1597 */
1598 void setParentTab(Tab parent) {
1599 mParentTab = parent;
1600 // This tab may have been freed due to low memory. If that is the case,
1601 // the parent tab index is already saved. If we are changing that index
1602 // (most likely due to removing the parent tab) we must update the
1603 // parent tab index in the saved Bundle.
1604 if (mSavedState != null) {
1605 if (parent == null) {
1606 mSavedState.remove(PARENTTAB);
1607 } else {
1608 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1609 .getTabIndex(parent));
1610 }
1611 }
1612 }
1613
1614 /**
1615 * When a Tab is created through the content of another Tab, then we
1616 * associate the Tabs.
1617 * @param child the Tab that was created from this Tab
1618 */
1619 void addChildTab(Tab child) {
1620 if (mChildTabs == null) {
1621 mChildTabs = new Vector<Tab>();
1622 }
1623 mChildTabs.add(child);
1624 child.setParentTab(this);
1625 }
1626
1627 Vector<Tab> getChildTabs() {
1628 return mChildTabs;
1629 }
1630
1631 void resume() {
1632 if (mMainView != null) {
1633 mMainView.onResume();
1634 if (mSubView != null) {
1635 mSubView.onResume();
1636 }
1637 }
1638 }
1639
1640 void pause() {
1641 if (mMainView != null) {
1642 mMainView.onPause();
1643 if (mSubView != null) {
1644 mSubView.onPause();
1645 }
1646 }
1647 }
1648
1649 void putInForeground() {
1650 mInForeground = true;
1651 resume();
1652 mMainView.setOnCreateContextMenuListener(mActivity);
1653 if (mSubView != null) {
1654 mSubView.setOnCreateContextMenuListener(mActivity);
1655 }
1656 // Show the pending error dialog if the queue is not empty
1657 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1658 showError(mQueuedErrors.getFirst());
1659 }
1660 }
1661
1662 void putInBackground() {
1663 mInForeground = false;
1664 pause();
1665 mMainView.setOnCreateContextMenuListener(null);
1666 if (mSubView != null) {
1667 mSubView.setOnCreateContextMenuListener(null);
1668 }
1669 }
1670
1671 /**
1672 * Return the top window of this tab; either the subwindow if it is not
1673 * null or the main window.
1674 * @return The top window of this tab.
1675 */
1676 WebView getTopWindow() {
1677 if (mSubView != null) {
1678 return mSubView;
1679 }
1680 return mMainView;
1681 }
1682
1683 /**
1684 * Return the main window of this tab. Note: if a tab is freed in the
1685 * background, this can return null. It is only guaranteed to be
1686 * non-null for the current tab.
1687 * @return The main WebView of this tab.
1688 */
1689 WebView getWebView() {
1690 return mMainView;
1691 }
1692
1693 /**
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001694 * Return whether private browsing is enabled for the main window of
1695 * this tab.
1696 * @return True if private browsing is enabled.
1697 */
1698 private boolean isPrivateBrowsingEnabled() {
1699 WebView webView = getWebView();
1700 if (webView == null) {
1701 return false;
1702 }
1703 return webView.isPrivateBrowsingEnabled();
1704 }
1705
1706 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -07001707 * Return the subwindow of this tab or null if there is no subwindow.
1708 * @return The subwindow of this tab or null.
1709 */
1710 WebView getSubWebView() {
1711 return mSubView;
1712 }
1713
1714 /**
1715 * @return The geolocation permissions prompt for this tab.
1716 */
1717 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001718 if (mGeolocationPermissionsPrompt == null) {
1719 ViewStub stub = (ViewStub) mContainer
1720 .findViewById(R.id.geolocation_permissions_prompt);
1721 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1722 .inflate();
1723 mGeolocationPermissionsPrompt.init();
1724 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001725 return mGeolocationPermissionsPrompt;
1726 }
1727
1728 /**
1729 * @return The application id string
1730 */
1731 String getAppId() {
1732 return mAppId;
1733 }
1734
1735 /**
1736 * Set the application id string
1737 * @param id
1738 */
1739 void setAppId(String id) {
1740 mAppId = id;
1741 }
1742
1743 /**
1744 * @return The original url associated with this Tab
1745 */
1746 String getOriginalUrl() {
1747 return mOriginalUrl;
1748 }
1749
1750 /**
1751 * Set the original url associated with this tab
1752 */
1753 void setOriginalUrl(String url) {
1754 mOriginalUrl = url;
1755 }
1756
1757 /**
1758 * Get the url of this tab. Valid after calling populatePickerData, but
1759 * before calling wipePickerData, or if the webview has been destroyed.
1760 * @return The WebView's url or null.
1761 */
1762 String getUrl() {
1763 if (mPickerData != null) {
1764 return mPickerData.mUrl;
1765 }
1766 return null;
1767 }
1768
1769 /**
1770 * Get the title of this tab. Valid after calling populatePickerData, but
1771 * before calling wipePickerData, or if the webview has been destroyed. If
1772 * the url has no title, use the url instead.
1773 * @return The WebView's title (or url) or null.
1774 */
1775 String getTitle() {
1776 if (mPickerData != null) {
1777 return mPickerData.mTitle;
1778 }
1779 return null;
1780 }
1781
1782 /**
1783 * Get the favicon of this tab. Valid after calling populatePickerData, but
1784 * before calling wipePickerData, or if the webview has been destroyed.
1785 * @return The WebView's favicon or null.
1786 */
1787 Bitmap getFavicon() {
1788 if (mPickerData != null) {
1789 return mPickerData.mFavicon;
1790 }
1791 return null;
1792 }
1793
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001794 /*
1795 * Update the favorites icon if the private browsing isn't enabled and the
1796 * icon is valid.
1797 */
1798 void maybeUpdateFavicon(final String originalUrl, final String url, Bitmap favicon) {
1799 if (favicon == null) {
1800 return;
1801 }
1802 if (!isPrivateBrowsingEnabled()) {
1803 Bookmarks.updateFavicon(mActivity
1804 .getContentResolver(), originalUrl, url, favicon);
1805 }
1806 }
1807
Grace Kloba22ac16e2009-10-07 18:00:23 -07001808 /**
1809 * Return the tab's error console. Creates the console if createIfNEcessary
1810 * is true and we haven't already created the console.
1811 * @param createIfNecessary Flag to indicate if the console should be
1812 * created if it has not been already.
1813 * @return The tab's error console, or null if one has not been created and
1814 * createIfNecessary is false.
1815 */
1816 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1817 if (createIfNecessary && mErrorConsole == null) {
1818 mErrorConsole = new ErrorConsoleView(mActivity);
1819 mErrorConsole.setWebView(mMainView);
1820 }
1821 return mErrorConsole;
1822 }
1823
1824 /**
1825 * If this Tab was created through another Tab, then this method returns
1826 * that Tab.
1827 * @return the Tab parent or null
1828 */
1829 public Tab getParentTab() {
1830 return mParentTab;
1831 }
1832
1833 /**
1834 * Return whether this tab should be closed when it is backing out of the
1835 * first page.
1836 * @return TRUE if this tab should be closed when exit.
1837 */
1838 boolean closeOnExit() {
1839 return mCloseOnExit;
1840 }
1841
1842 /**
1843 * Saves the current lock-icon state before resetting the lock icon. If we
1844 * have an error, we may need to roll back to the previous state.
1845 */
1846 void resetLockIcon(String url) {
1847 mPrevLockIconType = mLockIconType;
1848 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1849 if (URLUtil.isHttpsUrl(url)) {
1850 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1851 }
1852 }
1853
1854 /**
1855 * Reverts the lock-icon state to the last saved state, for example, if we
1856 * had an error, and need to cancel the load.
1857 */
1858 void revertLockIcon() {
1859 mLockIconType = mPrevLockIconType;
1860 }
1861
1862 /**
1863 * @return The tab's lock icon type.
1864 */
1865 int getLockIconType() {
1866 return mLockIconType;
1867 }
1868
1869 /**
1870 * @return TRUE if onPageStarted is called while onPageFinished is not
1871 * called yet.
1872 */
1873 boolean inLoad() {
1874 return mInLoad;
1875 }
1876
1877 // force mInLoad to be false. This should only be called before closing the
1878 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1879 void clearInLoad() {
1880 mInLoad = false;
1881 }
1882
1883 void populatePickerData() {
1884 if (mMainView == null) {
1885 populatePickerDataFromSavedState();
1886 return;
1887 }
1888
1889 // FIXME: The only place we cared about subwindow was for
1890 // bookmarking (i.e. not when saving state). Was this deliberate?
1891 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001892 if (list == null) {
1893 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1894 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001895 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1896 populatePickerData(item);
1897 }
1898
1899 // Populate the picker data using the given history item and the current top
1900 // WebView.
1901 private void populatePickerData(WebHistoryItem item) {
1902 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001903 if (item == null) {
1904 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1905 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001906 mPickerData.mUrl = item.getUrl();
1907 mPickerData.mTitle = item.getTitle();
1908 mPickerData.mFavicon = item.getFavicon();
1909 if (mPickerData.mTitle == null) {
1910 mPickerData.mTitle = mPickerData.mUrl;
1911 }
1912 }
1913 }
1914
1915 // Create the PickerData and populate it using the saved state of the tab.
1916 void populatePickerDataFromSavedState() {
1917 if (mSavedState == null) {
1918 return;
1919 }
1920 mPickerData = new PickerData();
1921 mPickerData.mUrl = mSavedState.getString(CURRURL);
1922 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1923 }
1924
1925 void clearPickerData() {
1926 mPickerData = null;
1927 }
1928
1929 /**
1930 * Get the saved state bundle.
1931 * @return
1932 */
1933 Bundle getSavedState() {
1934 return mSavedState;
1935 }
1936
1937 /**
1938 * Set the saved state.
1939 */
1940 void setSavedState(Bundle state) {
1941 mSavedState = state;
1942 }
1943
1944 /**
1945 * @return TRUE if succeed in saving the state.
1946 */
1947 boolean saveState() {
1948 // If the WebView is null it means we ran low on memory and we already
1949 // stored the saved state in mSavedState.
1950 if (mMainView == null) {
1951 return mSavedState != null;
1952 }
1953
1954 mSavedState = new Bundle();
1955 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001956
1957 // Store some extra info for displaying the tab in the picker.
1958 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1959 populatePickerData(item);
1960
1961 if (mPickerData.mUrl != null) {
1962 mSavedState.putString(CURRURL, mPickerData.mUrl);
1963 }
1964 if (mPickerData.mTitle != null) {
1965 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1966 }
1967 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1968 if (mAppId != null) {
1969 mSavedState.putString(APPID, mAppId);
1970 }
1971 if (mOriginalUrl != null) {
1972 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1973 }
1974 // Remember the parent tab so the relationship can be restored.
1975 if (mParentTab != null) {
1976 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1977 mParentTab));
1978 }
1979 return true;
1980 }
1981
1982 /*
1983 * Restore the state of the tab.
1984 */
1985 boolean restoreState(Bundle b) {
1986 if (b == null) {
1987 return false;
1988 }
1989 // Restore the internal state even if the WebView fails to restore.
1990 // This will maintain the app id, original url and close-on-exit values.
1991 mSavedState = null;
1992 mPickerData = null;
1993 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1994 mAppId = b.getString(APPID);
1995 mOriginalUrl = b.getString(ORIGINALURL);
1996
1997 final WebBackForwardList list = mMainView.restoreState(b);
1998 if (list == null) {
1999 return false;
2000 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002001 return true;
2002 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04002003
Michael Kolbfe251992010-07-08 15:41:55 -07002004 /**
2005 * always get the TabChangeListener form the tab control
2006 * @return the TabControl change listener
2007 */
2008 private TabChangeListener getTabChangeListener() {
2009 return mActivity.getTabControl().getTabChangeListener();
2010 }
2011
Grace Kloba22ac16e2009-10-07 18:00:23 -07002012}