blob: cb70e013ca33aa9e14115729c02e2bd86b6134fc [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) {
821 mActivity.showHttpAuthentication(handler, host, realm,
822 null, null, null, 0);
823 } else {
824 handler.cancel();
825 }
826 }
827 }
828
829 @Override
830 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
831 if (!mInForeground) {
832 return false;
833 }
834 if (mActivity.isMenuDown()) {
835 // only check shortcut key when MENU is held
836 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
837 event);
838 } else {
839 return false;
840 }
841 }
842
843 @Override
844 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400845 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700846 return;
847 }
Bjorn Bringertb1402a52010-10-12 10:53:12 +0100848 if (event.getAction() == KeyEvent.ACTION_DOWN) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700849 mActivity.onKeyDown(event.getKeyCode(), event);
850 } else {
851 mActivity.onKeyUp(event.getKeyCode(), event);
852 }
853 }
854 };
855
856 // -------------------------------------------------------------------------
857 // WebChromeClient implementation for the main WebView
858 // -------------------------------------------------------------------------
859
860 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
861 // Helper method to create a new tab or sub window.
862 private void createWindow(final boolean dialog, final Message msg) {
863 WebView.WebViewTransport transport =
864 (WebView.WebViewTransport) msg.obj;
865 if (dialog) {
866 createSubWindow();
867 mActivity.attachSubWindow(Tab.this);
868 transport.setWebView(mSubView);
869 } else {
870 final Tab newTab = mActivity.openTabAndShow(
871 BrowserActivity.EMPTY_URL_DATA, false, null);
872 if (newTab != Tab.this) {
873 Tab.this.addChildTab(newTab);
874 }
875 transport.setWebView(newTab.getWebView());
876 }
877 msg.sendToTarget();
878 }
879
880 @Override
881 public boolean onCreateWindow(WebView view, final boolean dialog,
882 final boolean userGesture, final Message resultMsg) {
883 // only allow new window or sub window for the foreground case
884 if (!mInForeground) {
885 return false;
886 }
887 // Short-circuit if we can't create any more tabs or sub windows.
888 if (dialog && mSubView != null) {
889 new AlertDialog.Builder(mActivity)
890 .setTitle(R.string.too_many_subwindows_dialog_title)
891 .setIcon(android.R.drawable.ic_dialog_alert)
892 .setMessage(R.string.too_many_subwindows_dialog_message)
893 .setPositiveButton(R.string.ok, null)
894 .show();
895 return false;
896 } else if (!mActivity.getTabControl().canCreateNewTab()) {
897 new AlertDialog.Builder(mActivity)
898 .setTitle(R.string.too_many_windows_dialog_title)
899 .setIcon(android.R.drawable.ic_dialog_alert)
900 .setMessage(R.string.too_many_windows_dialog_message)
901 .setPositiveButton(R.string.ok, null)
902 .show();
903 return false;
904 }
905
906 // Short-circuit if this was a user gesture.
907 if (userGesture) {
908 createWindow(dialog, resultMsg);
909 return true;
910 }
911
912 // Allow the popup and create the appropriate window.
913 final AlertDialog.OnClickListener allowListener =
914 new AlertDialog.OnClickListener() {
915 public void onClick(DialogInterface d,
916 int which) {
917 createWindow(dialog, resultMsg);
918 }
919 };
920
921 // Block the popup by returning a null WebView.
922 final AlertDialog.OnClickListener blockListener =
923 new AlertDialog.OnClickListener() {
924 public void onClick(DialogInterface d, int which) {
925 resultMsg.sendToTarget();
926 }
927 };
928
929 // Build a confirmation dialog to display to the user.
930 final AlertDialog d =
931 new AlertDialog.Builder(mActivity)
932 .setTitle(R.string.attention)
933 .setIcon(android.R.drawable.ic_dialog_alert)
934 .setMessage(R.string.popup_window_attempt)
935 .setPositiveButton(R.string.allow, allowListener)
936 .setNegativeButton(R.string.block, blockListener)
937 .setCancelable(false)
938 .create();
939
940 // Show the confirmation dialog.
941 d.show();
942 return true;
943 }
944
945 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500946 public void onRequestFocus(WebView view) {
947 if (!mInForeground) {
948 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
949 Tab.this));
950 }
951 }
952
953 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700954 public void onCloseWindow(WebView window) {
955 if (mParentTab != null) {
956 // JavaScript can only close popup window.
957 if (mInForeground) {
958 mActivity.switchToTab(mActivity.getTabControl()
959 .getTabIndex(mParentTab));
960 }
961 mActivity.closeTab(Tab.this);
962 }
963 }
964
965 @Override
966 public void onProgressChanged(WebView view, int newProgress) {
967 if (newProgress == 100) {
968 // sync cookies and cache promptly here.
969 CookieSyncManager.getInstance().sync();
970 }
971 if (mInForeground) {
972 mActivity.onProgressChanged(view, newProgress);
973 }
Michael Kolbfe251992010-07-08 15:41:55 -0700974 if (getTabChangeListener() != null) {
975 getTabChangeListener().onProgress(Tab.this, newProgress);
976 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700977 }
978
979 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500980 public void onReceivedTitle(WebView view, final String title) {
981 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700982 if (mInForeground) {
983 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500984 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700985 }
Michael Kolbfe251992010-07-08 15:41:55 -0700986 TabChangeListener tcl = getTabChangeListener();
987 if (tcl != null) {
988 tcl.onUrlAndTitle(Tab.this, pageUrl,title);
989 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500990 if (pageUrl == null || pageUrl.length()
991 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700992 return;
993 }
Jeff Hamilton47654f42010-09-07 09:57:51 -0500994
995 // Update the title in the history database if not in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -0700996 if (!isPrivateBrowsingEnabled()) {
Jeff Hamilton47654f42010-09-07 09:57:51 -0500997 new AsyncTask<Void, Void, Void>() {
998 @Override
999 protected Void doInBackground(Void... unused) {
1000 // See if we can find the current url in our history
1001 // database and add the new title to it.
1002 String url = pageUrl;
1003 if (url.startsWith("http://www.")) {
1004 url = url.substring(11);
1005 } else if (url.startsWith("http://")) {
1006 url = url.substring(4);
1007 }
1008 // Escape wildcards for LIKE operator.
1009 url = url.replace("\\", "\\\\").replace("%", "\\%")
1010 .replace("_", "\\_");
1011 Cursor c = null;
1012 try {
1013 final ContentResolver cr = mActivity.getContentResolver();
1014 String selection = History.URL + " LIKE ? ESCAPE '\\'";
1015 String [] selectionArgs = new String[] { "%" + url };
1016 ContentValues values = new ContentValues();
1017 values.put(History.TITLE, title);
1018 cr.update(History.CONTENT_URI, values, selection, selectionArgs);
1019 } catch (IllegalStateException e) {
1020 Log.e(LOGTAG, "Tab onReceived title", e);
1021 } catch (SQLiteException ex) {
1022 Log.e(LOGTAG,
1023 "onReceivedTitle() caught SQLiteException: ",
1024 ex);
1025 } finally {
1026 if (c != null) c.close();
1027 }
1028 return null;
Leon Scroggins21d9b902010-03-11 09:33:11 -05001029 }
Jeff Hamilton47654f42010-09-07 09:57:51 -05001030 }.execute();
1031 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 }
1033
1034 @Override
1035 public void onReceivedIcon(WebView view, Bitmap icon) {
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001036 maybeUpdateFavicon(view.getOriginalUrl(), view.getUrl(), icon);
1037
Grace Kloba22ac16e2009-10-07 18:00:23 -07001038 if (mInForeground) {
1039 mActivity.setFavicon(icon);
1040 }
Michael Kolbfe251992010-07-08 15:41:55 -07001041 if (getTabChangeListener() != null) {
1042 getTabChangeListener().onFavicon(Tab.this, icon);
1043 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001044 }
1045
1046 @Override
1047 public void onReceivedTouchIconUrl(WebView view, String url,
1048 boolean precomposed) {
1049 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001050 // Let precomposed icons take precedence over non-composed
1051 // icons.
1052 if (precomposed && mTouchIconLoader != null) {
1053 mTouchIconLoader.cancel(false);
1054 mTouchIconLoader = null;
1055 }
1056 // Have only one async task at a time.
1057 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001058 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001059 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 }
1061 }
1062
1063 @Override
1064 public void onShowCustomView(View view,
1065 WebChromeClient.CustomViewCallback callback) {
1066 if (mInForeground) mActivity.onShowCustomView(view, callback);
1067 }
1068
1069 @Override
1070 public void onHideCustomView() {
1071 if (mInForeground) mActivity.onHideCustomView();
1072 }
1073
1074 /**
1075 * The origin has exceeded its database quota.
1076 * @param url the URL that exceeded the quota
1077 * @param databaseIdentifier the identifier of the database on which the
1078 * transaction that caused the quota overflow was run
1079 * @param currentQuota the current quota for the origin.
1080 * @param estimatedSize the estimated size of the database.
1081 * @param totalUsedQuota is the sum of all origins' quota.
1082 * @param quotaUpdater The callback to run when a decision to allow or
1083 * deny quota has been made. Don't forget to call this!
1084 */
1085 @Override
1086 public void onExceededDatabaseQuota(String url,
1087 String databaseIdentifier, long currentQuota, long estimatedSize,
1088 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1089 BrowserSettings.getInstance().getWebStorageSizeManager()
1090 .onExceededDatabaseQuota(url, databaseIdentifier,
1091 currentQuota, estimatedSize, totalUsedQuota,
1092 quotaUpdater);
1093 }
1094
1095 /**
1096 * The Application Cache has exceeded its max size.
1097 * @param spaceNeeded is the amount of disk space that would be needed
1098 * in order for the last appcache operation to succeed.
1099 * @param totalUsedQuota is the sum of all origins' quota.
1100 * @param quotaUpdater A callback to inform the WebCore thread that a
1101 * new app cache size is available. This callback must always
1102 * be executed at some point to ensure that the sleeping
1103 * WebCore thread is woken up.
1104 */
1105 @Override
1106 public void onReachedMaxAppCacheSize(long spaceNeeded,
1107 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1108 BrowserSettings.getInstance().getWebStorageSizeManager()
1109 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1110 quotaUpdater);
1111 }
1112
1113 /**
1114 * Instructs the browser to show a prompt to ask the user to set the
1115 * Geolocation permission state for the specified origin.
1116 * @param origin The origin for which Geolocation permissions are
1117 * requested.
1118 * @param callback The callback to call once the user has set the
1119 * Geolocation permission state.
1120 */
1121 @Override
1122 public void onGeolocationPermissionsShowPrompt(String origin,
1123 GeolocationPermissions.Callback callback) {
1124 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001125 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001126 }
1127 }
1128
1129 /**
1130 * Instructs the browser to hide the Geolocation permissions prompt.
1131 */
1132 @Override
1133 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001134 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001135 mGeolocationPermissionsPrompt.hide();
1136 }
1137 }
1138
Ben Murdoch65acc352009-11-19 18:16:04 +00001139 /* Adds a JavaScript error message to the system log and if the JS
1140 * console is enabled in the about:debug options, to that console
1141 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001142 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001143 */
1144 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001145 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001146 if (mInForeground) {
1147 // call getErrorConsole(true) so it will create one if needed
1148 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001149 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001150 if (mActivity.shouldShowErrorConsole()
1151 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1152 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1153 }
1154 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001155
Jeff Hamilton47654f42010-09-07 09:57:51 -05001156 // Don't log console messages in private browsing mode
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001157 if (isPrivateBrowsingEnabled()) return true;
Jeff Hamilton47654f42010-09-07 09:57:51 -05001158
Ben Murdochc42addf2010-01-28 15:19:59 +00001159 String message = "Console: " + consoleMessage.message() + " "
1160 + consoleMessage.sourceId() + ":"
1161 + consoleMessage.lineNumber();
1162
1163 switch (consoleMessage.messageLevel()) {
1164 case TIP:
1165 Log.v(CONSOLE_LOGTAG, message);
1166 break;
1167 case LOG:
1168 Log.i(CONSOLE_LOGTAG, message);
1169 break;
1170 case WARNING:
1171 Log.w(CONSOLE_LOGTAG, message);
1172 break;
1173 case ERROR:
1174 Log.e(CONSOLE_LOGTAG, message);
1175 break;
1176 case DEBUG:
1177 Log.d(CONSOLE_LOGTAG, message);
1178 break;
1179 }
1180
1181 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001182 }
1183
1184 /**
1185 * Ask the browser for an icon to represent a <video> element.
1186 * This icon will be used if the Web page did not specify a poster attribute.
1187 * @return Bitmap The icon or null if no such icon is available.
1188 */
1189 @Override
1190 public Bitmap getDefaultVideoPoster() {
1191 if (mInForeground) {
1192 return mActivity.getDefaultVideoPoster();
1193 }
1194 return null;
1195 }
1196
1197 /**
1198 * Ask the host application for a custom progress view to show while
1199 * a <video> is loading.
1200 * @return View The progress view.
1201 */
1202 @Override
1203 public View getVideoLoadingProgressView() {
1204 if (mInForeground) {
1205 return mActivity.getVideoLoadingProgressView();
1206 }
1207 return null;
1208 }
1209
1210 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001211 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001212 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001213 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001214 } else {
1215 uploadMsg.onReceiveValue(null);
1216 }
1217 }
1218
1219 /**
1220 * Deliver a list of already-visited URLs
1221 */
1222 @Override
1223 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1224 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
Michael Kolbfe251992010-07-08 15:41:55 -07001225 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001226 public String[] doInBackground(Void... unused) {
1227 return Browser.getVisitedHistory(mActivity
1228 .getContentResolver());
1229 }
Michael Kolbfe251992010-07-08 15:41:55 -07001230 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001231 public void onPostExecute(String[] result) {
1232 callback.onReceiveValue(result);
1233 };
1234 };
1235 task.execute();
1236 };
1237 };
1238
1239 // -------------------------------------------------------------------------
1240 // WebViewClient implementation for the sub window
1241 // -------------------------------------------------------------------------
1242
1243 // Subclass of WebViewClient used in subwindows to notify the main
1244 // WebViewClient of certain WebView activities.
1245 private static class SubWindowClient extends WebViewClient {
1246 // The main WebViewClient.
1247 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001248 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001249
Leon Scroggins III211ba542010-04-19 13:21:13 -04001250 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001251 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001252 mBrowserActivity = activity;
1253 }
1254 @Override
1255 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1256 // Unlike the others, do not call mClient's version, which would
1257 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001258 // find or select dialog.
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001259 mBrowserActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001260 }
1261 @Override
1262 public void doUpdateVisitedHistory(WebView view, String url,
1263 boolean isReload) {
1264 mClient.doUpdateVisitedHistory(view, url, isReload);
1265 }
1266 @Override
1267 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1268 return mClient.shouldOverrideUrlLoading(view, url);
1269 }
1270 @Override
1271 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1272 SslError error) {
1273 mClient.onReceivedSslError(view, handler, error);
1274 }
1275 @Override
1276 public void onReceivedHttpAuthRequest(WebView view,
1277 HttpAuthHandler handler, String host, String realm) {
1278 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1279 }
1280 @Override
1281 public void onFormResubmission(WebView view, Message dontResend,
1282 Message resend) {
1283 mClient.onFormResubmission(view, dontResend, resend);
1284 }
1285 @Override
1286 public void onReceivedError(WebView view, int errorCode,
1287 String description, String failingUrl) {
1288 mClient.onReceivedError(view, errorCode, description, failingUrl);
1289 }
1290 @Override
1291 public boolean shouldOverrideKeyEvent(WebView view,
1292 android.view.KeyEvent event) {
1293 return mClient.shouldOverrideKeyEvent(view, event);
1294 }
1295 @Override
1296 public void onUnhandledKeyEvent(WebView view,
1297 android.view.KeyEvent event) {
1298 mClient.onUnhandledKeyEvent(view, event);
1299 }
1300 }
1301
1302 // -------------------------------------------------------------------------
1303 // WebChromeClient implementation for the sub window
1304 // -------------------------------------------------------------------------
1305
1306 private class SubWindowChromeClient extends WebChromeClient {
1307 // The main WebChromeClient.
1308 private final WebChromeClient mClient;
1309
1310 SubWindowChromeClient(WebChromeClient client) {
1311 mClient = client;
1312 }
1313 @Override
1314 public void onProgressChanged(WebView view, int newProgress) {
1315 mClient.onProgressChanged(view, newProgress);
1316 }
1317 @Override
1318 public boolean onCreateWindow(WebView view, boolean dialog,
1319 boolean userGesture, android.os.Message resultMsg) {
1320 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1321 }
1322 @Override
1323 public void onCloseWindow(WebView window) {
1324 if (window != mSubView) {
1325 Log.e(LOGTAG, "Can't close the window");
1326 }
1327 mActivity.dismissSubWindow(Tab.this);
1328 }
1329 }
1330
1331 // -------------------------------------------------------------------------
1332
1333 // Construct a new tab
1334 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1335 String url) {
1336 mActivity = activity;
1337 mCloseOnExit = closeOnExit;
1338 mAppId = appId;
1339 mOriginalUrl = url;
1340 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1341 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1342 mInLoad = false;
1343 mInForeground = false;
1344
1345 mInflateService = LayoutInflater.from(activity);
1346
1347 // The tab consists of a container view, which contains the main
1348 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001349 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001350
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001351 mDownloadListener = new DownloadListener() {
1352 public void onDownloadStart(String url, String userAgent,
1353 String contentDisposition, String mimetype,
1354 long contentLength) {
1355 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1356 mimetype, contentLength);
1357 if (mMainView.copyBackForwardList().getSize() == 0) {
1358 // This Tab was opened for the sole purpose of downloading a
1359 // file. Remove it.
1360 if (mActivity.getTabControl().getCurrentWebView()
1361 == mMainView) {
1362 // In this case, the Tab is still on top.
1363 mActivity.goBackOnePageOrQuit();
1364 } else {
1365 // In this case, it is not.
1366 mActivity.closeTab(Tab.this);
1367 }
1368 }
1369 }
1370 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001371 mWebBackForwardListClient = new WebBackForwardListClient() {
1372 @Override
1373 public void onNewHistoryItem(WebHistoryItem item) {
1374 if (isInVoiceSearchMode()) {
1375 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1376 }
1377 }
1378 @Override
1379 public void onIndexChanged(WebHistoryItem item, int index) {
1380 Object data = item.getCustomData();
1381 if (data != null && data instanceof Intent) {
1382 activateVoiceSearchMode((Intent) data);
1383 }
1384 }
1385 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001386
Grace Kloba22ac16e2009-10-07 18:00:23 -07001387 setWebView(w);
1388 }
1389
1390 /**
1391 * Sets the WebView for this tab, correctly removing the old WebView from
1392 * the container view.
1393 */
1394 void setWebView(WebView w) {
1395 if (mMainView == w) {
1396 return;
1397 }
1398 // If the WebView is changing, the page will be reloaded, so any ongoing
1399 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001400 if (mGeolocationPermissionsPrompt != null) {
1401 mGeolocationPermissionsPrompt.hide();
1402 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001403
1404 // Just remove the old one.
1405 FrameLayout wrapper =
1406 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1407 wrapper.removeView(mMainView);
1408
1409 // set the new one
1410 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001411 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001412 if (mMainView != null) {
1413 mMainView.setWebViewClient(mWebViewClient);
1414 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001415 // Attach DownloadManager so that downloads can start in an active
1416 // or a non-active window. This can happen when going to a site that
1417 // does a redirect after a period of time. The user could have
1418 // switched to another tab while waiting for the download to start.
1419 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001420 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001421 }
1422 }
1423
1424 /**
1425 * Destroy the tab's main WebView and subWindow if any
1426 */
1427 void destroy() {
1428 if (mMainView != null) {
1429 dismissSubWindow();
1430 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1431 // save the WebView to call destroy() after detach it from the tab
1432 WebView webView = mMainView;
1433 setWebView(null);
1434 webView.destroy();
1435 }
1436 }
1437
1438 /**
1439 * Remove the tab from the parent
1440 */
1441 void removeFromTree() {
1442 // detach the children
1443 if (mChildTabs != null) {
1444 for(Tab t : mChildTabs) {
1445 t.setParentTab(null);
1446 }
1447 }
1448 // remove itself from the parent list
1449 if (mParentTab != null) {
1450 mParentTab.mChildTabs.remove(this);
1451 }
1452 }
1453
1454 /**
1455 * Create a new subwindow unless a subwindow already exists.
1456 * @return True if a new subwindow was created. False if one already exists.
1457 */
1458 boolean createSubWindow() {
1459 if (mSubView == null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001460 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001461 mSubViewContainer = mInflateService.inflate(
1462 R.layout.browser_subwindow, null);
1463 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001464 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001465 // use trackball directly
1466 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001467 // Enable the built-in zoom
1468 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001469 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1470 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001471 mSubView.setWebChromeClient(new SubWindowChromeClient(
1472 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001473 // Set a different DownloadListener for the mSubView, since it will
1474 // just need to dismiss the mSubView, rather than close the Tab
1475 mSubView.setDownloadListener(new DownloadListener() {
1476 public void onDownloadStart(String url, String userAgent,
1477 String contentDisposition, String mimetype,
1478 long contentLength) {
1479 mActivity.onDownloadStart(url, userAgent,
1480 contentDisposition, mimetype, contentLength);
1481 if (mSubView.copyBackForwardList().getSize() == 0) {
1482 // This subwindow was opened for the sole purpose of
1483 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001484 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001485 }
1486 }
1487 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001488 mSubView.setOnCreateContextMenuListener(mActivity);
1489 final BrowserSettings s = BrowserSettings.getInstance();
1490 s.addObserver(mSubView.getSettings()).update(s, null);
1491 final ImageButton cancel = (ImageButton) mSubViewContainer
1492 .findViewById(R.id.subwindow_close);
1493 cancel.setOnClickListener(new OnClickListener() {
1494 public void onClick(View v) {
1495 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1496 }
1497 });
1498 return true;
1499 }
1500 return false;
1501 }
1502
1503 /**
1504 * Dismiss the subWindow for the tab.
1505 */
1506 void dismissSubWindow() {
1507 if (mSubView != null) {
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001508 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001509 BrowserSettings.getInstance().deleteObserver(
1510 mSubView.getSettings());
1511 mSubView.destroy();
1512 mSubView = null;
1513 mSubViewContainer = null;
1514 }
1515 }
1516
1517 /**
1518 * Attach the sub window to the content view.
1519 */
1520 void attachSubWindow(ViewGroup content) {
1521 if (mSubView != null) {
1522 content.addView(mSubViewContainer,
1523 BrowserActivity.COVER_SCREEN_PARAMS);
1524 }
1525 }
1526
1527 /**
1528 * Remove the sub window from the content view.
1529 */
1530 void removeSubWindow(ViewGroup content) {
1531 if (mSubView != null) {
1532 content.removeView(mSubViewContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001533 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001534 }
1535 }
1536
1537 /**
1538 * This method attaches both the WebView and any sub window to the
1539 * given content view.
1540 */
1541 void attachTabToContentView(ViewGroup content) {
1542 if (mMainView == null) {
1543 return;
1544 }
1545
1546 // Attach the WebView to the container and then attach the
1547 // container to the content view.
1548 FrameLayout wrapper =
1549 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001550 ViewGroup parent = (ViewGroup) mMainView.getParent();
1551 if (parent != wrapper) {
1552 if (parent != null) {
1553 Log.w(LOGTAG, "mMainView already has a parent in"
1554 + " attachTabToContentView!");
1555 parent.removeView(mMainView);
1556 }
1557 wrapper.addView(mMainView);
1558 } else {
1559 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1560 + " attachTabToContentView!");
1561 }
1562 parent = (ViewGroup) mContainer.getParent();
1563 if (parent != content) {
1564 if (parent != null) {
1565 Log.w(LOGTAG, "mContainer already has a parent in"
1566 + " attachTabToContentView!");
1567 parent.removeView(mContainer);
1568 }
1569 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1570 } else {
1571 Log.w(LOGTAG, "mContainer is already attached to content in"
1572 + " attachTabToContentView!");
1573 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001574 attachSubWindow(content);
1575 }
1576
1577 /**
1578 * Remove the WebView and any sub window from the given content view.
1579 */
1580 void removeTabFromContentView(ViewGroup content) {
1581 if (mMainView == null) {
1582 return;
1583 }
1584
1585 // Remove the container from the content and then remove the
1586 // WebView from the container. This will trigger a focus change
1587 // needed by WebView.
1588 FrameLayout wrapper =
1589 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1590 wrapper.removeView(mMainView);
1591 content.removeView(mContainer);
Leon Scroggins III8e4fbf12010-08-17 16:58:15 -04001592 mActivity.endActionMode();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001593 removeSubWindow(content);
1594 }
1595
1596 /**
1597 * Set the parent tab of this tab.
1598 */
1599 void setParentTab(Tab parent) {
1600 mParentTab = parent;
1601 // This tab may have been freed due to low memory. If that is the case,
1602 // the parent tab index is already saved. If we are changing that index
1603 // (most likely due to removing the parent tab) we must update the
1604 // parent tab index in the saved Bundle.
1605 if (mSavedState != null) {
1606 if (parent == null) {
1607 mSavedState.remove(PARENTTAB);
1608 } else {
1609 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1610 .getTabIndex(parent));
1611 }
1612 }
1613 }
1614
1615 /**
1616 * When a Tab is created through the content of another Tab, then we
1617 * associate the Tabs.
1618 * @param child the Tab that was created from this Tab
1619 */
1620 void addChildTab(Tab child) {
1621 if (mChildTabs == null) {
1622 mChildTabs = new Vector<Tab>();
1623 }
1624 mChildTabs.add(child);
1625 child.setParentTab(this);
1626 }
1627
1628 Vector<Tab> getChildTabs() {
1629 return mChildTabs;
1630 }
1631
1632 void resume() {
1633 if (mMainView != null) {
1634 mMainView.onResume();
1635 if (mSubView != null) {
1636 mSubView.onResume();
1637 }
1638 }
1639 }
1640
1641 void pause() {
1642 if (mMainView != null) {
1643 mMainView.onPause();
1644 if (mSubView != null) {
1645 mSubView.onPause();
1646 }
1647 }
1648 }
1649
1650 void putInForeground() {
1651 mInForeground = true;
1652 resume();
1653 mMainView.setOnCreateContextMenuListener(mActivity);
1654 if (mSubView != null) {
1655 mSubView.setOnCreateContextMenuListener(mActivity);
1656 }
1657 // Show the pending error dialog if the queue is not empty
1658 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1659 showError(mQueuedErrors.getFirst());
1660 }
1661 }
1662
1663 void putInBackground() {
1664 mInForeground = false;
1665 pause();
1666 mMainView.setOnCreateContextMenuListener(null);
1667 if (mSubView != null) {
1668 mSubView.setOnCreateContextMenuListener(null);
1669 }
1670 }
1671
1672 /**
1673 * Return the top window of this tab; either the subwindow if it is not
1674 * null or the main window.
1675 * @return The top window of this tab.
1676 */
1677 WebView getTopWindow() {
1678 if (mSubView != null) {
1679 return mSubView;
1680 }
1681 return mMainView;
1682 }
1683
1684 /**
1685 * Return the main window of this tab. Note: if a tab is freed in the
1686 * background, this can return null. It is only guaranteed to be
1687 * non-null for the current tab.
1688 * @return The main WebView of this tab.
1689 */
1690 WebView getWebView() {
1691 return mMainView;
1692 }
1693
1694 /**
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001695 * Return whether private browsing is enabled for the main window of
1696 * this tab.
1697 * @return True if private browsing is enabled.
1698 */
1699 private boolean isPrivateBrowsingEnabled() {
1700 WebView webView = getWebView();
1701 if (webView == null) {
1702 return false;
1703 }
1704 return webView.isPrivateBrowsingEnabled();
1705 }
1706
1707 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -07001708 * Return the subwindow of this tab or null if there is no subwindow.
1709 * @return The subwindow of this tab or null.
1710 */
1711 WebView getSubWebView() {
1712 return mSubView;
1713 }
1714
1715 /**
1716 * @return The geolocation permissions prompt for this tab.
1717 */
1718 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001719 if (mGeolocationPermissionsPrompt == null) {
1720 ViewStub stub = (ViewStub) mContainer
1721 .findViewById(R.id.geolocation_permissions_prompt);
1722 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1723 .inflate();
1724 mGeolocationPermissionsPrompt.init();
1725 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001726 return mGeolocationPermissionsPrompt;
1727 }
1728
1729 /**
1730 * @return The application id string
1731 */
1732 String getAppId() {
1733 return mAppId;
1734 }
1735
1736 /**
1737 * Set the application id string
1738 * @param id
1739 */
1740 void setAppId(String id) {
1741 mAppId = id;
1742 }
1743
1744 /**
1745 * @return The original url associated with this Tab
1746 */
1747 String getOriginalUrl() {
1748 return mOriginalUrl;
1749 }
1750
1751 /**
1752 * Set the original url associated with this tab
1753 */
1754 void setOriginalUrl(String url) {
1755 mOriginalUrl = url;
1756 }
1757
1758 /**
1759 * Get the url of this tab. Valid after calling populatePickerData, but
1760 * before calling wipePickerData, or if the webview has been destroyed.
1761 * @return The WebView's url or null.
1762 */
1763 String getUrl() {
1764 if (mPickerData != null) {
1765 return mPickerData.mUrl;
1766 }
1767 return null;
1768 }
1769
1770 /**
1771 * Get the title of this tab. Valid after calling populatePickerData, but
1772 * before calling wipePickerData, or if the webview has been destroyed. If
1773 * the url has no title, use the url instead.
1774 * @return The WebView's title (or url) or null.
1775 */
1776 String getTitle() {
1777 if (mPickerData != null) {
1778 return mPickerData.mTitle;
1779 }
1780 return null;
1781 }
1782
1783 /**
1784 * Get the favicon of this tab. Valid after calling populatePickerData, but
1785 * before calling wipePickerData, or if the webview has been destroyed.
1786 * @return The WebView's favicon or null.
1787 */
1788 Bitmap getFavicon() {
1789 if (mPickerData != null) {
1790 return mPickerData.mFavicon;
1791 }
1792 return null;
1793 }
1794
Rob Tsukf8bdfce2010-10-07 15:41:16 -07001795 /*
1796 * Update the favorites icon if the private browsing isn't enabled and the
1797 * icon is valid.
1798 */
1799 void maybeUpdateFavicon(final String originalUrl, final String url, Bitmap favicon) {
1800 if (favicon == null) {
1801 return;
1802 }
1803 if (!isPrivateBrowsingEnabled()) {
1804 Bookmarks.updateFavicon(mActivity
1805 .getContentResolver(), originalUrl, url, favicon);
1806 }
1807 }
1808
Grace Kloba22ac16e2009-10-07 18:00:23 -07001809 /**
1810 * Return the tab's error console. Creates the console if createIfNEcessary
1811 * is true and we haven't already created the console.
1812 * @param createIfNecessary Flag to indicate if the console should be
1813 * created if it has not been already.
1814 * @return The tab's error console, or null if one has not been created and
1815 * createIfNecessary is false.
1816 */
1817 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1818 if (createIfNecessary && mErrorConsole == null) {
1819 mErrorConsole = new ErrorConsoleView(mActivity);
1820 mErrorConsole.setWebView(mMainView);
1821 }
1822 return mErrorConsole;
1823 }
1824
1825 /**
1826 * If this Tab was created through another Tab, then this method returns
1827 * that Tab.
1828 * @return the Tab parent or null
1829 */
1830 public Tab getParentTab() {
1831 return mParentTab;
1832 }
1833
1834 /**
1835 * Return whether this tab should be closed when it is backing out of the
1836 * first page.
1837 * @return TRUE if this tab should be closed when exit.
1838 */
1839 boolean closeOnExit() {
1840 return mCloseOnExit;
1841 }
1842
1843 /**
1844 * Saves the current lock-icon state before resetting the lock icon. If we
1845 * have an error, we may need to roll back to the previous state.
1846 */
1847 void resetLockIcon(String url) {
1848 mPrevLockIconType = mLockIconType;
1849 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1850 if (URLUtil.isHttpsUrl(url)) {
1851 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1852 }
1853 }
1854
1855 /**
1856 * Reverts the lock-icon state to the last saved state, for example, if we
1857 * had an error, and need to cancel the load.
1858 */
1859 void revertLockIcon() {
1860 mLockIconType = mPrevLockIconType;
1861 }
1862
1863 /**
1864 * @return The tab's lock icon type.
1865 */
1866 int getLockIconType() {
1867 return mLockIconType;
1868 }
1869
1870 /**
1871 * @return TRUE if onPageStarted is called while onPageFinished is not
1872 * called yet.
1873 */
1874 boolean inLoad() {
1875 return mInLoad;
1876 }
1877
1878 // force mInLoad to be false. This should only be called before closing the
1879 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1880 void clearInLoad() {
1881 mInLoad = false;
1882 }
1883
1884 void populatePickerData() {
1885 if (mMainView == null) {
1886 populatePickerDataFromSavedState();
1887 return;
1888 }
1889
1890 // FIXME: The only place we cared about subwindow was for
1891 // bookmarking (i.e. not when saving state). Was this deliberate?
1892 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001893 if (list == null) {
1894 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1895 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001896 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1897 populatePickerData(item);
1898 }
1899
1900 // Populate the picker data using the given history item and the current top
1901 // WebView.
1902 private void populatePickerData(WebHistoryItem item) {
1903 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001904 if (item == null) {
1905 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1906 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001907 mPickerData.mUrl = item.getUrl();
1908 mPickerData.mTitle = item.getTitle();
1909 mPickerData.mFavicon = item.getFavicon();
1910 if (mPickerData.mTitle == null) {
1911 mPickerData.mTitle = mPickerData.mUrl;
1912 }
1913 }
1914 }
1915
1916 // Create the PickerData and populate it using the saved state of the tab.
1917 void populatePickerDataFromSavedState() {
1918 if (mSavedState == null) {
1919 return;
1920 }
1921 mPickerData = new PickerData();
1922 mPickerData.mUrl = mSavedState.getString(CURRURL);
1923 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1924 }
1925
1926 void clearPickerData() {
1927 mPickerData = null;
1928 }
1929
1930 /**
1931 * Get the saved state bundle.
1932 * @return
1933 */
1934 Bundle getSavedState() {
1935 return mSavedState;
1936 }
1937
1938 /**
1939 * Set the saved state.
1940 */
1941 void setSavedState(Bundle state) {
1942 mSavedState = state;
1943 }
1944
1945 /**
1946 * @return TRUE if succeed in saving the state.
1947 */
1948 boolean saveState() {
1949 // If the WebView is null it means we ran low on memory and we already
1950 // stored the saved state in mSavedState.
1951 if (mMainView == null) {
1952 return mSavedState != null;
1953 }
1954
1955 mSavedState = new Bundle();
1956 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001957
1958 // Store some extra info for displaying the tab in the picker.
1959 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1960 populatePickerData(item);
1961
1962 if (mPickerData.mUrl != null) {
1963 mSavedState.putString(CURRURL, mPickerData.mUrl);
1964 }
1965 if (mPickerData.mTitle != null) {
1966 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1967 }
1968 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1969 if (mAppId != null) {
1970 mSavedState.putString(APPID, mAppId);
1971 }
1972 if (mOriginalUrl != null) {
1973 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1974 }
1975 // Remember the parent tab so the relationship can be restored.
1976 if (mParentTab != null) {
1977 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1978 mParentTab));
1979 }
1980 return true;
1981 }
1982
1983 /*
1984 * Restore the state of the tab.
1985 */
1986 boolean restoreState(Bundle b) {
1987 if (b == null) {
1988 return false;
1989 }
1990 // Restore the internal state even if the WebView fails to restore.
1991 // This will maintain the app id, original url and close-on-exit values.
1992 mSavedState = null;
1993 mPickerData = null;
1994 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1995 mAppId = b.getString(APPID);
1996 mOriginalUrl = b.getString(ORIGINALURL);
1997
1998 final WebBackForwardList list = mMainView.restoreState(b);
1999 if (list == null) {
2000 return false;
2001 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002002 return true;
2003 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04002004
Michael Kolbfe251992010-07-08 15:41:55 -07002005 /**
2006 * always get the TabChangeListener form the tab control
2007 * @return the TabControl change listener
2008 */
2009 private TabChangeListener getTabChangeListener() {
2010 return mActivity.getTabControl().getTabChangeListener();
2011 }
2012
Grace Kloba22ac16e2009-10-07 18:00:23 -07002013}