blob: 7e03bbcec928c2505f0ce4e8870c223136e4b710 [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;
Grace Kloba22ac16e2009-10-07 18:00:23 -070021import java.util.LinkedList;
22import java.util.Vector;
23
24import android.app.AlertDialog;
Leon Scroggins58d56c62010-01-28 15:12:40 -050025import android.app.SearchManager;
Grace Kloba22ac16e2009-10-07 18:00:23 -070026import android.content.ContentResolver;
27import android.content.ContentValues;
28import android.content.DialogInterface;
29import android.content.DialogInterface.OnCancelListener;
Leon Scroggins58d56c62010-01-28 15:12:40 -050030import android.content.Intent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070031import android.database.Cursor;
32import android.database.sqlite.SQLiteDatabase;
33import android.database.sqlite.SQLiteException;
34import android.graphics.Bitmap;
35import android.net.Uri;
36import android.net.http.SslError;
37import android.os.AsyncTask;
38import android.os.Bundle;
39import android.os.Message;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +000040import android.os.SystemClock;
Grace Kloba22ac16e2009-10-07 18:00:23 -070041import android.provider.Browser;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050042import android.speech.RecognizerResultsIntent;
Grace Kloba22ac16e2009-10-07 18:00:23 -070043import android.util.Log;
44import android.view.KeyEvent;
45import android.view.LayoutInflater;
46import android.view.View;
47import android.view.ViewGroup;
48import android.view.View.OnClickListener;
Ben Murdochc42addf2010-01-28 15:19:59 +000049import android.webkit.ConsoleMessage;
Grace Kloba22ac16e2009-10-07 18:00:23 -070050import android.webkit.CookieSyncManager;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -050051import android.webkit.DownloadListener;
Grace Kloba22ac16e2009-10-07 18:00:23 -070052import android.webkit.GeolocationPermissions;
53import android.webkit.HttpAuthHandler;
54import android.webkit.SslErrorHandler;
55import android.webkit.URLUtil;
56import android.webkit.ValueCallback;
57import android.webkit.WebBackForwardList;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -050058import android.webkit.WebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -070059import android.webkit.WebChromeClient;
60import android.webkit.WebHistoryItem;
61import android.webkit.WebIconDatabase;
62import android.webkit.WebStorage;
63import android.webkit.WebView;
64import android.webkit.WebViewClient;
65import android.widget.FrameLayout;
66import android.widget.ImageButton;
67import android.widget.LinearLayout;
68import android.widget.TextView;
69
Leon Scroggins1fe13a52010-02-09 15:31:26 -050070import com.android.common.speech.LoggingEvents;
71
Grace Kloba22ac16e2009-10-07 18:00:23 -070072/**
73 * Class for maintaining Tabs with a main WebView and a subwindow.
74 */
75class Tab {
76 // Log Tag
77 private static final String LOGTAG = "Tab";
Ben Murdochc42addf2010-01-28 15:19:59 +000078 // Special case the logtag for messages for the Console to make it easier to
79 // filter them and match the logtag used for these messages in older versions
80 // of the browser.
81 private static final String CONSOLE_LOGTAG = "browser";
82
Grace Kloba22ac16e2009-10-07 18:00:23 -070083 // The Geolocation permissions prompt
84 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
85 // Main WebView wrapper
86 private View mContainer;
87 // Main WebView
88 private WebView mMainView;
89 // Subwindow container
90 private View mSubViewContainer;
91 // Subwindow WebView
92 private WebView mSubView;
93 // Saved bundle for when we are running low on memory. It contains the
94 // information needed to restore the WebView if the user goes back to the
95 // tab.
96 private Bundle mSavedState;
97 // Data used when displaying the tab in the picker.
98 private PickerData mPickerData;
99 // Parent Tab. This is the Tab that created this Tab, or null if the Tab was
100 // created by the UI
101 private Tab mParentTab;
102 // Tab that constructed by this Tab. This is used when this Tab is
103 // destroyed, it clears all mParentTab values in the children.
104 private Vector<Tab> mChildTabs;
105 // If true, the tab will be removed when back out of the first page.
106 private boolean mCloseOnExit;
107 // If true, the tab is in the foreground of the current activity.
108 private boolean mInForeground;
109 // If true, the tab is in loading state.
110 private boolean mInLoad;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000111 // The time the load started, used to find load page time
112 private long mLoadStartTime;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700113 // Application identifier used to find tabs that another application wants
114 // to reuse.
115 private String mAppId;
116 // Keep the original url around to avoid killing the old WebView if the url
117 // has not changed.
118 private String mOriginalUrl;
119 // Error console for the tab
120 private ErrorConsoleView mErrorConsole;
121 // the lock icon type and previous lock icon type for the tab
122 private int mLockIconType;
123 private int mPrevLockIconType;
124 // Inflation service for making subwindows.
125 private final LayoutInflater mInflateService;
126 // The BrowserActivity which owners the Tab
127 private final BrowserActivity mActivity;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -0500128 // The listener that gets invoked when a download is started from the
129 // mMainView
130 private final DownloadListener mDownloadListener;
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500131 // Listener used to know when we move forward or back in the history list.
132 private final WebBackForwardListClient mWebBackForwardListClient;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700133
134 // AsyncTask for downloading touch icons
135 DownloadTouchIcon mTouchIconLoader;
136
137 // Extra saved information for displaying the tab in the picker.
138 private static class PickerData {
139 String mUrl;
140 String mTitle;
141 Bitmap mFavicon;
142 }
143
144 // Used for saving and restoring each Tab
145 static final String WEBVIEW = "webview";
146 static final String NUMTABS = "numTabs";
147 static final String CURRTAB = "currentTab";
148 static final String CURRURL = "currentUrl";
149 static final String CURRTITLE = "currentTitle";
150 static final String CURRPICTURE = "currentPicture";
151 static final String CLOSEONEXIT = "closeonexit";
152 static final String PARENTTAB = "parentTab";
153 static final String APPID = "appid";
154 static final String ORIGINALURL = "originalUrl";
155
156 // -------------------------------------------------------------------------
157
Leon Scroggins58d56c62010-01-28 15:12:40 -0500158 /**
159 * Private information regarding the latest voice search. If the Tab is not
160 * in voice search mode, this will be null.
161 */
162 private VoiceSearchData mVoiceSearchData;
163 /**
164 * Return whether the tab is in voice search mode.
165 */
166 public boolean isInVoiceSearchMode() {
167 return mVoiceSearchData != null;
168 }
169 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500170 * Return true if the voice search Intent came with a String identifying
171 * that Google provided the Intent.
172 */
173 public boolean voiceSearchSourceIsGoogle() {
174 return mVoiceSearchData != null && mVoiceSearchData.mSourceIsGoogle;
175 }
176 /**
Leon Scroggins58d56c62010-01-28 15:12:40 -0500177 * Get the title to display for the current voice search page. If the Tab
178 * is not in voice search mode, return null.
179 */
180 public String getVoiceDisplayTitle() {
181 if (mVoiceSearchData == null) return null;
182 return mVoiceSearchData.mLastVoiceSearchTitle;
183 }
184 /**
185 * Get the latest array of voice search results, to be passed to the
186 * BrowserProvider. If the Tab is not in voice search mode, return null.
187 */
188 public ArrayList<String> getVoiceSearchResults() {
189 if (mVoiceSearchData == null) return null;
190 return mVoiceSearchData.mVoiceSearchResults;
191 }
192 /**
193 * Activate voice search mode.
194 * @param intent Intent which has the results to use, or an index into the
195 * results when reusing the old results.
196 */
197 /* package */ void activateVoiceSearchMode(Intent intent) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500198 int index = 0;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500199 ArrayList<String> results = intent.getStringArrayListExtra(
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500200 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_STRINGS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500201 if (results != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500202 ArrayList<String> urls = intent.getStringArrayListExtra(
203 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_URLS);
204 ArrayList<String> htmls = intent.getStringArrayListExtra(
205 RecognizerResultsIntent.EXTRA_VOICE_SEARCH_RESULT_HTML);
206 ArrayList<String> baseUrls = intent.getStringArrayListExtra(
207 RecognizerResultsIntent
208 .EXTRA_VOICE_SEARCH_RESULT_HTML_BASE_URLS);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500209 // This tab is now entering voice search mode for the first time, or
210 // a new voice search was done.
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500211 int size = results.size();
212 if (urls == null || size != urls.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500213 throw new AssertionError("improper extras passed in Intent");
214 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500215 if (htmls == null || htmls.size() != size || baseUrls == null ||
216 (baseUrls.size() != size && baseUrls.size() != 1)) {
217 // If either of these arrays are empty/incorrectly sized, ignore
218 // them.
219 htmls = null;
220 baseUrls = null;
221 }
222 mVoiceSearchData = new VoiceSearchData(results, urls, htmls,
223 baseUrls);
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500224 mVoiceSearchData.mSourceIsGoogle = intent.getBooleanExtra(
225 VoiceSearchData.SOURCE_IS_GOOGLE, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500226 } else {
227 String extraData = intent.getStringExtra(
228 SearchManager.EXTRA_DATA_KEY);
229 if (extraData != null) {
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500230 index = Integer.parseInt(extraData);
231 if (index >= mVoiceSearchData.mVoiceSearchResults.size()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500232 throw new AssertionError("index must be less than "
233 + " size of mVoiceSearchResults");
234 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500235 if (mVoiceSearchData.mSourceIsGoogle) {
236 Intent logIntent = new Intent(
237 LoggingEvents.ACTION_LOG_EVENT);
238 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
239 LoggingEvents.VoiceSearch.N_BEST_CHOOSE);
240 logIntent.putExtra(
241 LoggingEvents.VoiceSearch.EXTRA_N_BEST_CHOOSE_INDEX,
242 index);
243 mActivity.sendBroadcast(logIntent);
244 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500245 }
246 }
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500247 mVoiceSearchData.mVoiceSearchIntent = intent;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500248 mVoiceSearchData.mLastVoiceSearchTitle
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500249 = mVoiceSearchData.mVoiceSearchResults.get(index);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500250 if (mInForeground) {
251 mActivity.showVoiceTitleBar(mVoiceSearchData.mLastVoiceSearchTitle);
252 }
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500253 if (mVoiceSearchData.mVoiceSearchHtmls != null) {
254 // When index was found it was already ensured that it was valid
255 String uriString = mVoiceSearchData.mVoiceSearchHtmls.get(index);
256 if (uriString != null) {
257 Uri dataUri = Uri.parse(uriString);
258 if (RecognizerResultsIntent.URI_SCHEME_INLINE.equals(
259 dataUri.getScheme())) {
260 // If there is only one base URL, use it. If there are
261 // more, there will be one for each index, so use the base
262 // URL corresponding to the index.
263 String baseUrl = mVoiceSearchData.mVoiceSearchBaseUrls.get(
264 mVoiceSearchData.mVoiceSearchBaseUrls.size() > 1 ?
265 index : 0);
266 mVoiceSearchData.mLastVoiceSearchUrl = baseUrl;
267 mMainView.loadDataWithBaseURL(baseUrl,
268 uriString.substring(RecognizerResultsIntent
269 .URI_SCHEME_INLINE.length() + 1), "text/html",
270 "utf-8", baseUrl);
271 return;
272 }
273 }
274 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500275 mVoiceSearchData.mLastVoiceSearchUrl
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500276 = mVoiceSearchData.mVoiceSearchUrls.get(index);
277 if (null == mVoiceSearchData.mLastVoiceSearchUrl) {
278 mVoiceSearchData.mLastVoiceSearchUrl = mActivity.smartUrlFilter(
279 mVoiceSearchData.mLastVoiceSearchTitle);
280 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500281 mMainView.loadUrl(mVoiceSearchData.mLastVoiceSearchUrl);
282 }
283 /* package */ static class VoiceSearchData {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500284 public VoiceSearchData(ArrayList<String> results,
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500285 ArrayList<String> urls, ArrayList<String> htmls,
286 ArrayList<String> baseUrls) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500287 mVoiceSearchResults = results;
288 mVoiceSearchUrls = urls;
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500289 mVoiceSearchHtmls = htmls;
290 mVoiceSearchBaseUrls = baseUrls;
Leon Scroggins58d56c62010-01-28 15:12:40 -0500291 }
292 /*
293 * ArrayList of suggestions to be displayed when opening the
294 * SearchManager
295 */
296 public ArrayList<String> mVoiceSearchResults;
297 /*
298 * ArrayList of urls, associated with the suggestions in
299 * mVoiceSearchResults.
300 */
301 public ArrayList<String> mVoiceSearchUrls;
302 /*
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500303 * ArrayList holding content to load for each item in
304 * mVoiceSearchResults.
305 */
306 public ArrayList<String> mVoiceSearchHtmls;
307 /*
308 * ArrayList holding base urls for the items in mVoiceSearchResults.
309 * If non null, this will either have the same size as
310 * mVoiceSearchResults or have a size of 1, in which case all will use
311 * the same base url
312 */
313 public ArrayList<String> mVoiceSearchBaseUrls;
314 /*
Leon Scroggins58d56c62010-01-28 15:12:40 -0500315 * The last url provided by voice search. Used for comparison to see if
Leon Scroggins82c1baa2010-02-02 16:10:57 -0500316 * we are going to a page by some method besides voice search.
Leon Scroggins58d56c62010-01-28 15:12:40 -0500317 */
318 public String mLastVoiceSearchUrl;
319 /**
320 * The last title used for voice search. Needed to update the title bar
321 * when switching tabs.
322 */
323 public String mLastVoiceSearchTitle;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500324 /**
325 * Whether the Intent which turned on voice search mode contained the
326 * String signifying that Google was the source.
327 */
328 public boolean mSourceIsGoogle;
329 /**
Leon Scroggins0c75a8e2010-03-03 16:40:58 -0500330 * The Intent used to invoke voice search. Placed on the
331 * WebHistoryItem so that when coming back to a previous voice search
332 * page we can again activate voice search.
333 */
334 public Object mVoiceSearchIntent;
335 /**
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500336 * String used to identify Google as the source of voice search.
337 */
338 public static String SOURCE_IS_GOOGLE
339 = "android.speech.extras.SOURCE_IS_GOOGLE";
Leon Scroggins58d56c62010-01-28 15:12:40 -0500340 }
341
Grace Kloba22ac16e2009-10-07 18:00:23 -0700342 // Container class for the next error dialog that needs to be displayed
343 private class ErrorDialog {
344 public final int mTitle;
345 public final String mDescription;
346 public final int mError;
347 ErrorDialog(int title, String desc, int error) {
348 mTitle = title;
349 mDescription = desc;
350 mError = error;
351 }
352 };
353
354 private void processNextError() {
355 if (mQueuedErrors == null) {
356 return;
357 }
358 // The first one is currently displayed so just remove it.
359 mQueuedErrors.removeFirst();
360 if (mQueuedErrors.size() == 0) {
361 mQueuedErrors = null;
362 return;
363 }
364 showError(mQueuedErrors.getFirst());
365 }
366
367 private DialogInterface.OnDismissListener mDialogListener =
368 new DialogInterface.OnDismissListener() {
369 public void onDismiss(DialogInterface d) {
370 processNextError();
371 }
372 };
373 private LinkedList<ErrorDialog> mQueuedErrors;
374
375 private void queueError(int err, String desc) {
376 if (mQueuedErrors == null) {
377 mQueuedErrors = new LinkedList<ErrorDialog>();
378 }
379 for (ErrorDialog d : mQueuedErrors) {
380 if (d.mError == err) {
381 // Already saw a similar error, ignore the new one.
382 return;
383 }
384 }
385 ErrorDialog errDialog = new ErrorDialog(
386 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
387 R.string.browserFrameFileErrorLabel :
388 R.string.browserFrameNetworkErrorLabel,
389 desc, err);
390 mQueuedErrors.addLast(errDialog);
391
392 // Show the dialog now if the queue was empty and it is in foreground
393 if (mQueuedErrors.size() == 1 && mInForeground) {
394 showError(errDialog);
395 }
396 }
397
398 private void showError(ErrorDialog errDialog) {
399 if (mInForeground) {
400 AlertDialog d = new AlertDialog.Builder(mActivity)
401 .setTitle(errDialog.mTitle)
402 .setMessage(errDialog.mDescription)
403 .setPositiveButton(R.string.ok, null)
404 .create();
405 d.setOnDismissListener(mDialogListener);
406 d.show();
407 }
408 }
409
410 // -------------------------------------------------------------------------
411 // WebViewClient implementation for the main WebView
412 // -------------------------------------------------------------------------
413
414 private final WebViewClient mWebViewClient = new WebViewClient() {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500415 private Message mDontResend;
416 private Message mResend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700417 @Override
418 public void onPageStarted(WebView view, String url, Bitmap favicon) {
419 mInLoad = true;
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000420 mLoadStartTime = SystemClock.uptimeMillis();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500421 if (mVoiceSearchData != null
422 && !url.equals(mVoiceSearchData.mLastVoiceSearchUrl)) {
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500423 if (mVoiceSearchData.mSourceIsGoogle) {
424 Intent i = new Intent(LoggingEvents.ACTION_LOG_EVENT);
425 i.putExtra(LoggingEvents.EXTRA_FLUSH, true);
426 mActivity.sendBroadcast(i);
427 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500428 mVoiceSearchData = null;
429 if (mInForeground) {
430 mActivity.revertVoiceTitleBar();
431 }
432 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700433
434 // We've started to load a new page. If there was a pending message
435 // to save a screenshot then we will now take the new page and save
436 // an incorrect screenshot. Therefore, remove any pending thumbnail
437 // messages from the queue.
438 mActivity.removeMessages(BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL,
439 view);
440
441 // If we start a touch icon load and then load a new page, we don't
442 // want to cancel the current touch icon loader. But, we do want to
443 // create a new one when the touch icon url is known.
444 if (mTouchIconLoader != null) {
445 mTouchIconLoader.mTab = null;
446 mTouchIconLoader = null;
447 }
448
449 // reset the error console
450 if (mErrorConsole != null) {
451 mErrorConsole.clearErrorMessages();
452 if (mActivity.shouldShowErrorConsole()) {
453 mErrorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
454 }
455 }
456
457 // update the bookmark database for favicon
458 if (favicon != null) {
459 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
460 .getContentResolver(), view.getOriginalUrl(), view
461 .getUrl(), favicon);
462 }
463
464 // reset sync timer to avoid sync starts during loading a page
465 CookieSyncManager.getInstance().resetSync();
466
467 if (!mActivity.isNetworkUp()) {
468 view.setNetworkAvailable(false);
469 }
470
471 // finally update the UI in the activity if it is in the foreground
472 if (mInForeground) {
473 mActivity.onPageStarted(view, url, favicon);
474 }
475 }
476
477 @Override
478 public void onPageFinished(WebView view, String url) {
Kristian Monsen4dce3bf2010-02-02 13:37:09 +0000479 LogTag.logPageFinishedLoading(
480 url, SystemClock.uptimeMillis() - mLoadStartTime);
Grace Kloba22ac16e2009-10-07 18:00:23 -0700481 mInLoad = false;
482
483 if (mInForeground && !mActivity.didUserStopLoading()
484 || !mInForeground) {
485 // Only update the bookmark screenshot if the user did not
486 // cancel the load early.
487 mActivity.postMessage(
488 BrowserActivity.UPDATE_BOOKMARK_THUMBNAIL, 0, 0, view,
489 500);
490 }
491
492 // finally update the UI in the activity if it is in the foreground
493 if (mInForeground) {
494 mActivity.onPageFinished(view, url);
495 }
496 }
497
498 // return true if want to hijack the url to let another app to handle it
499 @Override
500 public boolean shouldOverrideUrlLoading(WebView view, String url) {
501 if (mInForeground) {
502 return mActivity.shouldOverrideUrlLoading(view, url);
503 } else {
504 return false;
505 }
506 }
507
508 /**
509 * Updates the lock icon. This method is called when we discover another
510 * resource to be loaded for this page (for example, javascript). While
511 * we update the icon type, we do not update the lock icon itself until
512 * we are done loading, it is slightly more secure this way.
513 */
514 @Override
515 public void onLoadResource(WebView view, String url) {
516 if (url != null && url.length() > 0) {
517 // It is only if the page claims to be secure that we may have
518 // to update the lock:
519 if (mLockIconType == BrowserActivity.LOCK_ICON_SECURE) {
520 // If NOT a 'safe' url, change the lock to mixed content!
521 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url)
522 || URLUtil.isAboutUrl(url))) {
523 mLockIconType = BrowserActivity.LOCK_ICON_MIXED;
524 }
525 }
526 }
527 }
528
529 /**
Grace Kloba22ac16e2009-10-07 18:00:23 -0700530 * Show a dialog informing the user of the network error reported by
531 * WebCore if it is in the foreground.
532 */
533 @Override
534 public void onReceivedError(WebView view, int errorCode,
535 String description, String failingUrl) {
536 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
537 errorCode != WebViewClient.ERROR_CONNECT &&
538 errorCode != WebViewClient.ERROR_BAD_URL &&
539 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
540 errorCode != WebViewClient.ERROR_FILE) {
541 queueError(errorCode, description);
542 }
543 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
544 + " " + description);
545
546 // We need to reset the title after an error if it is in foreground.
547 if (mInForeground) {
548 mActivity.resetTitleAndRevertLockIcon();
549 }
550 }
551
552 /**
553 * Check with the user if it is ok to resend POST data as the page they
554 * are trying to navigate to is the result of a POST.
555 */
556 @Override
557 public void onFormResubmission(WebView view, final Message dontResend,
558 final Message resend) {
559 if (!mInForeground) {
560 dontResend.sendToTarget();
561 return;
562 }
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500563 if (mDontResend != null) {
564 Log.w(LOGTAG, "onFormResubmission should not be called again "
565 + "while dialog is still up");
566 dontResend.sendToTarget();
567 return;
568 }
569 mDontResend = dontResend;
570 mResend = resend;
Grace Kloba22ac16e2009-10-07 18:00:23 -0700571 new AlertDialog.Builder(mActivity).setTitle(
572 R.string.browserFrameFormResubmitLabel).setMessage(
573 R.string.browserFrameFormResubmitMessage)
574 .setPositiveButton(R.string.ok,
575 new DialogInterface.OnClickListener() {
576 public void onClick(DialogInterface dialog,
577 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500578 if (mResend != null) {
579 mResend.sendToTarget();
580 mResend = null;
581 mDontResend = null;
582 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700583 }
584 }).setNegativeButton(R.string.cancel,
585 new DialogInterface.OnClickListener() {
586 public void onClick(DialogInterface dialog,
587 int which) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500588 if (mDontResend != null) {
589 mDontResend.sendToTarget();
590 mResend = null;
591 mDontResend = null;
592 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700593 }
594 }).setOnCancelListener(new OnCancelListener() {
595 public void onCancel(DialogInterface dialog) {
Leon Scroggins4a64a8a2010-03-02 17:57:40 -0500596 if (mDontResend != null) {
597 mDontResend.sendToTarget();
598 mResend = null;
599 mDontResend = null;
600 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700601 }
602 }).show();
603 }
604
605 /**
606 * Insert the url into the visited history database.
607 * @param url The url to be inserted.
608 * @param isReload True if this url is being reloaded.
609 * FIXME: Not sure what to do when reloading the page.
610 */
611 @Override
612 public void doUpdateVisitedHistory(WebView view, String url,
613 boolean isReload) {
614 if (url.regionMatches(true, 0, "about:", 0, 6)) {
615 return;
616 }
617 // remove "client" before updating it to the history so that it wont
618 // show up in the auto-complete list.
619 int index = url.indexOf("client=ms-");
620 if (index > 0 && url.contains(".google.")) {
621 int end = url.indexOf('&', index);
622 if (end > 0) {
623 url = url.substring(0, index)
624 .concat(url.substring(end + 1));
625 } else {
626 // the url.charAt(index-1) should be either '?' or '&'
627 url = url.substring(0, index-1);
628 }
629 }
630 Browser.updateVisitedHistory(mActivity.getContentResolver(), url,
631 true);
632 WebIconDatabase.getInstance().retainIconForPageUrl(url);
633 }
634
635 /**
636 * Displays SSL error(s) dialog to the user.
637 */
638 @Override
639 public void onReceivedSslError(final WebView view,
640 final SslErrorHandler handler, final SslError error) {
641 if (!mInForeground) {
642 handler.cancel();
643 return;
644 }
645 if (BrowserSettings.getInstance().showSecurityWarnings()) {
646 final LayoutInflater factory =
647 LayoutInflater.from(mActivity);
648 final View warningsView =
649 factory.inflate(R.layout.ssl_warnings, null);
650 final LinearLayout placeholder =
651 (LinearLayout)warningsView.findViewById(R.id.placeholder);
652
653 if (error.hasError(SslError.SSL_UNTRUSTED)) {
654 LinearLayout ll = (LinearLayout)factory
655 .inflate(R.layout.ssl_warning, null);
656 ((TextView)ll.findViewById(R.id.warning))
657 .setText(R.string.ssl_untrusted);
658 placeholder.addView(ll);
659 }
660
661 if (error.hasError(SslError.SSL_IDMISMATCH)) {
662 LinearLayout ll = (LinearLayout)factory
663 .inflate(R.layout.ssl_warning, null);
664 ((TextView)ll.findViewById(R.id.warning))
665 .setText(R.string.ssl_mismatch);
666 placeholder.addView(ll);
667 }
668
669 if (error.hasError(SslError.SSL_EXPIRED)) {
670 LinearLayout ll = (LinearLayout)factory
671 .inflate(R.layout.ssl_warning, null);
672 ((TextView)ll.findViewById(R.id.warning))
673 .setText(R.string.ssl_expired);
674 placeholder.addView(ll);
675 }
676
677 if (error.hasError(SslError.SSL_NOTYETVALID)) {
678 LinearLayout ll = (LinearLayout)factory
679 .inflate(R.layout.ssl_warning, null);
680 ((TextView)ll.findViewById(R.id.warning))
681 .setText(R.string.ssl_not_yet_valid);
682 placeholder.addView(ll);
683 }
684
685 new AlertDialog.Builder(mActivity).setTitle(
686 R.string.security_warning).setIcon(
687 android.R.drawable.ic_dialog_alert).setView(
688 warningsView).setPositiveButton(R.string.ssl_continue,
689 new DialogInterface.OnClickListener() {
690 public void onClick(DialogInterface dialog,
691 int whichButton) {
692 handler.proceed();
693 }
694 }).setNeutralButton(R.string.view_certificate,
695 new DialogInterface.OnClickListener() {
696 public void onClick(DialogInterface dialog,
697 int whichButton) {
698 mActivity.showSSLCertificateOnError(view,
699 handler, error);
700 }
701 }).setNegativeButton(R.string.cancel,
702 new DialogInterface.OnClickListener() {
703 public void onClick(DialogInterface dialog,
704 int whichButton) {
705 handler.cancel();
706 mActivity.resetTitleAndRevertLockIcon();
707 }
708 }).setOnCancelListener(
709 new DialogInterface.OnCancelListener() {
710 public void onCancel(DialogInterface dialog) {
711 handler.cancel();
712 mActivity.resetTitleAndRevertLockIcon();
713 }
714 }).show();
715 } else {
716 handler.proceed();
717 }
718 }
719
720 /**
721 * Handles an HTTP authentication request.
722 *
723 * @param handler The authentication handler
724 * @param host The host
725 * @param realm The realm
726 */
727 @Override
728 public void onReceivedHttpAuthRequest(WebView view,
729 final HttpAuthHandler handler, final String host,
730 final String realm) {
731 String username = null;
732 String password = null;
733
734 boolean reuseHttpAuthUsernamePassword = handler
735 .useHttpAuthUsernamePassword();
736
737 if (reuseHttpAuthUsernamePassword && mMainView != null) {
738 String[] credentials = mMainView.getHttpAuthUsernamePassword(
739 host, realm);
740 if (credentials != null && credentials.length == 2) {
741 username = credentials[0];
742 password = credentials[1];
743 }
744 }
745
746 if (username != null && password != null) {
747 handler.proceed(username, password);
748 } else {
749 if (mInForeground) {
750 mActivity.showHttpAuthentication(handler, host, realm,
751 null, null, null, 0);
752 } else {
753 handler.cancel();
754 }
755 }
756 }
757
758 @Override
759 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
760 if (!mInForeground) {
761 return false;
762 }
763 if (mActivity.isMenuDown()) {
764 // only check shortcut key when MENU is held
765 return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
766 event);
767 } else {
768 return false;
769 }
770 }
771
772 @Override
773 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
774 if (!mInForeground) {
775 return;
776 }
777 if (event.isDown()) {
778 mActivity.onKeyDown(event.getKeyCode(), event);
779 } else {
780 mActivity.onKeyUp(event.getKeyCode(), event);
781 }
782 }
783 };
784
785 // -------------------------------------------------------------------------
786 // WebChromeClient implementation for the main WebView
787 // -------------------------------------------------------------------------
788
789 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
790 // Helper method to create a new tab or sub window.
791 private void createWindow(final boolean dialog, final Message msg) {
792 WebView.WebViewTransport transport =
793 (WebView.WebViewTransport) msg.obj;
794 if (dialog) {
795 createSubWindow();
796 mActivity.attachSubWindow(Tab.this);
797 transport.setWebView(mSubView);
798 } else {
799 final Tab newTab = mActivity.openTabAndShow(
800 BrowserActivity.EMPTY_URL_DATA, false, null);
801 if (newTab != Tab.this) {
802 Tab.this.addChildTab(newTab);
803 }
804 transport.setWebView(newTab.getWebView());
805 }
806 msg.sendToTarget();
807 }
808
809 @Override
810 public boolean onCreateWindow(WebView view, final boolean dialog,
811 final boolean userGesture, final Message resultMsg) {
812 // only allow new window or sub window for the foreground case
813 if (!mInForeground) {
814 return false;
815 }
816 // Short-circuit if we can't create any more tabs or sub windows.
817 if (dialog && mSubView != null) {
818 new AlertDialog.Builder(mActivity)
819 .setTitle(R.string.too_many_subwindows_dialog_title)
820 .setIcon(android.R.drawable.ic_dialog_alert)
821 .setMessage(R.string.too_many_subwindows_dialog_message)
822 .setPositiveButton(R.string.ok, null)
823 .show();
824 return false;
825 } else if (!mActivity.getTabControl().canCreateNewTab()) {
826 new AlertDialog.Builder(mActivity)
827 .setTitle(R.string.too_many_windows_dialog_title)
828 .setIcon(android.R.drawable.ic_dialog_alert)
829 .setMessage(R.string.too_many_windows_dialog_message)
830 .setPositiveButton(R.string.ok, null)
831 .show();
832 return false;
833 }
834
835 // Short-circuit if this was a user gesture.
836 if (userGesture) {
837 createWindow(dialog, resultMsg);
838 return true;
839 }
840
841 // Allow the popup and create the appropriate window.
842 final AlertDialog.OnClickListener allowListener =
843 new AlertDialog.OnClickListener() {
844 public void onClick(DialogInterface d,
845 int which) {
846 createWindow(dialog, resultMsg);
847 }
848 };
849
850 // Block the popup by returning a null WebView.
851 final AlertDialog.OnClickListener blockListener =
852 new AlertDialog.OnClickListener() {
853 public void onClick(DialogInterface d, int which) {
854 resultMsg.sendToTarget();
855 }
856 };
857
858 // Build a confirmation dialog to display to the user.
859 final AlertDialog d =
860 new AlertDialog.Builder(mActivity)
861 .setTitle(R.string.attention)
862 .setIcon(android.R.drawable.ic_dialog_alert)
863 .setMessage(R.string.popup_window_attempt)
864 .setPositiveButton(R.string.allow, allowListener)
865 .setNegativeButton(R.string.block, blockListener)
866 .setCancelable(false)
867 .create();
868
869 // Show the confirmation dialog.
870 d.show();
871 return true;
872 }
873
874 @Override
Patrick Scotteb5061b2009-11-18 15:00:30 -0500875 public void onRequestFocus(WebView view) {
876 if (!mInForeground) {
877 mActivity.switchToTab(mActivity.getTabControl().getTabIndex(
878 Tab.this));
879 }
880 }
881
882 @Override
Grace Kloba22ac16e2009-10-07 18:00:23 -0700883 public void onCloseWindow(WebView window) {
884 if (mParentTab != null) {
885 // JavaScript can only close popup window.
886 if (mInForeground) {
887 mActivity.switchToTab(mActivity.getTabControl()
888 .getTabIndex(mParentTab));
889 }
890 mActivity.closeTab(Tab.this);
891 }
892 }
893
894 @Override
895 public void onProgressChanged(WebView view, int newProgress) {
896 if (newProgress == 100) {
897 // sync cookies and cache promptly here.
898 CookieSyncManager.getInstance().sync();
899 }
900 if (mInForeground) {
901 mActivity.onProgressChanged(view, newProgress);
902 }
903 }
904
905 @Override
906 public void onReceivedTitle(WebView view, String title) {
907 String url = view.getUrl();
908 if (mInForeground) {
909 // here, if url is null, we want to reset the title
910 mActivity.setUrlTitle(url, title);
911 }
912 if (url == null ||
913 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
914 return;
915 }
916 // See if we can find the current url in our history database and
917 // add the new title to it.
918 if (url.startsWith("http://www.")) {
919 url = url.substring(11);
920 } else if (url.startsWith("http://")) {
921 url = url.substring(4);
922 }
923 try {
924 final ContentResolver cr = mActivity.getContentResolver();
925 url = "%" + url;
926 String [] selArgs = new String[] { url };
927 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
928 + Browser.BookmarkColumns.BOOKMARK + " = 0";
929 Cursor c = cr.query(Browser.BOOKMARKS_URI,
930 Browser.HISTORY_PROJECTION, where, selArgs, null);
931 if (c.moveToFirst()) {
932 // Current implementation of database only has one entry per
933 // url.
934 ContentValues map = new ContentValues();
935 map.put(Browser.BookmarkColumns.TITLE, title);
936 cr.update(Browser.BOOKMARKS_URI, map, "_id = "
937 + c.getInt(0), null);
938 }
939 c.close();
940 } catch (IllegalStateException e) {
941 Log.e(LOGTAG, "Tab onReceived title", e);
942 } catch (SQLiteException ex) {
943 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
944 }
945 }
946
947 @Override
948 public void onReceivedIcon(WebView view, Bitmap icon) {
949 if (icon != null) {
950 BrowserBookmarksAdapter.updateBookmarkFavicon(mActivity
951 .getContentResolver(), view.getOriginalUrl(), view
952 .getUrl(), icon);
953 }
954 if (mInForeground) {
955 mActivity.setFavicon(icon);
956 }
957 }
958
959 @Override
960 public void onReceivedTouchIconUrl(WebView view, String url,
961 boolean precomposed) {
962 final ContentResolver cr = mActivity.getContentResolver();
963 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
964 view.getOriginalUrl(), view.getUrl(), true);
965 if (c != null) {
966 if (c.getCount() > 0) {
967 // Let precomposed icons take precedence over non-composed
968 // icons.
969 if (precomposed && mTouchIconLoader != null) {
970 mTouchIconLoader.cancel(false);
971 mTouchIconLoader = null;
972 }
973 // Have only one async task at a time.
974 if (mTouchIconLoader == null) {
975 mTouchIconLoader = new DownloadTouchIcon(Tab.this, cr,
976 c, view);
977 mTouchIconLoader.execute(url);
978 }
979 } else {
980 c.close();
981 }
982 }
983 }
984
985 @Override
986 public void onShowCustomView(View view,
987 WebChromeClient.CustomViewCallback callback) {
988 if (mInForeground) mActivity.onShowCustomView(view, callback);
989 }
990
991 @Override
992 public void onHideCustomView() {
993 if (mInForeground) mActivity.onHideCustomView();
994 }
995
996 /**
997 * The origin has exceeded its database quota.
998 * @param url the URL that exceeded the quota
999 * @param databaseIdentifier the identifier of the database on which the
1000 * transaction that caused the quota overflow was run
1001 * @param currentQuota the current quota for the origin.
1002 * @param estimatedSize the estimated size of the database.
1003 * @param totalUsedQuota is the sum of all origins' quota.
1004 * @param quotaUpdater The callback to run when a decision to allow or
1005 * deny quota has been made. Don't forget to call this!
1006 */
1007 @Override
1008 public void onExceededDatabaseQuota(String url,
1009 String databaseIdentifier, long currentQuota, long estimatedSize,
1010 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1011 BrowserSettings.getInstance().getWebStorageSizeManager()
1012 .onExceededDatabaseQuota(url, databaseIdentifier,
1013 currentQuota, estimatedSize, totalUsedQuota,
1014 quotaUpdater);
1015 }
1016
1017 /**
1018 * The Application Cache has exceeded its max size.
1019 * @param spaceNeeded is the amount of disk space that would be needed
1020 * in order for the last appcache operation to succeed.
1021 * @param totalUsedQuota is the sum of all origins' quota.
1022 * @param quotaUpdater A callback to inform the WebCore thread that a
1023 * new app cache size is available. This callback must always
1024 * be executed at some point to ensure that the sleeping
1025 * WebCore thread is woken up.
1026 */
1027 @Override
1028 public void onReachedMaxAppCacheSize(long spaceNeeded,
1029 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
1030 BrowserSettings.getInstance().getWebStorageSizeManager()
1031 .onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota,
1032 quotaUpdater);
1033 }
1034
1035 /**
1036 * Instructs the browser to show a prompt to ask the user to set the
1037 * Geolocation permission state for the specified origin.
1038 * @param origin The origin for which Geolocation permissions are
1039 * requested.
1040 * @param callback The callback to call once the user has set the
1041 * Geolocation permission state.
1042 */
1043 @Override
1044 public void onGeolocationPermissionsShowPrompt(String origin,
1045 GeolocationPermissions.Callback callback) {
1046 if (mInForeground) {
1047 mGeolocationPermissionsPrompt.show(origin, callback);
1048 }
1049 }
1050
1051 /**
1052 * Instructs the browser to hide the Geolocation permissions prompt.
1053 */
1054 @Override
1055 public void onGeolocationPermissionsHidePrompt() {
1056 if (mInForeground) {
1057 mGeolocationPermissionsPrompt.hide();
1058 }
1059 }
1060
Ben Murdoch65acc352009-11-19 18:16:04 +00001061 /* Adds a JavaScript error message to the system log and if the JS
1062 * console is enabled in the about:debug options, to that console
1063 * also.
Ben Murdochc42addf2010-01-28 15:19:59 +00001064 * @param consoleMessage the message object.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001065 */
1066 @Override
Ben Murdochc42addf2010-01-28 15:19:59 +00001067 public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 if (mInForeground) {
1069 // call getErrorConsole(true) so it will create one if needed
1070 ErrorConsoleView errorConsole = getErrorConsole(true);
Ben Murdochc42addf2010-01-28 15:19:59 +00001071 errorConsole.addErrorMessage(consoleMessage);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001072 if (mActivity.shouldShowErrorConsole()
1073 && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
1074 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1075 }
1076 }
Ben Murdochc42addf2010-01-28 15:19:59 +00001077
1078 String message = "Console: " + consoleMessage.message() + " "
1079 + consoleMessage.sourceId() + ":"
1080 + consoleMessage.lineNumber();
1081
1082 switch (consoleMessage.messageLevel()) {
1083 case TIP:
1084 Log.v(CONSOLE_LOGTAG, message);
1085 break;
1086 case LOG:
1087 Log.i(CONSOLE_LOGTAG, message);
1088 break;
1089 case WARNING:
1090 Log.w(CONSOLE_LOGTAG, message);
1091 break;
1092 case ERROR:
1093 Log.e(CONSOLE_LOGTAG, message);
1094 break;
1095 case DEBUG:
1096 Log.d(CONSOLE_LOGTAG, message);
1097 break;
1098 }
1099
1100 return true;
Grace Kloba22ac16e2009-10-07 18:00:23 -07001101 }
1102
1103 /**
1104 * Ask the browser for an icon to represent a <video> element.
1105 * This icon will be used if the Web page did not specify a poster attribute.
1106 * @return Bitmap The icon or null if no such icon is available.
1107 */
1108 @Override
1109 public Bitmap getDefaultVideoPoster() {
1110 if (mInForeground) {
1111 return mActivity.getDefaultVideoPoster();
1112 }
1113 return null;
1114 }
1115
1116 /**
1117 * Ask the host application for a custom progress view to show while
1118 * a <video> is loading.
1119 * @return View The progress view.
1120 */
1121 @Override
1122 public View getVideoLoadingProgressView() {
1123 if (mInForeground) {
1124 return mActivity.getVideoLoadingProgressView();
1125 }
1126 return null;
1127 }
1128
1129 @Override
1130 public void openFileChooser(ValueCallback<Uri> uploadMsg) {
1131 if (mInForeground) {
1132 mActivity.openFileChooser(uploadMsg);
1133 } else {
1134 uploadMsg.onReceiveValue(null);
1135 }
1136 }
1137
1138 /**
1139 * Deliver a list of already-visited URLs
1140 */
1141 @Override
1142 public void getVisitedHistory(final ValueCallback<String[]> callback) {
1143 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
1144 public String[] doInBackground(Void... unused) {
1145 return Browser.getVisitedHistory(mActivity
1146 .getContentResolver());
1147 }
1148 public void onPostExecute(String[] result) {
1149 callback.onReceiveValue(result);
1150 };
1151 };
1152 task.execute();
1153 };
1154 };
1155
1156 // -------------------------------------------------------------------------
1157 // WebViewClient implementation for the sub window
1158 // -------------------------------------------------------------------------
1159
1160 // Subclass of WebViewClient used in subwindows to notify the main
1161 // WebViewClient of certain WebView activities.
1162 private static class SubWindowClient extends WebViewClient {
1163 // The main WebViewClient.
1164 private final WebViewClient mClient;
1165
1166 SubWindowClient(WebViewClient client) {
1167 mClient = client;
1168 }
1169 @Override
1170 public void doUpdateVisitedHistory(WebView view, String url,
1171 boolean isReload) {
1172 mClient.doUpdateVisitedHistory(view, url, isReload);
1173 }
1174 @Override
1175 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1176 return mClient.shouldOverrideUrlLoading(view, url);
1177 }
1178 @Override
1179 public void onReceivedSslError(WebView view, SslErrorHandler handler,
1180 SslError error) {
1181 mClient.onReceivedSslError(view, handler, error);
1182 }
1183 @Override
1184 public void onReceivedHttpAuthRequest(WebView view,
1185 HttpAuthHandler handler, String host, String realm) {
1186 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
1187 }
1188 @Override
1189 public void onFormResubmission(WebView view, Message dontResend,
1190 Message resend) {
1191 mClient.onFormResubmission(view, dontResend, resend);
1192 }
1193 @Override
1194 public void onReceivedError(WebView view, int errorCode,
1195 String description, String failingUrl) {
1196 mClient.onReceivedError(view, errorCode, description, failingUrl);
1197 }
1198 @Override
1199 public boolean shouldOverrideKeyEvent(WebView view,
1200 android.view.KeyEvent event) {
1201 return mClient.shouldOverrideKeyEvent(view, event);
1202 }
1203 @Override
1204 public void onUnhandledKeyEvent(WebView view,
1205 android.view.KeyEvent event) {
1206 mClient.onUnhandledKeyEvent(view, event);
1207 }
1208 }
1209
1210 // -------------------------------------------------------------------------
1211 // WebChromeClient implementation for the sub window
1212 // -------------------------------------------------------------------------
1213
1214 private class SubWindowChromeClient extends WebChromeClient {
1215 // The main WebChromeClient.
1216 private final WebChromeClient mClient;
1217
1218 SubWindowChromeClient(WebChromeClient client) {
1219 mClient = client;
1220 }
1221 @Override
1222 public void onProgressChanged(WebView view, int newProgress) {
1223 mClient.onProgressChanged(view, newProgress);
1224 }
1225 @Override
1226 public boolean onCreateWindow(WebView view, boolean dialog,
1227 boolean userGesture, android.os.Message resultMsg) {
1228 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
1229 }
1230 @Override
1231 public void onCloseWindow(WebView window) {
1232 if (window != mSubView) {
1233 Log.e(LOGTAG, "Can't close the window");
1234 }
1235 mActivity.dismissSubWindow(Tab.this);
1236 }
1237 }
1238
1239 // -------------------------------------------------------------------------
1240
1241 // Construct a new tab
1242 Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1243 String url) {
1244 mActivity = activity;
1245 mCloseOnExit = closeOnExit;
1246 mAppId = appId;
1247 mOriginalUrl = url;
1248 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1249 mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1250 mInLoad = false;
1251 mInForeground = false;
1252
1253 mInflateService = LayoutInflater.from(activity);
1254
1255 // The tab consists of a container view, which contains the main
1256 // WebView, as well as any other UI elements associated with the tab.
1257 mContainer = mInflateService.inflate(R.layout.tab, null);
1258
1259 mGeolocationPermissionsPrompt =
1260 (GeolocationPermissionsPrompt) mContainer.findViewById(
1261 R.id.geolocation_permissions_prompt);
1262
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001263 mDownloadListener = new DownloadListener() {
1264 public void onDownloadStart(String url, String userAgent,
1265 String contentDisposition, String mimetype,
1266 long contentLength) {
1267 mActivity.onDownloadStart(url, userAgent, contentDisposition,
1268 mimetype, contentLength);
1269 if (mMainView.copyBackForwardList().getSize() == 0) {
1270 // This Tab was opened for the sole purpose of downloading a
1271 // file. Remove it.
1272 if (mActivity.getTabControl().getCurrentWebView()
1273 == mMainView) {
1274 // In this case, the Tab is still on top.
1275 mActivity.goBackOnePageOrQuit();
1276 } else {
1277 // In this case, it is not.
1278 mActivity.closeTab(Tab.this);
1279 }
1280 }
1281 }
1282 };
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001283 mWebBackForwardListClient = new WebBackForwardListClient() {
1284 @Override
1285 public void onNewHistoryItem(WebHistoryItem item) {
1286 if (isInVoiceSearchMode()) {
1287 item.setCustomData(mVoiceSearchData.mVoiceSearchIntent);
1288 }
1289 }
1290 @Override
1291 public void onIndexChanged(WebHistoryItem item, int index) {
1292 Object data = item.getCustomData();
1293 if (data != null && data instanceof Intent) {
1294 activateVoiceSearchMode((Intent) data);
1295 }
1296 }
1297 };
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001298
Grace Kloba22ac16e2009-10-07 18:00:23 -07001299 setWebView(w);
1300 }
1301
1302 /**
1303 * Sets the WebView for this tab, correctly removing the old WebView from
1304 * the container view.
1305 */
1306 void setWebView(WebView w) {
1307 if (mMainView == w) {
1308 return;
1309 }
1310 // If the WebView is changing, the page will be reloaded, so any ongoing
1311 // Geolocation permission requests are void.
1312 mGeolocationPermissionsPrompt.hide();
1313
1314 // Just remove the old one.
1315 FrameLayout wrapper =
1316 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1317 wrapper.removeView(mMainView);
1318
1319 // set the new one
1320 mMainView = w;
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001321 // attach the WebViewClient, WebChromeClient and DownloadListener
Grace Kloba22ac16e2009-10-07 18:00:23 -07001322 if (mMainView != null) {
1323 mMainView.setWebViewClient(mWebViewClient);
1324 mMainView.setWebChromeClient(mWebChromeClient);
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001325 // Attach DownloadManager so that downloads can start in an active
1326 // or a non-active window. This can happen when going to a site that
1327 // does a redirect after a period of time. The user could have
1328 // switched to another tab while waiting for the download to start.
1329 mMainView.setDownloadListener(mDownloadListener);
Leon Scroggins0c75a8e2010-03-03 16:40:58 -05001330 mMainView.setWebBackForwardListClient(mWebBackForwardListClient);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001331 }
1332 }
1333
1334 /**
1335 * Destroy the tab's main WebView and subWindow if any
1336 */
1337 void destroy() {
1338 if (mMainView != null) {
1339 dismissSubWindow();
1340 BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1341 // save the WebView to call destroy() after detach it from the tab
1342 WebView webView = mMainView;
1343 setWebView(null);
1344 webView.destroy();
1345 }
1346 }
1347
1348 /**
1349 * Remove the tab from the parent
1350 */
1351 void removeFromTree() {
1352 // detach the children
1353 if (mChildTabs != null) {
1354 for(Tab t : mChildTabs) {
1355 t.setParentTab(null);
1356 }
1357 }
1358 // remove itself from the parent list
1359 if (mParentTab != null) {
1360 mParentTab.mChildTabs.remove(this);
1361 }
1362 }
1363
1364 /**
1365 * Create a new subwindow unless a subwindow already exists.
1366 * @return True if a new subwindow was created. False if one already exists.
1367 */
1368 boolean createSubWindow() {
1369 if (mSubView == null) {
1370 mSubViewContainer = mInflateService.inflate(
1371 R.layout.browser_subwindow, null);
1372 mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1373 // use trackball directly
1374 mSubView.setMapTrackballToArrowKeys(false);
1375 mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1376 mSubView.setWebChromeClient(new SubWindowChromeClient(
1377 mWebChromeClient));
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001378 // Set a different DownloadListener for the mSubView, since it will
1379 // just need to dismiss the mSubView, rather than close the Tab
1380 mSubView.setDownloadListener(new DownloadListener() {
1381 public void onDownloadStart(String url, String userAgent,
1382 String contentDisposition, String mimetype,
1383 long contentLength) {
1384 mActivity.onDownloadStart(url, userAgent,
1385 contentDisposition, mimetype, contentLength);
1386 if (mSubView.copyBackForwardList().getSize() == 0) {
1387 // This subwindow was opened for the sole purpose of
1388 // downloading a file. Remove it.
1389 dismissSubWindow();
1390 }
1391 }
1392 });
Grace Kloba22ac16e2009-10-07 18:00:23 -07001393 mSubView.setOnCreateContextMenuListener(mActivity);
1394 final BrowserSettings s = BrowserSettings.getInstance();
1395 s.addObserver(mSubView.getSettings()).update(s, null);
1396 final ImageButton cancel = (ImageButton) mSubViewContainer
1397 .findViewById(R.id.subwindow_close);
1398 cancel.setOnClickListener(new OnClickListener() {
1399 public void onClick(View v) {
1400 mSubView.getWebChromeClient().onCloseWindow(mSubView);
1401 }
1402 });
1403 return true;
1404 }
1405 return false;
1406 }
1407
1408 /**
1409 * Dismiss the subWindow for the tab.
1410 */
1411 void dismissSubWindow() {
1412 if (mSubView != null) {
1413 BrowserSettings.getInstance().deleteObserver(
1414 mSubView.getSettings());
1415 mSubView.destroy();
1416 mSubView = null;
1417 mSubViewContainer = null;
1418 }
1419 }
1420
1421 /**
1422 * Attach the sub window to the content view.
1423 */
1424 void attachSubWindow(ViewGroup content) {
1425 if (mSubView != null) {
1426 content.addView(mSubViewContainer,
1427 BrowserActivity.COVER_SCREEN_PARAMS);
1428 }
1429 }
1430
1431 /**
1432 * Remove the sub window from the content view.
1433 */
1434 void removeSubWindow(ViewGroup content) {
1435 if (mSubView != null) {
1436 content.removeView(mSubViewContainer);
1437 }
1438 }
1439
1440 /**
1441 * This method attaches both the WebView and any sub window to the
1442 * given content view.
1443 */
1444 void attachTabToContentView(ViewGroup content) {
1445 if (mMainView == null) {
1446 return;
1447 }
1448
1449 // Attach the WebView to the container and then attach the
1450 // container to the content view.
1451 FrameLayout wrapper =
1452 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1453 wrapper.addView(mMainView);
1454 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1455 attachSubWindow(content);
1456 }
1457
1458 /**
1459 * Remove the WebView and any sub window from the given content view.
1460 */
1461 void removeTabFromContentView(ViewGroup content) {
1462 if (mMainView == null) {
1463 return;
1464 }
1465
1466 // Remove the container from the content and then remove the
1467 // WebView from the container. This will trigger a focus change
1468 // needed by WebView.
1469 FrameLayout wrapper =
1470 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1471 wrapper.removeView(mMainView);
1472 content.removeView(mContainer);
1473 removeSubWindow(content);
1474 }
1475
1476 /**
1477 * Set the parent tab of this tab.
1478 */
1479 void setParentTab(Tab parent) {
1480 mParentTab = parent;
1481 // This tab may have been freed due to low memory. If that is the case,
1482 // the parent tab index is already saved. If we are changing that index
1483 // (most likely due to removing the parent tab) we must update the
1484 // parent tab index in the saved Bundle.
1485 if (mSavedState != null) {
1486 if (parent == null) {
1487 mSavedState.remove(PARENTTAB);
1488 } else {
1489 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1490 .getTabIndex(parent));
1491 }
1492 }
1493 }
1494
1495 /**
1496 * When a Tab is created through the content of another Tab, then we
1497 * associate the Tabs.
1498 * @param child the Tab that was created from this Tab
1499 */
1500 void addChildTab(Tab child) {
1501 if (mChildTabs == null) {
1502 mChildTabs = new Vector<Tab>();
1503 }
1504 mChildTabs.add(child);
1505 child.setParentTab(this);
1506 }
1507
1508 Vector<Tab> getChildTabs() {
1509 return mChildTabs;
1510 }
1511
1512 void resume() {
1513 if (mMainView != null) {
1514 mMainView.onResume();
1515 if (mSubView != null) {
1516 mSubView.onResume();
1517 }
1518 }
1519 }
1520
1521 void pause() {
1522 if (mMainView != null) {
1523 mMainView.onPause();
1524 if (mSubView != null) {
1525 mSubView.onPause();
1526 }
1527 }
1528 }
1529
1530 void putInForeground() {
1531 mInForeground = true;
1532 resume();
1533 mMainView.setOnCreateContextMenuListener(mActivity);
1534 if (mSubView != null) {
1535 mSubView.setOnCreateContextMenuListener(mActivity);
1536 }
1537 // Show the pending error dialog if the queue is not empty
1538 if (mQueuedErrors != null && mQueuedErrors.size() > 0) {
1539 showError(mQueuedErrors.getFirst());
1540 }
1541 }
1542
1543 void putInBackground() {
1544 mInForeground = false;
1545 pause();
1546 mMainView.setOnCreateContextMenuListener(null);
1547 if (mSubView != null) {
1548 mSubView.setOnCreateContextMenuListener(null);
1549 }
1550 }
1551
1552 /**
1553 * Return the top window of this tab; either the subwindow if it is not
1554 * null or the main window.
1555 * @return The top window of this tab.
1556 */
1557 WebView getTopWindow() {
1558 if (mSubView != null) {
1559 return mSubView;
1560 }
1561 return mMainView;
1562 }
1563
1564 /**
1565 * Return the main window of this tab. Note: if a tab is freed in the
1566 * background, this can return null. It is only guaranteed to be
1567 * non-null for the current tab.
1568 * @return The main WebView of this tab.
1569 */
1570 WebView getWebView() {
1571 return mMainView;
1572 }
1573
1574 /**
1575 * Return the subwindow of this tab or null if there is no subwindow.
1576 * @return The subwindow of this tab or null.
1577 */
1578 WebView getSubWebView() {
1579 return mSubView;
1580 }
1581
1582 /**
1583 * @return The geolocation permissions prompt for this tab.
1584 */
1585 GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1586 return mGeolocationPermissionsPrompt;
1587 }
1588
1589 /**
1590 * @return The application id string
1591 */
1592 String getAppId() {
1593 return mAppId;
1594 }
1595
1596 /**
1597 * Set the application id string
1598 * @param id
1599 */
1600 void setAppId(String id) {
1601 mAppId = id;
1602 }
1603
1604 /**
1605 * @return The original url associated with this Tab
1606 */
1607 String getOriginalUrl() {
1608 return mOriginalUrl;
1609 }
1610
1611 /**
1612 * Set the original url associated with this tab
1613 */
1614 void setOriginalUrl(String url) {
1615 mOriginalUrl = url;
1616 }
1617
1618 /**
1619 * Get the url of this tab. Valid after calling populatePickerData, but
1620 * before calling wipePickerData, or if the webview has been destroyed.
1621 * @return The WebView's url or null.
1622 */
1623 String getUrl() {
1624 if (mPickerData != null) {
1625 return mPickerData.mUrl;
1626 }
1627 return null;
1628 }
1629
1630 /**
1631 * Get the title of this tab. Valid after calling populatePickerData, but
1632 * before calling wipePickerData, or if the webview has been destroyed. If
1633 * the url has no title, use the url instead.
1634 * @return The WebView's title (or url) or null.
1635 */
1636 String getTitle() {
1637 if (mPickerData != null) {
1638 return mPickerData.mTitle;
1639 }
1640 return null;
1641 }
1642
1643 /**
1644 * Get the favicon of this tab. Valid after calling populatePickerData, but
1645 * before calling wipePickerData, or if the webview has been destroyed.
1646 * @return The WebView's favicon or null.
1647 */
1648 Bitmap getFavicon() {
1649 if (mPickerData != null) {
1650 return mPickerData.mFavicon;
1651 }
1652 return null;
1653 }
1654
1655 /**
1656 * Return the tab's error console. Creates the console if createIfNEcessary
1657 * is true and we haven't already created the console.
1658 * @param createIfNecessary Flag to indicate if the console should be
1659 * created if it has not been already.
1660 * @return The tab's error console, or null if one has not been created and
1661 * createIfNecessary is false.
1662 */
1663 ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1664 if (createIfNecessary && mErrorConsole == null) {
1665 mErrorConsole = new ErrorConsoleView(mActivity);
1666 mErrorConsole.setWebView(mMainView);
1667 }
1668 return mErrorConsole;
1669 }
1670
1671 /**
1672 * If this Tab was created through another Tab, then this method returns
1673 * that Tab.
1674 * @return the Tab parent or null
1675 */
1676 public Tab getParentTab() {
1677 return mParentTab;
1678 }
1679
1680 /**
1681 * Return whether this tab should be closed when it is backing out of the
1682 * first page.
1683 * @return TRUE if this tab should be closed when exit.
1684 */
1685 boolean closeOnExit() {
1686 return mCloseOnExit;
1687 }
1688
1689 /**
1690 * Saves the current lock-icon state before resetting the lock icon. If we
1691 * have an error, we may need to roll back to the previous state.
1692 */
1693 void resetLockIcon(String url) {
1694 mPrevLockIconType = mLockIconType;
1695 mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1696 if (URLUtil.isHttpsUrl(url)) {
1697 mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1698 }
1699 }
1700
1701 /**
1702 * Reverts the lock-icon state to the last saved state, for example, if we
1703 * had an error, and need to cancel the load.
1704 */
1705 void revertLockIcon() {
1706 mLockIconType = mPrevLockIconType;
1707 }
1708
1709 /**
1710 * @return The tab's lock icon type.
1711 */
1712 int getLockIconType() {
1713 return mLockIconType;
1714 }
1715
1716 /**
1717 * @return TRUE if onPageStarted is called while onPageFinished is not
1718 * called yet.
1719 */
1720 boolean inLoad() {
1721 return mInLoad;
1722 }
1723
1724 // force mInLoad to be false. This should only be called before closing the
1725 // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1726 void clearInLoad() {
1727 mInLoad = false;
1728 }
1729
1730 void populatePickerData() {
1731 if (mMainView == null) {
1732 populatePickerDataFromSavedState();
1733 return;
1734 }
1735
1736 // FIXME: The only place we cared about subwindow was for
1737 // bookmarking (i.e. not when saving state). Was this deliberate?
1738 final WebBackForwardList list = mMainView.copyBackForwardList();
1739 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1740 populatePickerData(item);
1741 }
1742
1743 // Populate the picker data using the given history item and the current top
1744 // WebView.
1745 private void populatePickerData(WebHistoryItem item) {
1746 mPickerData = new PickerData();
1747 if (item != null) {
1748 mPickerData.mUrl = item.getUrl();
1749 mPickerData.mTitle = item.getTitle();
1750 mPickerData.mFavicon = item.getFavicon();
1751 if (mPickerData.mTitle == null) {
1752 mPickerData.mTitle = mPickerData.mUrl;
1753 }
1754 }
1755 }
1756
1757 // Create the PickerData and populate it using the saved state of the tab.
1758 void populatePickerDataFromSavedState() {
1759 if (mSavedState == null) {
1760 return;
1761 }
1762 mPickerData = new PickerData();
1763 mPickerData.mUrl = mSavedState.getString(CURRURL);
1764 mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1765 }
1766
1767 void clearPickerData() {
1768 mPickerData = null;
1769 }
1770
1771 /**
1772 * Get the saved state bundle.
1773 * @return
1774 */
1775 Bundle getSavedState() {
1776 return mSavedState;
1777 }
1778
1779 /**
1780 * Set the saved state.
1781 */
1782 void setSavedState(Bundle state) {
1783 mSavedState = state;
1784 }
1785
1786 /**
1787 * @return TRUE if succeed in saving the state.
1788 */
1789 boolean saveState() {
1790 // If the WebView is null it means we ran low on memory and we already
1791 // stored the saved state in mSavedState.
1792 if (mMainView == null) {
1793 return mSavedState != null;
1794 }
1795
1796 mSavedState = new Bundle();
1797 final WebBackForwardList list = mMainView.saveState(mSavedState);
1798 if (list != null) {
1799 final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1800 mMainView.hashCode() + "_pic.save");
1801 if (mMainView.savePicture(mSavedState, f)) {
1802 mSavedState.putString(CURRPICTURE, f.getPath());
1803 }
1804 }
1805
1806 // Store some extra info for displaying the tab in the picker.
1807 final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1808 populatePickerData(item);
1809
1810 if (mPickerData.mUrl != null) {
1811 mSavedState.putString(CURRURL, mPickerData.mUrl);
1812 }
1813 if (mPickerData.mTitle != null) {
1814 mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1815 }
1816 mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1817 if (mAppId != null) {
1818 mSavedState.putString(APPID, mAppId);
1819 }
1820 if (mOriginalUrl != null) {
1821 mSavedState.putString(ORIGINALURL, mOriginalUrl);
1822 }
1823 // Remember the parent tab so the relationship can be restored.
1824 if (mParentTab != null) {
1825 mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1826 mParentTab));
1827 }
1828 return true;
1829 }
1830
1831 /*
1832 * Restore the state of the tab.
1833 */
1834 boolean restoreState(Bundle b) {
1835 if (b == null) {
1836 return false;
1837 }
1838 // Restore the internal state even if the WebView fails to restore.
1839 // This will maintain the app id, original url and close-on-exit values.
1840 mSavedState = null;
1841 mPickerData = null;
1842 mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1843 mAppId = b.getString(APPID);
1844 mOriginalUrl = b.getString(ORIGINALURL);
1845
1846 final WebBackForwardList list = mMainView.restoreState(b);
1847 if (list == null) {
1848 return false;
1849 }
1850 if (b.containsKey(CURRPICTURE)) {
1851 final File f = new File(b.getString(CURRPICTURE));
1852 mMainView.restorePicture(b, f);
1853 f.delete();
1854 }
1855 return true;
1856 }
1857}