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