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