blob: 6b74a6c8ded827079f34b3030559d50760c8345c [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
19import java.io.File;
Leon Scroggins58d56c62010-01-28 15:12:40 -050020import java.util.ArrayList;
Leon Scroggins9df94972010-03-08 18:20:35 -050021import java.util.HashMap;
22import java.util.Iterator;
Grace Kloba22ac16e2009-10-07 18:00:23 -070023import java.util.LinkedList;
Leon Scroggins9df94972010-03-08 18:20:35 -050024import java.util.Map;
Grace Kloba22ac16e2009-10-07 18:00:23 -070025import java.util.Vector;
26
27import android.app.AlertDialog;
Leon Scroggins58d56c62010-01-28 15:12:40 -050028import android.app.SearchManager;
Grace Kloba22ac16e2009-10-07 18:00:23 -070029import android.content.ContentResolver;
30import android.content.ContentValues;
31import android.content.DialogInterface;
32import android.content.DialogInterface.OnCancelListener;
Leon Scroggins58d56c62010-01-28 15:12:40 -050033import android.content.Intent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070034import android.database.Cursor;
35import android.database.sqlite.SQLiteDatabase;
36import android.database.sqlite.SQLiteException;
37import android.graphics.Bitmap;
38import android.net.Uri;
39import android.net.http.SslError;
40import android.os.AsyncTask;
41import android.os.Bundle;
42import android.os.Message;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +000043import android.os.SystemClock;
Grace Kloba22ac16e2009-10-07 18:00:23 -070044import android.provider.Browser;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050045import android.speech.RecognizerResultsIntent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070046import android.util.Log;
47import android.view.KeyEvent;
48import android.view.LayoutInflater;
49import android.view.View;
50import android.view.ViewGroup;
Grace Kloba50c241e2010-04-20 11:07:50 -070051import android.view.ViewStub;
Grace Kloba22ac16e2009-10-07 18:00:23 -070052import android.view.View.OnClickListener;
Ben Murdochc42addf2010-01-28 15:19:59 +000053import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070054import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050055import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070056import android.webkit.GeolocationPermissions;
57import android.webkit.HttpAuthHandler;
58import android.webkit.SslErrorHandler;
59import android.webkit.URLUtil;
60import android.webkit.ValueCallback;
61import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050062import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070063import android.webkit.WebChromeClient;
64import android.webkit.WebHistoryItem;
65import android.webkit.WebIconDatabase;
66import android.webkit.WebStorage;
67import android.webkit.WebView;
68import android.webkit.WebViewClient;
69import android.widget.FrameLayout;
70import android.widget.ImageButton;
71import android.widget.LinearLayout;
72import android.widget.TextView;
73
Leon Scroggins1fe13a52010-02-09 15:31:26 -050074import com.android.common.speech.LoggingEvents;
75
Grace Kloba22ac16e2009-10-07 18:00:23 -070076/**
77 * Class for maintaining Tabs with a main WebView and a subwindow.
78 */
79class Tab {
80 // Log Tag
81 private static final String LOGTAG = "Tab";
Ben Murdochc42addf2010-01-28 15:19:59 +000082 // Special case the logtag for messages for the Console to make it easier to
83 // filter them and match the logtag used for these messages in older versions
84 // of the browser.
85 private static final String CONSOLE_LOGTAG = "browser";
86
Grace Kloba22ac16e2009-10-07 18:00:23 -070087 // The Geolocation permissions prompt
88 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
89 // Main WebView wrapper
Leon Scroggins III211ba542010-04-19 13:21:13 -040090 private LinearLayout mContainer;
Grace Kloba22ac16e2009-10-07 18:00:23 -070091 // Main WebView
92 private WebView mMainView;
93 // Subwindow container
94 private View mSubViewContainer;
95 // Subwindow WebView
96 private WebView mSubView;
97 // Saved bundle for when we are running low on memory. It contains the
98 // information needed to restore the WebView if the user goes back to the
99 // tab.
100 private Bundle mSavedState;
101 // Data used when displaying the tab in the picker.
102 private PickerData mPickerData;
103 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
104 // created by the UI
105 private Tab mParentTab;
106 // Tab that constructed by this Tab. This is used when this Tab is
107 // destroyed, it clears all mParentTab values in the children.
108 private Vector<Tab> mChildTabs;
109 // If true, the tab will be removed when back out of the first page.
110 private boolean mCloseOnExit;
111 // If true, the tab is in the foreground of the current activity.
112 private boolean mInForeground;
113 // If true, the tab is in loading state.
114 private boolean mInLoad;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000115 // The time the load started, used to find load page time
116 private long mLoadStartTime;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700117 // Application identifier used to find tabs that another application wants
118 // to reuse.
119 private String mAppId;
120 // Keep the original url around to avoid killing the old WebView if the url
121 // has not changed.
122 private String mOriginalUrl;
123 // Error console for the tab
124 private ErrorConsoleView mErrorConsole;
125 // the lock icon type and previous lock icon type for the tab
126 private int mLockIconType;
127 private int mPrevLockIconType;
128 // Inflation service for making subwindows.
129 private final LayoutInflater mInflateService;
130 // The BrowserActivity which owners the Tab
131 private final BrowserActivity mActivity;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -0500132 // The listener that gets invoked when a download is started from the
133 // mMainView
134 private final DownloadListener mDownloadListener;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500135 // Listener used to know when we move forward or back in the history list.
136 private final WebBackForwardListClient mWebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700137
138 // AsyncTask for downloading touch icons
139 DownloadTouchIcon mTouchIconLoader;
140
141 // Extra saved information for displaying the tab in the picker.
142 private static class PickerData {
143 String mUrl;
144 String mTitle;
145 Bitmap mFavicon;
146 }
147
148 // Used for saving and restoring each Tab
149 static final String WEBVIEW = "webview";
150 static final String NUMTABS = "numTabs";
151 static final String CURRTAB = "currentTab";
152 static final String CURRURL = "currentUrl";
153 static final String CURRTITLE = "currentTitle";
Grace Kloba22ac16e2009-10-07 18:00:23 -0700154 static final String CLOSEONEXIT = "closeonexit";
155 static final String PARENTTAB = "parentTab";
156 static final String APPID = "appid";
157 static final String ORIGINALURL = "originalUrl";
158
159 // -------------------------------------------------------------------------
160
Leon Scroggins58d56c62010-01-28 15:12:40 -0500161 /**
162 * Private information regarding the latest voice search. If the Tab is not
163 * in voice search mode, this will be null.
164 */
165 private VoiceSearchData mVoiceSearchData;
166 /**
167 * Return whether the tab is in voice search mode.
168 */
169 public boolean isInVoiceSearchMode() {
170 return mVoiceSearchData != null;
171 }
172 /**
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400173 * Return true if the Tab is in voice search mode and the voice search
174 * Intent came with a String identifying that Google provided the Intent.
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500175 */
176 public boolean voiceSearchSourceIsGoogle() {
177 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
178 }
179 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500180 * Get the title to display for the current voice search page. If the Tab
181 * is not in voice search mode, return null.
182 */
183 public String getVoiceDisplayTitle() {
184 if (mVoiceSearchData == null) return null;
185 return mVoiceSearchData.mLastVoiceSearchTitle;
186 }
187 /**
188 * Get the latest array of voice search results, to be passed to the
189 * BrowserProvider. If the Tab is not in voice search mode, return null.
190 */
191 public ArrayList<String> getVoiceSearchResults() {
192 if (mVoiceSearchData == null) return null;
193 return mVoiceSearchData.mVoiceSearchResults;
194 }
195 /**
196 * Activate voice search mode.
197 * @param intent Intent which has the results to use, or an index into the
198 * results when reusing the old results.
199 */
200 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500201 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500202 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500203 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500204 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500205 ArrayList<String> urls = intent.getStringArrayListExtra(
206 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
207 ArrayList<String> htmls = intent.getStringArrayListExtra(
208 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
209 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
210 RecognizerResultsIntent
211 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500212 // This tab is now entering voice search mode for the first time, or
213 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500214 int size = results.size();
215 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500216 throw new AssertionError("improper extras passed in Intent");
217 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500218 if (htmls == null || htmls.size() != size || baseUrls == null ||
219 (baseUrls.size() != size && baseUrls.size() != 1)) {
220 // If either of these arrays are empty/incorrectly sized, ignore
221 // them.
222 htmls = null;
223 baseUrls = null;
224 }
225 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
226 baseUrls);
Leon Scroggins9df94972010-03-08 18:20:35 -0500227 mVoiceSearchData.mHeaders = intent.getParcelableArrayListExtra(
228 RecognizerResultsIntent
229 .EXTRA_VOICE_SEARCH_RESULT_HTTP_HEADERS);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500230 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
231 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400232 mVoiceSearchData.mVoiceSearchIntent = new Intent(intent);
Leon Scrogginse10dde52010-03-08 19:53:03 -0500233 }
234 String extraData = intent.getStringExtra(
235 SearchManager.EXTRA_DATA_KEY);
236 if (extraData != null) {
237 index = Integer.parseInt(extraData);
238 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
239 throw new AssertionError("index must be less than "
240 + "size of mVoiceSearchResults");
241 }
242 if (mVoiceSearchData.mSourceIsGoogle) {
243 Intent logIntent = new Intent(
244 LoggingEvents.ACTION_LOG_EVENT);
245 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
246 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
247 logIntent.putExtra(
248 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
249 index);
250 mActivity.sendBroadcast(logIntent);
251 }
252 if (mVoiceSearchData.mVoiceSearchIntent != null) {
Leon Scroggins2ee4a5a2010-03-15 16:56:57 -0400253 // Copy the Intent, so that each history item will have its own
254 // Intent, with different (or none) extra data.
255 Intent latest = new Intent(mVoiceSearchData.mVoiceSearchIntent);
256 latest.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
257 mVoiceSearchData.mVoiceSearchIntent = latest;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500258 }
259 }
260 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500261 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500262 if (mInForeground) {
263 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
264 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500265 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
266 // When index was found it was already ensured that it was valid
267 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
268 if (uriString != null) {
269 Uri dataUri = Uri.parse(uriString);
270 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
271 dataUri.getScheme())) {
272 // If there is only one base URL, use it. If there are
273 // more, there will be one for each index, so use the base
274 // URL corresponding to the index.
275 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
276 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
277 index : 0);
278 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
279 mMainView.loadDataWithBaseURL(baseUrl,
280 uriString.substring(RecognizerResultsIntent
281 .URI_SCHEME_INLINE.length() + 1), "text/html",
282 "utf-8", baseUrl);
283 return;
284 }
285 }
286 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500287 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500288 = mVoiceSearchData.mVoiceSearchUrls.get(index);
289 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
290 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
291 mVoiceSearchData.mLastVoiceSearchTitle);
292 }
Leon Scroggins9df94972010-03-08 18:20:35 -0500293 Map<String, String> headers = null;
294 if (mVoiceSearchData.mHeaders != null) {
295 int bundleIndex = mVoiceSearchData.mHeaders.size() == 1 ? 0
296 : index;
297 Bundle bundle = mVoiceSearchData.mHeaders.get(bundleIndex);
298 if (bundle != null && !bundle.isEmpty()) {
299 Iterator<String> iter = bundle.keySet().iterator();
300 headers = new HashMap<String, String>();
301 while (iter.hasNext()) {
302 String key = iter.next();
303 headers.put(key, bundle.getString(key));
304 }
305 }
306 }
307 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl, headers);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500308 }
309 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500310 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500311 ArrayList<String> urls, ArrayList<String> htmls,
312 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500313 mVoiceSearchResults = results;
314 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500315 mVoiceSearchHtmls = htmls;
316 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500317 }
318 /*
319 * ArrayList of suggestions to be displayed when opening the
320 * SearchManager
321 */
322 public ArrayList<String> mVoiceSearchResults;
323 /*
324 * ArrayList of urls, associated with the suggestions in
325 * mVoiceSearchResults.
326 */
327 public ArrayList<String> mVoiceSearchUrls;
328 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500329 * ArrayList holding content to load for each item in
330 * mVoiceSearchResults.
331 */
332 public ArrayList<String> mVoiceSearchHtmls;
333 /*
334 * ArrayList holding base urls for the items in mVoiceSearchResults.
335 * If non null, this will either have the same size as
336 * mVoiceSearchResults or have a size of 1, in which case all will use
337 * the same base url
338 */
339 public ArrayList<String> mVoiceSearchBaseUrls;
340 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500341 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500342 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500343 */
344 public String mLastVoiceSearchUrl;
345 /**
346 * The last title used for voice search. Needed to update the title bar
347 * when switching tabs.
348 */
349 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500350 /**
351 * Whether the Intent which turned on voice search mode contained the
352 * String signifying that Google was the source.
353 */
354 public boolean mSourceIsGoogle;
355 /**
Leon Scroggins9df94972010-03-08 18:20:35 -0500356 * List of headers to be passed into the WebView containing location
357 * information
358 */
359 public ArrayList<Bundle> mHeaders;
360 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500361 * The Intent used to invoke voice search. Placed on the
362 * WebHistoryItem so that when coming back to a previous voice search
363 * page we can again activate voice search.
364 */
Leon Scrogginse10dde52010-03-08 19:53:03 -0500365 public Intent mVoiceSearchIntent;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500366 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500367 * String used to identify Google as the source of voice search.
368 */
369 public static String SOURCE_IS_GOOGLE
370 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500371 }
372
Grace Kloba22ac16e2009-10-07 18:00:23 -0700373 // Container class for the next error dialog that needs to be displayed
374 private class ErrorDialog {
375 public final int mTitle;
376 public final String mDescription;
377 public final int mError;
378 ErrorDialog(int title, String desc, int error) {
379 mTitle = title;
380 mDescription = desc;
381 mError = error;
382 }
383 };
384
385 private void processNextError() {
386 if (mQueuedErrors == null) {
387 return;
388 }
389 // The first one is currently displayed so just remove it.
390 mQueuedErrors.removeFirst();
391 if (mQueuedErrors.size() == 0) {
392 mQueuedErrors = null;
393 return;
394 }
395 showError(mQueuedErrors.getFirst());
396 }
397
398 private DialogInterface.OnDismissListener mDialogListener =
399 new DialogInterface.OnDismissListener() {
400 public void onDismiss(DialogInterface d) {
401 processNextError();
402 }
403 };
404 private LinkedList<ErrorDialog> mQueuedErrors;
405
406 private void queueError(int err, String desc) {
407 if (mQueuedErrors == null) {
408 mQueuedErrors = new LinkedList<ErrorDialog>();
409 }
410 for (ErrorDialog d : mQueuedErrors) {
411 if (d.mError == err) {
412 // Already saw a similar error, ignore the new one.
413 return;
414 }
415 }
416 ErrorDialog errDialog = new ErrorDialog(
417 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
418 R.string.browserFrameFileErrorLabel :
419 R.string.browserFrameNetworkErrorLabel,
420 desc, err);
421 mQueuedErrors.addLast(errDialog);
422
423 // Show the dialog now if the queue was empty and it is in foreground
424 if (mQueuedErrors.size() == 1 && mInForeground) {
425 showError(errDialog);
426 }
427 }
428
429 private void showError(ErrorDialog errDialog) {
430 if (mInForeground) {
431 AlertDialog d = new AlertDialog.Builder(mActivity)
432 .setTitle(errDialog.mTitle)
433 .setMessage(errDialog.mDescription)
434 .setPositiveButton(R.string.ok, null)
435 .create();
436 d.setOnDismissListener(mDialogListener);
437 d.show();
438 }
439 }
440
441 // -------------------------------------------------------------------------
442 // WebViewClient implementation for the main WebView
443 // -------------------------------------------------------------------------
444
445 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500446 private Message mDontResend;
447 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700448 @Override
449 public void onPageStarted(WebView view, String url, Bitmap favicon) {
450 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000451 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500452 if (mVoiceSearchData != null
453 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500454 if (mVoiceSearchData.mSourceIsGoogle) {
455 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
456 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
457 mActivity.sendBroadcast(i);
458 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500459 mVoiceSearchData = null;
460 if (mInForeground) {
461 mActivity.revertVoiceTitleBar();
462 }
463 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700464
465 // We've started to load a new page. If there was a pending message
466 // to save a screenshot then we will now take the new page and save
467 // an incorrect screenshot. Therefore, remove any pending thumbnail
468 // messages from the queue.
469 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
470 view);
471
472 // If we start a touch icon load and then load a new page, we don't
473 // want to cancel the current touch icon loader. But, we do want to
474 // create a new one when the touch icon url is known.
475 if (mTouchIconLoader != null) {
476 mTouchIconLoader.mTab = null;
477 mTouchIconLoader = null;
478 }
479
480 // reset the error console
481 if (mErrorConsole != null) {
482 mErrorConsole.clearErrorMessages();
483 if (mActivity.shouldShowErrorConsole()) {
484 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
485 }
486 }
487
488 // update the bookmark database for favicon
489 if (favicon != null) {
490 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
Patrick Scottcc949122010-03-17 16:06:30 -0400491 .getContentResolver(), null, url, favicon);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700492 }
493
494 // reset sync timer to avoid sync starts during loading a page
495 CookieSyncManager.getInstance().resetSync();
496
497 if (!mActivity.isNetworkUp()) {
498 view.setNetworkAvailable(false);
499 }
500
501 // finally update the UI in the activity if it is in the foreground
502 if (mInForeground) {
503 mActivity.onPageStarted(view, url, favicon);
504 }
505 }
506
507 @Override
508 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000509 LogTag.logPageFinishedLoading(
510 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700511 mInLoad = false;
512
513 if (mInForeground && !mActivity.didUserStopLoading()
514 || !mInForeground) {
515 // Only update the bookmark screenshot if the user did not
516 // cancel the load early.
517 mActivity.postMessage(
518 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
519 500);
520 }
521
522 // finally update the UI in the activity if it is in the foreground
523 if (mInForeground) {
524 mActivity.onPageFinished(view, url);
525 }
526 }
527
528 // return true if want to hijack the url to let another app to handle it
529 @Override
530 public boolean shouldOverrideUrlLoading(WebView view, String url) {
Leon Scroggins IIIc1f5ae22010-06-29 17:11:29 -0400531 if (voiceSearchSourceIsGoogle()) {
532 // This method is called when the user clicks on a link.
533 // VoiceSearchMode is turned off when the user leaves the
534 // Google results page, so at this point the user must be on
535 // that page. If the user clicked a link on that page, assume
536 // that the voice search was effective, and broadcast an Intent
537 // so a receiver can take note of that fact.
538 Intent logIntent = new Intent(LoggingEvents.ACTION_LOG_EVENT);
539 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
540 LoggingEvents.VoiceSearch.RESULT_CLICKED);
541 mActivity.sendBroadcast(logIntent);
542 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700543 if (mInForeground) {
544 return mActivity.shouldOverrideUrlLoading(view, url);
545 } else {
546 return false;
547 }
548 }
549
550 /**
551 * Updates the lock icon. This method is called when we discover another
552 * resource to be loaded for this page (for example, javascript). While
553 * we update the icon type, we do not update the lock icon itself until
554 * we are done loading, it is slightly more secure this way.
555 */
556 @Override
557 public void onLoadResource(WebView view, String url) {
558 if (url != null && url.length() > 0) {
559 // It is only if the page claims to be secure that we may have
560 // to update the lock:
561 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
562 // If NOT a 'safe' url, change the lock to mixed content!
563 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
564 || URLUtil.isAboutUrl(url))) {
565 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
566 }
567 }
568 }
569 }
570
571 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700572 * Show a dialog informing the user of the network error reported by
573 * WebCore if it is in the foreground.
574 */
575 @Override
576 public void onReceivedError(WebView view, int errorCode,
577 String description, String failingUrl) {
578 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
579 errorCode != WebViewClient.ERROR_CONNECT &&
580 errorCode != WebViewClient.ERROR_BAD_URL &&
581 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
582 errorCode != WebViewClient.ERROR_FILE) {
583 queueError(errorCode, description);
584 }
585 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
586 + " " + description);
587
588 // We need to reset the title after an error if it is in foreground.
589 if (mInForeground) {
590 mActivity.resetTitleAndRevertLockIcon();
591 }
592 }
593
594 /**
595 * Check with the user if it is ok to resend POST data as the page they
596 * are trying to navigate to is the result of a POST.
597 */
598 @Override
599 public void onFormResubmission(WebView view, final Message dontResend,
600 final Message resend) {
601 if (!mInForeground) {
602 dontResend.sendToTarget();
603 return;
604 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500605 if (mDontResend != null) {
606 Log.w(LOGTAG, "onFormResubmission should not be called again "
607 + "while dialog is still up");
608 dontResend.sendToTarget();
609 return;
610 }
611 mDontResend = dontResend;
612 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700613 new AlertDialog.Builder(mActivity).setTitle(
614 R.string.browserFrameFormResubmitLabel).setMessage(
615 R.string.browserFrameFormResubmitMessage)
616 .setPositiveButton(R.string.ok,
617 new DialogInterface.OnClickListener() {
618 public void onClick(DialogInterface dialog,
619 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500620 if (mResend != null) {
621 mResend.sendToTarget();
622 mResend = null;
623 mDontResend = null;
624 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700625 }
626 }).setNegativeButton(R.string.cancel,
627 new DialogInterface.OnClickListener() {
628 public void onClick(DialogInterface dialog,
629 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500630 if (mDontResend != null) {
631 mDontResend.sendToTarget();
632 mResend = null;
633 mDontResend = null;
634 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700635 }
636 }).setOnCancelListener(new OnCancelListener() {
637 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500638 if (mDontResend != null) {
639 mDontResend.sendToTarget();
640 mResend = null;
641 mDontResend = null;
642 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700643 }
644 }).show();
645 }
646
647 /**
648 * Insert the url into the visited history database.
649 * @param url The url to be inserted.
650 * @param isReload True if this url is being reloaded.
651 * FIXME: Not sure what to do when reloading the page.
652 */
653 @Override
654 public void doUpdateVisitedHistory(WebView view, String url,
655 boolean isReload) {
656 if (url.regionMatches(true, 0, "about:", 0, 6)) {
657 return;
658 }
659 // remove "client" before updating it to the history so that it wont
660 // show up in the auto-complete list.
661 int index = url.indexOf("client=ms-");
662 if (index > 0 && url.contains(".google.")) {
663 int end = url.indexOf('&', index);
664 if (end > 0) {
665 url = url.substring(0, index)
666 .concat(url.substring(end + 1));
667 } else {
668 // the url.charAt(index-1) should be either '?' or '&'
669 url = url.substring(0, index-1);
670 }
671 }
Leon Scroggins8d06e362010-03-24 14:45:57 -0400672 final ContentResolver cr = mActivity.getContentResolver();
673 final String newUrl = url;
674 new AsyncTask<Void, Void, Void>() {
675 protected Void doInBackground(Void... unused) {
676 Browser.updateVisitedHistory(cr, newUrl, true);
677 return null;
678 }
679 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700680 WebIconDatabase.getInstance().retainIconForPageUrl(url);
681 }
682
683 /**
684 * Displays SSL error(s) dialog to the user.
685 */
686 @Override
687 public void onReceivedSslError(final WebView view,
688 final SslErrorHandler handler, final SslError error) {
689 if (!mInForeground) {
690 handler.cancel();
691 return;
692 }
693 if (BrowserSettings.getInstance().showSecurityWarnings()) {
694 final LayoutInflater factory =
695 LayoutInflater.from(mActivity);
696 final View warningsView =
697 factory.inflate(R.layout.ssl_warnings, null);
698 final LinearLayout placeholder =
699 (LinearLayout)warningsView.findViewById(R.id.placeholder);
700
701 if (error.hasError(SslError.SSL_UNTRUSTED)) {
702 LinearLayout ll = (LinearLayout)factory
703 .inflate(R.layout.ssl_warning, null);
704 ((TextView)ll.findViewById(R.id.warning))
705 .setText(R.string.ssl_untrusted);
706 placeholder.addView(ll);
707 }
708
709 if (error.hasError(SslError.SSL_IDMISMATCH)) {
710 LinearLayout ll = (LinearLayout)factory
711 .inflate(R.layout.ssl_warning, null);
712 ((TextView)ll.findViewById(R.id.warning))
713 .setText(R.string.ssl_mismatch);
714 placeholder.addView(ll);
715 }
716
717 if (error.hasError(SslError.SSL_EXPIRED)) {
718 LinearLayout ll = (LinearLayout)factory
719 .inflate(R.layout.ssl_warning, null);
720 ((TextView)ll.findViewById(R.id.warning))
721 .setText(R.string.ssl_expired);
722 placeholder.addView(ll);
723 }
724
725 if (error.hasError(SslError.SSL_NOTYETVALID)) {
726 LinearLayout ll = (LinearLayout)factory
727 .inflate(R.layout.ssl_warning, null);
728 ((TextView)ll.findViewById(R.id.warning))
729 .setText(R.string.ssl_not_yet_valid);
730 placeholder.addView(ll);
731 }
732
733 new AlertDialog.Builder(mActivity).setTitle(
734 R.string.security_warning).setIcon(
735 android.R.drawable.ic_dialog_alert).setView(
736 warningsView).setPositiveButton(R.string.ssl_continue,
737 new DialogInterface.OnClickListener() {
738 public void onClick(DialogInterface dialog,
739 int whichButton) {
740 handler.proceed();
741 }
742 }).setNeutralButton(R.string.view_certificate,
743 new DialogInterface.OnClickListener() {
744 public void onClick(DialogInterface dialog,
745 int whichButton) {
746 mActivity.showSSLCertificateOnError(view,
747 handler, error);
748 }
749 }).setNegativeButton(R.string.cancel,
750 new DialogInterface.OnClickListener() {
751 public void onClick(DialogInterface dialog,
752 int whichButton) {
753 handler.cancel();
754 mActivity.resetTitleAndRevertLockIcon();
755 }
756 }).setOnCancelListener(
757 new DialogInterface.OnCancelListener() {
758 public void onCancel(DialogInterface dialog) {
759 handler.cancel();
760 mActivity.resetTitleAndRevertLockIcon();
761 }
762 }).show();
763 } else {
764 handler.proceed();
765 }
766 }
767
768 /**
769 * Handles an HTTP authentication request.
770 *
771 * @param handler The authentication handler
772 * @param host The host
773 * @param realm The realm
774 */
775 @Override
776 public void onReceivedHttpAuthRequest(WebView view,
777 final HttpAuthHandler handler, final String host,
778 final String realm) {
779 String username = null;
780 String password = null;
781
782 boolean reuseHttpAuthUsernamePassword = handler
783 .useHttpAuthUsernamePassword();
784
Steve Block95a53b22010-03-25 17:24:58 +0000785 if (reuseHttpAuthUsernamePassword && view != null) {
786 String[] credentials = view.getHttpAuthUsernamePassword(
Grace Kloba22ac16e2009-10-07 18:00:23 -0700787 host, realm);
788 if (credentials != null && credentials.length == 2) {
789 username = credentials[0];
790 password = credentials[1];
791 }
792 }
793
794 if (username != null && password != null) {
795 handler.proceed(username, password);
796 } else {
797 if (mInForeground) {
798 mActivity.showHttpAuthentication(handler, host, realm,
799 null, null, null, 0);
800 } else {
801 handler.cancel();
802 }
803 }
804 }
805
806 @Override
807 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
808 if (!mInForeground) {
809 return false;
810 }
811 if (mActivity.isMenuDown()) {
812 // only check shortcut key when MENU is held
813 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
814 event);
815 } else {
816 return false;
817 }
818 }
819
820 @Override
821 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
Cary Clark1f10cbf2010-03-22 11:45:23 -0400822 if (!mInForeground || mActivity.mActivityInPause) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700823 return;
824 }
825 if (event.isDown()) {
826 mActivity.onKeyDown(event.getKeyCode(), event);
827 } else {
828 mActivity.onKeyUp(event.getKeyCode(), event);
829 }
830 }
831 };
832
833 // -------------------------------------------------------------------------
834 // WebChromeClient implementation for the main WebView
835 // -------------------------------------------------------------------------
836
837 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
838 // Helper method to create a new tab or sub window.
839 private void createWindow(final boolean dialog, final Message msg) {
840 WebView.WebViewTransport transport =
841 (WebView.WebViewTransport) msg.obj;
842 if (dialog) {
843 createSubWindow();
844 mActivity.attachSubWindow(Tab.this);
845 transport.setWebView(mSubView);
846 } else {
847 final Tab newTab = mActivity.openTabAndShow(
848 BrowserActivity.EMPTY_URL_DATA, false, null);
849 if (newTab != Tab.this) {
850 Tab.this.addChildTab(newTab);
851 }
852 transport.setWebView(newTab.getWebView());
853 }
854 msg.sendToTarget();
855 }
856
857 @Override
858 public boolean onCreateWindow(WebView view, final boolean dialog,
859 final boolean userGesture, final Message resultMsg) {
860 // only allow new window or sub window for the foreground case
861 if (!mInForeground) {
862 return false;
863 }
864 // Short-circuit if we can't create any more tabs or sub windows.
865 if (dialog && mSubView != null) {
866 new AlertDialog.Builder(mActivity)
867 .setTitle(R.string.too_many_subwindows_dialog_title)
868 .setIcon(android.R.drawable.ic_dialog_alert)
869 .setMessage(R.string.too_many_subwindows_dialog_message)
870 .setPositiveButton(R.string.ok, null)
871 .show();
872 return false;
873 } else if (!mActivity.getTabControl().canCreateNewTab()) {
874 new AlertDialog.Builder(mActivity)
875 .setTitle(R.string.too_many_windows_dialog_title)
876 .setIcon(android.R.drawable.ic_dialog_alert)
877 .setMessage(R.string.too_many_windows_dialog_message)
878 .setPositiveButton(R.string.ok, null)
879 .show();
880 return false;
881 }
882
883 // Short-circuit if this was a user gesture.
884 if (userGesture) {
885 createWindow(dialog, resultMsg);
886 return true;
887 }
888
889 // Allow the popup and create the appropriate window.
890 final AlertDialog.OnClickListener allowListener =
891 new AlertDialog.OnClickListener() {
892 public void onClick(DialogInterface d,
893 int which) {
894 createWindow(dialog, resultMsg);
895 }
896 };
897
898 // Block the popup by returning a null WebView.
899 final AlertDialog.OnClickListener blockListener =
900 new AlertDialog.OnClickListener() {
901 public void onClick(DialogInterface d, int which) {
902 resultMsg.sendToTarget();
903 }
904 };
905
906 // Build a confirmation dialog to display to the user.
907 final AlertDialog d =
908 new AlertDialog.Builder(mActivity)
909 .setTitle(R.string.attention)
910 .setIcon(android.R.drawable.ic_dialog_alert)
911 .setMessage(R.string.popup_window_attempt)
912 .setPositiveButton(R.string.allow, allowListener)
913 .setNegativeButton(R.string.block, blockListener)
914 .setCancelable(false)
915 .create();
916
917 // Show the confirmation dialog.
918 d.show();
919 return true;
920 }
921
922 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500923 public void onRequestFocus(WebView view) {
924 if (!mInForeground) {
925 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
926 Tab.this));
927 }
928 }
929
930 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700931 public void onCloseWindow(WebView window) {
932 if (mParentTab != null) {
933 // JavaScript can only close popup window.
934 if (mInForeground) {
935 mActivity.switchToTab(mActivity.getTabControl()
936 .getTabIndex(mParentTab));
937 }
938 mActivity.closeTab(Tab.this);
939 }
940 }
941
942 @Override
943 public void onProgressChanged(WebView view, int newProgress) {
944 if (newProgress == 100) {
945 // sync cookies and cache promptly here.
946 CookieSyncManager.getInstance().sync();
947 }
948 if (mInForeground) {
949 mActivity.onProgressChanged(view, newProgress);
950 }
951 }
952
953 @Override
Leon Scroggins21d9b902010-03-11 09:33:11 -0500954 public void onReceivedTitle(WebView view, final String title) {
955 final String pageUrl = view.getUrl();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700956 if (mInForeground) {
957 // here, if url is null, we want to reset the title
Leon Scroggins21d9b902010-03-11 09:33:11 -0500958 mActivity.setUrlTitle(pageUrl, title);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700959 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500960 if (pageUrl == null || pageUrl.length()
961 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 return;
963 }
Leon Scroggins21d9b902010-03-11 09:33:11 -0500964 new AsyncTask<Void, Void, Void>() {
965 protected Void doInBackground(Void... unused) {
966 // See if we can find the current url in our history
967 // database and add the new title to it.
968 String url = pageUrl;
969 if (url.startsWith("http://www.")) {
970 url = url.substring(11);
971 } else if (url.startsWith("http://")) {
972 url = url.substring(4);
973 }
The Android Open Source Project55e849a2010-05-12 11:06:32 -0700974 // Escape wildcards for LIKE operator.
975 url = url.replace("\\", "\\\\").replace("%", "\\%")
976 .replace("_", "\\_");
Leon Scroggins21d9b902010-03-11 09:33:11 -0500977 Cursor c = null;
978 try {
979 final ContentResolver cr
980 = mActivity.getContentResolver();
981 url = "%" + url;
982 String [] selArgs = new String[] { url };
983 String where = Browser.BookmarkColumns.URL
The Android Open Source Project55e849a2010-05-12 11:06:32 -0700984 + " LIKE ? ESCAPE '\\' AND "
Leon Scroggins21d9b902010-03-11 09:33:11 -0500985 + Browser.BookmarkColumns.BOOKMARK + " = 0";
986 c = cr.query(Browser.BOOKMARKS_URI, new String[]
987 { Browser.BookmarkColumns._ID }, where, selArgs,
988 null);
989 if (c.moveToFirst()) {
990 // Current implementation of database only has one
991 // entry per url.
992 ContentValues map = new ContentValues();
993 map.put(Browser.BookmarkColumns.TITLE, title);
994 String[] projection = new String[]
995 { Integer.valueOf(c.getInt(0)).toString() };
996 cr.update(Browser.BOOKMARKS_URI, map, "_id = ?",
997 projection);
998 }
999 } catch (IllegalStateException e) {
1000 Log.e(LOGTAG, "Tab onReceived title", e);
1001 } catch (SQLiteException ex) {
1002 Log.e(LOGTAG,
1003 "onReceivedTitle() caught SQLiteException: ",
1004 ex);
1005 } finally {
1006 if (c != null) c.close();
1007 }
1008 return null;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001009 }
Leon Scroggins21d9b902010-03-11 09:33:11 -05001010 }.execute();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001011 }
1012
1013 @Override
1014 public void onReceivedIcon(WebView view, Bitmap icon) {
1015 if (icon != null) {
1016 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
1017 .getContentResolver(), view.getOriginalUrl(), view
1018 .getUrl(), icon);
1019 }
1020 if (mInForeground) {
1021 mActivity.setFavicon(icon);
1022 }
1023 }
1024
1025 @Override
1026 public void onReceivedTouchIconUrl(WebView view, String url,
1027 boolean precomposed) {
1028 final ContentResolver cr = mActivity.getContentResolver();
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001029 // Let precomposed icons take precedence over non-composed
1030 // icons.
1031 if (precomposed && mTouchIconLoader != null) {
1032 mTouchIconLoader.cancel(false);
1033 mTouchIconLoader = null;
1034 }
1035 // Have only one async task at a time.
1036 if (mTouchIconLoader == null) {
Andreas Sandbladd159ec52010-06-16 13:10:39 +02001037 mTouchIconLoader = new DownloadTouchIcon(Tab.this, mActivity, cr, view);
Leon Scrogginsc8393d92010-04-23 14:58:16 -04001038 mTouchIconLoader.execute(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 }
1040 }
1041
1042 @Override
Leon Clarke30e0ef42010-07-16 15:31:04 +01001043 public void onSelectionDone(WebView view) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001044 if (mInForeground) mActivity.closeDialogs();
1045 }
1046
1047 @Override
Leon Clarke30e0ef42010-07-16 15:31:04 +01001048 public void onSelectionStart(WebView view) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001049 if (mInForeground) mActivity.showSelectDialog();
1050 }
1051
1052 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -07001053 public void onShowCustomView(View view,
1054 WebChromeClient.CustomViewCallback callback) {
1055 if (mInForeground) mActivity.onShowCustomView(view, callback);
1056 }
1057
1058 @Override
1059 public void onHideCustomView() {
1060 if (mInForeground) mActivity.onHideCustomView();
1061 }
1062
1063 /**
1064 * The origin has exceeded its database quota.
1065 * @param url the URL that exceeded the quota
1066 * @param databaseIdentifier the identifier of the database on which the
1067 * transaction that caused the quota overflow was run
1068 * @param currentQuota the current quota for the origin.
1069 * @param estimatedSize the estimated size of the database.
1070 * @param totalUsedQuota is the sum of all origins' quota.
1071 * @param quotaUpdater The callback to run when a decision to allow or
1072 * deny quota has been made. Don't forget to call this!
1073 */
1074 @Override
1075 public void onExceededDatabaseQuota(String url,
1076 String databaseIdentifier, long currentQuota, long estimatedSize,
1077 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1078 BrowserSettings.getInstance().getWebStorageSizeManager()
1079 .onExceededDatabaseQuota(url, databaseIdentifier,
1080 currentQuota, estimatedSize, totalUsedQuota,
1081 quotaUpdater);
1082 }
1083
1084 /**
1085 * The Application Cache has exceeded its max size.
1086 * @param spaceNeeded is the amount of disk space that would be needed
1087 * in order for the last appcache operation to succeed.
1088 * @param totalUsedQuota is the sum of all origins' quota.
1089 * @param quotaUpdater A callback to inform the WebCore thread that a
1090 * new app cache size is available. This callback must always
1091 * be executed at some point to ensure that the sleeping
1092 * WebCore thread is woken up.
1093 */
1094 @Override
1095 public void onReachedMaxAppCacheSize(long spaceNeeded,
1096 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1097 BrowserSettings.getInstance().getWebStorageSizeManager()
1098 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1099 quotaUpdater);
1100 }
1101
1102 /**
1103 * Instructs the browser to show a prompt to ask the user to set the
1104 * Geolocation permission state for the specified origin.
1105 * @param origin The origin for which Geolocation permissions are
1106 * requested.
1107 * @param callback The callback to call once the user has set the
1108 * Geolocation permission state.
1109 */
1110 @Override
1111 public void onGeolocationPermissionsShowPrompt(String origin,
1112 GeolocationPermissions.Callback callback) {
1113 if (mInForeground) {
Grace Kloba50c241e2010-04-20 11:07:50 -07001114 getGeolocationPermissionsPrompt().show(origin, callback);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001115 }
1116 }
1117
1118 /**
1119 * Instructs the browser to hide the Geolocation permissions prompt.
1120 */
1121 @Override
1122 public void onGeolocationPermissionsHidePrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001123 if (mInForeground && mGeolocationPermissionsPrompt != null) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001124 mGeolocationPermissionsPrompt.hide();
1125 }
1126 }
1127
Ben Murdoch65acc352009-11-19 18:16:04 +00001128 /* Adds a JavaScript error message to the system log and if the JS
1129 * console is enabled in the about:debug options, to that console
1130 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001131 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001132 */
1133 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001134 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001135 if (mInForeground) {
1136 // call getErrorConsole(true) so it will create one if needed
1137 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001138 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001139 if (mActivity.shouldShowErrorConsole()
1140 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1141 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1142 }
1143 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001144
1145 String message = "Console: " + consoleMessage.message() + " "
1146 + consoleMessage.sourceId() + ":"
1147 + consoleMessage.lineNumber();
1148
1149 switch (consoleMessage.messageLevel()) {
1150 case TIP:
1151 Log.v(CONSOLE_LOGTAG, message);
1152 break;
1153 case LOG:
1154 Log.i(CONSOLE_LOGTAG, message);
1155 break;
1156 case WARNING:
1157 Log.w(CONSOLE_LOGTAG, message);
1158 break;
1159 case ERROR:
1160 Log.e(CONSOLE_LOGTAG, message);
1161 break;
1162 case DEBUG:
1163 Log.d(CONSOLE_LOGTAG, message);
1164 break;
1165 }
1166
1167 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001168 }
1169
1170 /**
1171 * Ask the browser for an icon to represent a <video> element.
1172 * This icon will be used if the Web page did not specify a poster attribute.
1173 * @return Bitmap The icon or null if no such icon is available.
1174 */
1175 @Override
1176 public Bitmap getDefaultVideoPoster() {
1177 if (mInForeground) {
1178 return mActivity.getDefaultVideoPoster();
1179 }
1180 return null;
1181 }
1182
1183 /**
1184 * Ask the host application for a custom progress view to show while
1185 * a <video> is loading.
1186 * @return View The progress view.
1187 */
1188 @Override
1189 public View getVideoLoadingProgressView() {
1190 if (mInForeground) {
1191 return mActivity.getVideoLoadingProgressView();
1192 }
1193 return null;
1194 }
1195
1196 @Override
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001197 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001198 if (mInForeground) {
Ben Murdoch62b1b7e2010-05-19 20:38:56 +01001199 mActivity.openFileChooser(uploadMsg, acceptType);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001200 } else {
1201 uploadMsg.onReceiveValue(null);
1202 }
1203 }
1204
1205 /**
1206 * Deliver a list of already-visited URLs
1207 */
1208 @Override
1209 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1210 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
1211 public String[] doInBackground(Void... unused) {
1212 return Browser.getVisitedHistory(mActivity
1213 .getContentResolver());
1214 }
1215 public void onPostExecute(String[] result) {
1216 callback.onReceiveValue(result);
1217 };
1218 };
1219 task.execute();
1220 };
1221 };
1222
1223 // -------------------------------------------------------------------------
1224 // WebViewClient implementation for the sub window
1225 // -------------------------------------------------------------------------
1226
1227 // Subclass of WebViewClient used in subwindows to notify the main
1228 // WebViewClient of certain WebView activities.
1229 private static class SubWindowClient extends WebViewClient {
1230 // The main WebViewClient.
1231 private final WebViewClient mClient;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001232 private final BrowserActivity mBrowserActivity;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001233
Leon Scroggins III211ba542010-04-19 13:21:13 -04001234 SubWindowClient(WebViewClient client, BrowserActivity activity) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001235 mClient = client;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001236 mBrowserActivity = activity;
1237 }
1238 @Override
1239 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1240 // Unlike the others, do not call mClient's version, which would
1241 // change the progress bar. However, we do want to remove the
Cary Clark01cfcdd2010-06-04 16:36:45 -04001242 // find or select dialog.
1243 mBrowserActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001244 }
1245 @Override
1246 public void doUpdateVisitedHistory(WebView view, String url,
1247 boolean isReload) {
1248 mClient.doUpdateVisitedHistory(view, url, isReload);
1249 }
1250 @Override
1251 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1252 return mClient.shouldOverrideUrlLoading(view, url);
1253 }
1254 @Override
1255 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1256 SslError error) {
1257 mClient.onReceivedSslError(view, handler, error);
1258 }
1259 @Override
1260 public void onReceivedHttpAuthRequest(WebView view,
1261 HttpAuthHandler handler, String host, String realm) {
1262 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1263 }
1264 @Override
1265 public void onFormResubmission(WebView view, Message dontResend,
1266 Message resend) {
1267 mClient.onFormResubmission(view, dontResend, resend);
1268 }
1269 @Override
1270 public void onReceivedError(WebView view, int errorCode,
1271 String description, String failingUrl) {
1272 mClient.onReceivedError(view, errorCode, description, failingUrl);
1273 }
1274 @Override
1275 public boolean shouldOverrideKeyEvent(WebView view,
1276 android.view.KeyEvent event) {
1277 return mClient.shouldOverrideKeyEvent(view, event);
1278 }
1279 @Override
1280 public void onUnhandledKeyEvent(WebView view,
1281 android.view.KeyEvent event) {
1282 mClient.onUnhandledKeyEvent(view, event);
1283 }
1284 }
1285
1286 // -------------------------------------------------------------------------
1287 // WebChromeClient implementation for the sub window
1288 // -------------------------------------------------------------------------
1289
1290 private class SubWindowChromeClient extends WebChromeClient {
1291 // The main WebChromeClient.
1292 private final WebChromeClient mClient;
1293
1294 SubWindowChromeClient(WebChromeClient client) {
1295 mClient = client;
1296 }
1297 @Override
1298 public void onProgressChanged(WebView view, int newProgress) {
1299 mClient.onProgressChanged(view, newProgress);
1300 }
1301 @Override
1302 public boolean onCreateWindow(WebView view, boolean dialog,
1303 boolean userGesture, android.os.Message resultMsg) {
1304 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1305 }
1306 @Override
1307 public void onCloseWindow(WebView window) {
1308 if (window != mSubView) {
1309 Log.e(LOGTAG, "Can't close the window");
1310 }
1311 mActivity.dismissSubWindow(Tab.this);
1312 }
1313 }
1314
1315 // -------------------------------------------------------------------------
1316
1317 // Construct a new tab
1318 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1319 String url) {
1320 mActivity = activity;
1321 mCloseOnExit = closeOnExit;
1322 mAppId = appId;
1323 mOriginalUrl = url;
1324 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1325 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1326 mInLoad = false;
1327 mInForeground = false;
1328
1329 mInflateService = LayoutInflater.from(activity);
1330
1331 // The tab consists of a container view, which contains the main
1332 // WebView, as well as any other UI elements associated with the tab.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001333 mContainer = (LinearLayout) mInflateService.inflate(R.layout.tab, null);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001334
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001335 mDownloadListener = new DownloadListener() {
1336 public void onDownloadStart(String url, String userAgent,
1337 String contentDisposition, String mimetype,
1338 long contentLength) {
1339 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1340 mimetype, contentLength);
1341 if (mMainView.copyBackForwardList().getSize() == 0) {
1342 // This Tab was opened for the sole purpose of downloading a
1343 // file. Remove it.
1344 if (mActivity.getTabControl().getCurrentWebView()
1345 == mMainView) {
1346 // In this case, the Tab is still on top.
1347 mActivity.goBackOnePageOrQuit();
1348 } else {
1349 // In this case, it is not.
1350 mActivity.closeTab(Tab.this);
1351 }
1352 }
1353 }
1354 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001355 mWebBackForwardListClient = new WebBackForwardListClient() {
1356 @Override
1357 public void onNewHistoryItem(WebHistoryItem item) {
1358 if (isInVoiceSearchMode()) {
1359 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1360 }
1361 }
1362 @Override
1363 public void onIndexChanged(WebHistoryItem item, int index) {
1364 Object data = item.getCustomData();
1365 if (data != null && data instanceof Intent) {
1366 activateVoiceSearchMode((Intent) data);
1367 }
1368 }
1369 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001370
Grace Kloba22ac16e2009-10-07 18:00:23 -07001371 setWebView(w);
1372 }
1373
1374 /**
1375 * Sets the WebView for this tab, correctly removing the old WebView from
1376 * the container view.
1377 */
1378 void setWebView(WebView w) {
1379 if (mMainView == w) {
1380 return;
1381 }
1382 // If the WebView is changing, the page will be reloaded, so any ongoing
1383 // Geolocation permission requests are void.
Grace Kloba50c241e2010-04-20 11:07:50 -07001384 if (mGeolocationPermissionsPrompt != null) {
1385 mGeolocationPermissionsPrompt.hide();
1386 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001387
1388 // Just remove the old one.
1389 FrameLayout wrapper =
1390 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1391 wrapper.removeView(mMainView);
1392
1393 // set the new one
1394 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001395 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001396 if (mMainView != null) {
1397 mMainView.setWebViewClient(mWebViewClient);
1398 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001399 // Attach DownloadManager so that downloads can start in an active
1400 // or a non-active window. This can happen when going to a site that
1401 // does a redirect after a period of time. The user could have
1402 // switched to another tab while waiting for the download to start.
1403 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001404 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001405 }
1406 }
1407
1408 /**
1409 * Destroy the tab's main WebView and subWindow if any
1410 */
1411 void destroy() {
1412 if (mMainView != null) {
1413 dismissSubWindow();
1414 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1415 // save the WebView to call destroy() after detach it from the tab
1416 WebView webView = mMainView;
1417 setWebView(null);
1418 webView.destroy();
1419 }
1420 }
1421
1422 /**
1423 * Remove the tab from the parent
1424 */
1425 void removeFromTree() {
1426 // detach the children
1427 if (mChildTabs != null) {
1428 for(Tab t : mChildTabs) {
1429 t.setParentTab(null);
1430 }
1431 }
1432 // remove itself from the parent list
1433 if (mParentTab != null) {
1434 mParentTab.mChildTabs.remove(this);
1435 }
1436 }
1437
1438 /**
1439 * Create a new subwindow unless a subwindow already exists.
1440 * @return True if a new subwindow was created. False if one already exists.
1441 */
1442 boolean createSubWindow() {
1443 if (mSubView == null) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001444 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001445 mSubViewContainer = mInflateService.inflate(
1446 R.layout.browser_subwindow, null);
1447 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
Grace Kloba80380ed2010-03-19 17:44:21 -07001448 mSubView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001449 // use trackball directly
1450 mSubView.setMapTrackballToArrowKeys(false);
Grace Kloba140b33a2010-03-19 18:40:09 -07001451 // Enable the built-in zoom
1452 mSubView.getSettings().setBuiltInZoomControls(true);
Leon Scroggins III211ba542010-04-19 13:21:13 -04001453 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient,
1454 mActivity));
Grace Kloba22ac16e2009-10-07 18:00:23 -07001455 mSubView.setWebChromeClient(new SubWindowChromeClient(
1456 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001457 // Set a different DownloadListener for the mSubView, since it will
1458 // just need to dismiss the mSubView, rather than close the Tab
1459 mSubView.setDownloadListener(new DownloadListener() {
1460 public void onDownloadStart(String url, String userAgent,
1461 String contentDisposition, String mimetype,
1462 long contentLength) {
1463 mActivity.onDownloadStart(url, userAgent,
1464 contentDisposition, mimetype, contentLength);
1465 if (mSubView.copyBackForwardList().getSize() == 0) {
1466 // This subwindow was opened for the sole purpose of
1467 // downloading a file. Remove it.
Leon Scroggins98b938b2010-06-25 14:49:24 -04001468 mActivity.dismissSubWindow(Tab.this);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001469 }
1470 }
1471 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001472 mSubView.setOnCreateContextMenuListener(mActivity);
1473 final BrowserSettings s = BrowserSettings.getInstance();
1474 s.addObserver(mSubView.getSettings()).update(s, null);
1475 final ImageButton cancel = (ImageButton) mSubViewContainer
1476 .findViewById(R.id.subwindow_close);
1477 cancel.setOnClickListener(new OnClickListener() {
1478 public void onClick(View v) {
1479 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1480 }
1481 });
1482 return true;
1483 }
1484 return false;
1485 }
1486
1487 /**
1488 * Dismiss the subWindow for the tab.
1489 */
1490 void dismissSubWindow() {
1491 if (mSubView != null) {
Cary Clark01cfcdd2010-06-04 16:36:45 -04001492 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001493 BrowserSettings.getInstance().deleteObserver(
1494 mSubView.getSettings());
1495 mSubView.destroy();
1496 mSubView = null;
1497 mSubViewContainer = null;
1498 }
1499 }
1500
1501 /**
1502 * Attach the sub window to the content view.
1503 */
1504 void attachSubWindow(ViewGroup content) {
1505 if (mSubView != null) {
1506 content.addView(mSubViewContainer,
1507 BrowserActivity.COVER_SCREEN_PARAMS);
1508 }
1509 }
1510
1511 /**
1512 * Remove the sub window from the content view.
1513 */
1514 void removeSubWindow(ViewGroup content) {
1515 if (mSubView != null) {
1516 content.removeView(mSubViewContainer);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001517 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001518 }
1519 }
1520
1521 /**
1522 * This method attaches both the WebView and any sub window to the
1523 * given content view.
1524 */
1525 void attachTabToContentView(ViewGroup content) {
1526 if (mMainView == null) {
1527 return;
1528 }
1529
1530 // Attach the WebView to the container and then attach the
1531 // container to the content view.
1532 FrameLayout wrapper =
1533 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
Leon Scroggins IIIb00cf362010-03-30 11:24:14 -04001534 ViewGroup parent = (ViewGroup) mMainView.getParent();
1535 if (parent != wrapper) {
1536 if (parent != null) {
1537 Log.w(LOGTAG, "mMainView already has a parent in"
1538 + " attachTabToContentView!");
1539 parent.removeView(mMainView);
1540 }
1541 wrapper.addView(mMainView);
1542 } else {
1543 Log.w(LOGTAG, "mMainView is already attached to wrapper in"
1544 + " attachTabToContentView!");
1545 }
1546 parent = (ViewGroup) mContainer.getParent();
1547 if (parent != content) {
1548 if (parent != null) {
1549 Log.w(LOGTAG, "mContainer already has a parent in"
1550 + " attachTabToContentView!");
1551 parent.removeView(mContainer);
1552 }
1553 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1554 } else {
1555 Log.w(LOGTAG, "mContainer is already attached to content in"
1556 + " attachTabToContentView!");
1557 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001558 attachSubWindow(content);
1559 }
1560
1561 /**
1562 * Remove the WebView and any sub window from the given content view.
1563 */
1564 void removeTabFromContentView(ViewGroup content) {
1565 if (mMainView == null) {
1566 return;
1567 }
1568
1569 // Remove the container from the content and then remove the
1570 // WebView from the container. This will trigger a focus change
1571 // needed by WebView.
1572 FrameLayout wrapper =
1573 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1574 wrapper.removeView(mMainView);
1575 content.removeView(mContainer);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001576 mActivity.closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001577 removeSubWindow(content);
1578 }
1579
1580 /**
1581 * Set the parent tab of this tab.
1582 */
1583 void setParentTab(Tab parent) {
1584 mParentTab = parent;
1585 // This tab may have been freed due to low memory. If that is the case,
1586 // the parent tab index is already saved. If we are changing that index
1587 // (most likely due to removing the parent tab) we must update the
1588 // parent tab index in the saved Bundle.
1589 if (mSavedState != null) {
1590 if (parent == null) {
1591 mSavedState.remove(PARENTTAB);
1592 } else {
1593 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1594 .getTabIndex(parent));
1595 }
1596 }
1597 }
1598
1599 /**
1600 * When a Tab is created through the content of another Tab, then we
1601 * associate the Tabs.
1602 * @param child the Tab that was created from this Tab
1603 */
1604 void addChildTab(Tab child) {
1605 if (mChildTabs == null) {
1606 mChildTabs = new Vector<Tab>();
1607 }
1608 mChildTabs.add(child);
1609 child.setParentTab(this);
1610 }
1611
1612 Vector<Tab> getChildTabs() {
1613 return mChildTabs;
1614 }
1615
1616 void resume() {
1617 if (mMainView != null) {
1618 mMainView.onResume();
1619 if (mSubView != null) {
1620 mSubView.onResume();
1621 }
1622 }
1623 }
1624
1625 void pause() {
1626 if (mMainView != null) {
1627 mMainView.onPause();
1628 if (mSubView != null) {
1629 mSubView.onPause();
1630 }
1631 }
1632 }
1633
1634 void putInForeground() {
1635 mInForeground = true;
1636 resume();
1637 mMainView.setOnCreateContextMenuListener(mActivity);
1638 if (mSubView != null) {
1639 mSubView.setOnCreateContextMenuListener(mActivity);
1640 }
1641 // Show the pending error dialog if the queue is not empty
1642 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1643 showError(mQueuedErrors.getFirst());
1644 }
1645 }
1646
1647 void putInBackground() {
1648 mInForeground = false;
1649 pause();
1650 mMainView.setOnCreateContextMenuListener(null);
1651 if (mSubView != null) {
1652 mSubView.setOnCreateContextMenuListener(null);
1653 }
1654 }
1655
1656 /**
1657 * Return the top window of this tab; either the subwindow if it is not
1658 * null or the main window.
1659 * @return The top window of this tab.
1660 */
1661 WebView getTopWindow() {
1662 if (mSubView != null) {
1663 return mSubView;
1664 }
1665 return mMainView;
1666 }
1667
1668 /**
1669 * Return the main window of this tab. Note: if a tab is freed in the
1670 * background, this can return null. It is only guaranteed to be
1671 * non-null for the current tab.
1672 * @return The main WebView of this tab.
1673 */
1674 WebView getWebView() {
1675 return mMainView;
1676 }
1677
1678 /**
1679 * Return the subwindow of this tab or null if there is no subwindow.
1680 * @return The subwindow of this tab or null.
1681 */
1682 WebView getSubWebView() {
1683 return mSubView;
1684 }
1685
1686 /**
1687 * @return The geolocation permissions prompt for this tab.
1688 */
1689 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
Grace Kloba50c241e2010-04-20 11:07:50 -07001690 if (mGeolocationPermissionsPrompt == null) {
1691 ViewStub stub = (ViewStub) mContainer
1692 .findViewById(R.id.geolocation_permissions_prompt);
1693 mGeolocationPermissionsPrompt = (GeolocationPermissionsPrompt) stub
1694 .inflate();
1695 mGeolocationPermissionsPrompt.init();
1696 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001697 return mGeolocationPermissionsPrompt;
1698 }
1699
1700 /**
1701 * @return The application id string
1702 */
1703 String getAppId() {
1704 return mAppId;
1705 }
1706
1707 /**
1708 * Set the application id string
1709 * @param id
1710 */
1711 void setAppId(String id) {
1712 mAppId = id;
1713 }
1714
1715 /**
1716 * @return The original url associated with this Tab
1717 */
1718 String getOriginalUrl() {
1719 return mOriginalUrl;
1720 }
1721
1722 /**
1723 * Set the original url associated with this tab
1724 */
1725 void setOriginalUrl(String url) {
1726 mOriginalUrl = url;
1727 }
1728
1729 /**
1730 * Get the url of this tab. Valid after calling populatePickerData, but
1731 * before calling wipePickerData, or if the webview has been destroyed.
1732 * @return The WebView's url or null.
1733 */
1734 String getUrl() {
1735 if (mPickerData != null) {
1736 return mPickerData.mUrl;
1737 }
1738 return null;
1739 }
1740
1741 /**
1742 * Get the title of this tab. Valid after calling populatePickerData, but
1743 * before calling wipePickerData, or if the webview has been destroyed. If
1744 * the url has no title, use the url instead.
1745 * @return The WebView's title (or url) or null.
1746 */
1747 String getTitle() {
1748 if (mPickerData != null) {
1749 return mPickerData.mTitle;
1750 }
1751 return null;
1752 }
1753
1754 /**
1755 * Get the favicon of this tab. Valid after calling populatePickerData, but
1756 * before calling wipePickerData, or if the webview has been destroyed.
1757 * @return The WebView's favicon or null.
1758 */
1759 Bitmap getFavicon() {
1760 if (mPickerData != null) {
1761 return mPickerData.mFavicon;
1762 }
1763 return null;
1764 }
1765
1766 /**
1767 * Return the tab's error console. Creates the console if createIfNEcessary
1768 * is true and we haven't already created the console.
1769 * @param createIfNecessary Flag to indicate if the console should be
1770 * created if it has not been already.
1771 * @return The tab's error console, or null if one has not been created and
1772 * createIfNecessary is false.
1773 */
1774 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1775 if (createIfNecessary && mErrorConsole == null) {
1776 mErrorConsole = new ErrorConsoleView(mActivity);
1777 mErrorConsole.setWebView(mMainView);
1778 }
1779 return mErrorConsole;
1780 }
1781
1782 /**
1783 * If this Tab was created through another Tab, then this method returns
1784 * that Tab.
1785 * @return the Tab parent or null
1786 */
1787 public Tab getParentTab() {
1788 return mParentTab;
1789 }
1790
1791 /**
1792 * Return whether this tab should be closed when it is backing out of the
1793 * first page.
1794 * @return TRUE if this tab should be closed when exit.
1795 */
1796 boolean closeOnExit() {
1797 return mCloseOnExit;
1798 }
1799
1800 /**
1801 * Saves the current lock-icon state before resetting the lock icon. If we
1802 * have an error, we may need to roll back to the previous state.
1803 */
1804 void resetLockIcon(String url) {
1805 mPrevLockIconType = mLockIconType;
1806 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1807 if (URLUtil.isHttpsUrl(url)) {
1808 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1809 }
1810 }
1811
1812 /**
1813 * Reverts the lock-icon state to the last saved state, for example, if we
1814 * had an error, and need to cancel the load.
1815 */
1816 void revertLockIcon() {
1817 mLockIconType = mPrevLockIconType;
1818 }
1819
1820 /**
1821 * @return The tab's lock icon type.
1822 */
1823 int getLockIconType() {
1824 return mLockIconType;
1825 }
1826
1827 /**
1828 * @return TRUE if onPageStarted is called while onPageFinished is not
1829 * called yet.
1830 */
1831 boolean inLoad() {
1832 return mInLoad;
1833 }
1834
1835 // force mInLoad to be false. This should only be called before closing the
1836 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1837 void clearInLoad() {
1838 mInLoad = false;
1839 }
1840
1841 void populatePickerData() {
1842 if (mMainView == null) {
1843 populatePickerDataFromSavedState();
1844 return;
1845 }
1846
1847 // FIXME: The only place we cared about subwindow was for
1848 // bookmarking (i.e. not when saving state). Was this deliberate?
1849 final WebBackForwardList list = mMainView.copyBackForwardList();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001850 if (list == null) {
1851 Log.w(LOGTAG, "populatePickerData called and WebBackForwardList is null");
1852 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001853 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1854 populatePickerData(item);
1855 }
1856
1857 // Populate the picker data using the given history item and the current top
1858 // WebView.
1859 private void populatePickerData(WebHistoryItem item) {
1860 mPickerData = new PickerData();
Leon Scroggins70a153b2010-05-10 17:27:26 -04001861 if (item == null) {
1862 Log.w(LOGTAG, "populatePickerData called with a null WebHistoryItem");
1863 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001864 mPickerData.mUrl = item.getUrl();
1865 mPickerData.mTitle = item.getTitle();
1866 mPickerData.mFavicon = item.getFavicon();
1867 if (mPickerData.mTitle == null) {
1868 mPickerData.mTitle = mPickerData.mUrl;
1869 }
1870 }
1871 }
1872
1873 // Create the PickerData and populate it using the saved state of the tab.
1874 void populatePickerDataFromSavedState() {
1875 if (mSavedState == null) {
1876 return;
1877 }
1878 mPickerData = new PickerData();
1879 mPickerData.mUrl = mSavedState.getString(CURRURL);
1880 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1881 }
1882
1883 void clearPickerData() {
1884 mPickerData = null;
1885 }
1886
1887 /**
1888 * Get the saved state bundle.
1889 * @return
1890 */
1891 Bundle getSavedState() {
1892 return mSavedState;
1893 }
1894
1895 /**
1896 * Set the saved state.
1897 */
1898 void setSavedState(Bundle state) {
1899 mSavedState = state;
1900 }
1901
1902 /**
1903 * @return TRUE if succeed in saving the state.
1904 */
1905 boolean saveState() {
1906 // If the WebView is null it means we ran low on memory and we already
1907 // stored the saved state in mSavedState.
1908 if (mMainView == null) {
1909 return mSavedState != null;
1910 }
1911
1912 mSavedState = new Bundle();
1913 final WebBackForwardList list = mMainView.saveState(mSavedState);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001914
1915 // Store some extra info for displaying the tab in the picker.
1916 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1917 populatePickerData(item);
1918
1919 if (mPickerData.mUrl != null) {
1920 mSavedState.putString(CURRURL, mPickerData.mUrl);
1921 }
1922 if (mPickerData.mTitle != null) {
1923 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1924 }
1925 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1926 if (mAppId != null) {
1927 mSavedState.putString(APPID, mAppId);
1928 }
1929 if (mOriginalUrl != null) {
1930 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1931 }
1932 // Remember the parent tab so the relationship can be restored.
1933 if (mParentTab != null) {
1934 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1935 mParentTab));
1936 }
1937 return true;
1938 }
1939
1940 /*
1941 * Restore the state of the tab.
1942 */
1943 boolean restoreState(Bundle b) {
1944 if (b == null) {
1945 return false;
1946 }
1947 // Restore the internal state even if the WebView fails to restore.
1948 // This will maintain the app id, original url and close-on-exit values.
1949 mSavedState = null;
1950 mPickerData = null;
1951 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1952 mAppId = b.getString(APPID);
1953 mOriginalUrl = b.getString(ORIGINALURL);
1954
1955 final WebBackForwardList list = mMainView.restoreState(b);
1956 if (list == null) {
1957 return false;
1958 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001959 return true;
1960 }
Leon Scroggins III211ba542010-04-19 13:21:13 -04001961
1962 /*
Cary Clark01cfcdd2010-06-04 16:36:45 -04001963 * Opens the find and select text dialogs. Called by BrowserActivity.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001964 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001965 WebView showDialog(WebDialog dialog) {
Leon Scroggins III211ba542010-04-19 13:21:13 -04001966 LinearLayout container;
1967 WebView view;
1968 if (mSubView != null) {
1969 view = mSubView;
1970 container = (LinearLayout) mSubViewContainer.findViewById(
1971 R.id.inner_container);
1972 } else {
1973 view = mMainView;
1974 container = mContainer;
1975 }
1976 dialog.show();
Leon Scroggins79e36d92010-04-29 16:01:46 +01001977 container.addView(dialog, 0, new LinearLayout.LayoutParams(
Leon Scroggins III211ba542010-04-19 13:21:13 -04001978 ViewGroup.LayoutParams.MATCH_PARENT,
1979 ViewGroup.LayoutParams.WRAP_CONTENT));
1980 dialog.setWebView(view);
Cary Clark01cfcdd2010-06-04 16:36:45 -04001981 return view;
Leon Scroggins III211ba542010-04-19 13:21:13 -04001982 }
1983
1984 /*
Cary Clark01cfcdd2010-06-04 16:36:45 -04001985 * Close the find or select dialog. Called by BrowserActivity.closeDialog.
Leon Scroggins III211ba542010-04-19 13:21:13 -04001986 */
Cary Clark01cfcdd2010-06-04 16:36:45 -04001987 void closeDialog(WebDialog dialog) {
Leon Scroggins III211ba542010-04-19 13:21:13 -04001988 // The dialog may be attached to the subwindow. Ensure that the
1989 // correct parent has it removed.
1990 LinearLayout parent = (LinearLayout) dialog.getParent();
1991 if (parent != null) parent.removeView(dialog);
1992 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001993}