2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
19 import android.content.Context;
20 import android.graphics.Bitmap;
21 import android.graphics.Picture;
22 import android.net.http.SslError;
23 import android.os.Bundle;
24 import android.os.Message;
25 import android.util.Log;
26 import android.view.Gravity;
27 import android.view.LayoutInflater;
28 import android.view.View;
29 import android.view.ViewGroup;
30 import android.view.View.OnClickListener;
31 import android.webkit.HttpAuthHandler;
32 import android.webkit.JsPromptResult;
33 import android.webkit.JsResult;
34 import android.webkit.SslErrorHandler;
35 import android.webkit.WebBackForwardList;
36 import android.webkit.WebChromeClient;
37 import android.webkit.WebHistoryItem;
38 import android.webkit.WebView;
39 import android.webkit.WebViewClient;
40 import android.widget.FrameLayout;
41 import android.widget.ImageButton;
42 import android.widget.LinearLayout;
45 import java.io.FileInputStream;
46 import java.util.ArrayList;
47 import java.util.Vector;
51 private static final String LOGTAG = "TabControl";
52 // Maximum number of tabs.
53 static final int MAX_TABS = 8;
54 // Static instance of an empty callback.
55 private static final WebViewClient mEmptyClient =
57 // Instance of BackgroundChromeClient for background tabs.
58 private final BackgroundChromeClient mBackgroundChromeClient =
59 new BackgroundChromeClient();
60 // Private array of WebViews that are used as tabs.
61 private ArrayList<Tab> mTabs = new ArrayList<Tab>(MAX_TABS);
62 // Queue of most recently viewed tabs.
63 private ArrayList<Tab> mTabQueue = new ArrayList<Tab>(MAX_TABS);
64 // Current position in mTabs.
65 private int mCurrentTab = -1;
66 // A private instance of BrowserActivity to interface with when adding and
67 // switching between tabs.
68 private final BrowserActivity mActivity;
69 // Inflation service for making subwindows.
70 private final LayoutInflater mInflateService;
71 // Subclass of WebViewClient used in subwindows to notify the main
72 // WebViewClient of certain WebView activities.
73 private static class SubWindowClient extends WebViewClient {
74 // The main WebViewClient.
75 private final WebViewClient mClient;
77 SubWindowClient(WebViewClient client) {
81 public void doUpdateVisitedHistory(WebView view, String url,
83 mClient.doUpdateVisitedHistory(view, url, isReload);
86 public boolean shouldOverrideUrlLoading(WebView view, String url) {
87 return mClient.shouldOverrideUrlLoading(view, url);
90 public void onReceivedSslError(WebView view, SslErrorHandler handler,
92 mClient.onReceivedSslError(view, handler, error);
95 public void onReceivedHttpAuthRequest(WebView view,
96 HttpAuthHandler handler, String host, String realm) {
97 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
100 public void onFormResubmission(WebView view, Message dontResend,
102 mClient.onFormResubmission(view, dontResend, resend);
105 public void onReceivedError(WebView view, int errorCode,
106 String description, String failingUrl) {
107 mClient.onReceivedError(view, errorCode, description, failingUrl);
110 public boolean shouldOverrideKeyEvent(WebView view,
111 android.view.KeyEvent event) {
112 return mClient.shouldOverrideKeyEvent(view, event);
115 public void onUnhandledKeyEvent(WebView view,
116 android.view.KeyEvent event) {
117 mClient.onUnhandledKeyEvent(view, event);
120 // Subclass of WebChromeClient to display javascript dialogs.
121 private class SubWindowChromeClient extends WebChromeClient {
122 // This subwindow's tab.
123 private final Tab mTab;
124 // The main WebChromeClient.
125 private final WebChromeClient mClient;
127 SubWindowChromeClient(Tab t, WebChromeClient client) {
132 public void onProgressChanged(WebView view, int newProgress) {
133 mClient.onProgressChanged(view, newProgress);
136 public boolean onCreateWindow(WebView view, boolean dialog,
137 boolean userGesture, android.os.Message resultMsg) {
138 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
141 public void onCloseWindow(WebView window) {
142 if (Browser.DEBUG && window != mTab.mSubView) {
143 throw new AssertionError("Can't close the window");
145 mActivity.dismissSubWindow(mTab);
148 // Background WebChromeClient for focusing tabs
149 private class BackgroundChromeClient extends WebChromeClient {
151 public void onRequestFocus(WebView view) {
152 Tab t = getTabFromView(view);
153 if (t != getCurrentTab()) {
154 mActivity.switchToTab(getTabIndex(t));
159 // Extra saved information for displaying the tab in the picker.
160 public static class PickerData {
170 * Private class for maintaining Tabs with a main WebView and a subwindow.
173 // The Geolocation permissions prompt
174 private GeolocationPermissionsPrompt mGeolocationPermissionsPrompt;
175 private View mContainer;
177 private WebView mMainView;
179 private WebView mSubView;
180 // Subwindow container
181 private View mSubViewContainer;
182 // Subwindow callback
183 private SubWindowClient mSubViewClient;
184 // Subwindow chrome callback
185 private SubWindowChromeClient mSubViewChromeClient;
186 // Saved bundle for when we are running low on memory. It contains the
187 // information needed to restore the WebView if the user goes back to
189 private Bundle mSavedState;
190 // Data used when displaying the tab in the picker.
191 private PickerData mPickerData;
193 // Parent Tab. This is the Tab that created this Tab, or null
194 // if the Tab was created by the UI
195 private Tab mParentTab;
196 // Tab that constructed by this Tab. This is used when this
197 // Tab is destroyed, it clears all mParentTab values in the
199 private Vector<Tab> mChildTabs;
201 private Boolean mCloseOnExit;
202 // Application identifier used to find tabs that another application
204 private String mAppId;
205 // Keep the original url around to avoid killing the old WebView if the
206 // url has not changed.
207 private String mOriginalUrl;
209 private ErrorConsoleView mErrorConsole;
210 // the lock icon type and previous lock icon type for the tab
211 private int mSavedLockIconType;
212 private int mSavedPrevLockIconType;
214 // Construct a new tab
215 private Tab(WebView w, boolean closeOnExit, String appId, String url, Context context) {
216 mCloseOnExit = closeOnExit;
219 mSavedLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
220 mSavedPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
222 // The tab consists of a container view, which contains the main
223 // WebView, as well as any other UI elements associated with the tab.
224 LayoutInflater factory = LayoutInflater.from(context);
225 mContainer = factory.inflate(R.layout.tab, null);
227 mGeolocationPermissionsPrompt =
228 (GeolocationPermissionsPrompt) mContainer.findViewById(
229 R.id.geolocation_permissions_prompt);
235 * Sets the WebView for this tab, correctly removing the old WebView
236 * from the container view.
238 public void setWebView(WebView w) {
239 if (mMainView == w) {
242 // If the WebView is changing, the page will be reloaded, so any ongoing Geolocation
243 // permission requests are void.
244 mGeolocationPermissionsPrompt.hide();
246 // Just remove the old one.
247 FrameLayout wrapper =
248 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
249 wrapper.removeView(mMainView);
254 * This method attaches both the WebView and any sub window to the
255 * given content view.
257 public void attachTabToContentView(ViewGroup content) {
258 if (mMainView == null) {
262 // Attach the WebView to the container and then attach the
263 // container to the content view.
264 FrameLayout wrapper =
265 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
266 wrapper.addView(mMainView);
267 content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
268 attachSubWindow(content);
272 * Remove the WebView and any sub window from the given content view.
274 public void removeTabFromContentView(ViewGroup content) {
275 if (mMainView == null) {
279 // Remove the container from the content and then remove the
280 // WebView from the container. This will trigger a focus change
281 // needed by WebView.
282 FrameLayout wrapper =
283 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
284 wrapper.removeView(mMainView);
285 content.removeView(mContainer);
286 removeSubWindow(content);
290 * Attach the sub window to the content view.
292 public void attachSubWindow(ViewGroup content) {
293 if (mSubView != null) {
294 content.addView(mSubViewContainer,
295 BrowserActivity.COVER_SCREEN_PARAMS);
300 * Remove the sub window from the content view.
302 public void removeSubWindow(ViewGroup content) {
303 if (mSubView != null) {
304 content.removeView(mSubViewContainer);
309 * Return the top window of this tab; either the subwindow if it is not
310 * null or the main window.
311 * @return The top window of this tab.
313 public WebView getTopWindow() {
314 if (mSubView != null) {
321 * Return the main window of this tab. Note: if a tab is freed in the
322 * background, this can return null. It is only guaranteed to be
323 * non-null for the current tab.
324 * @return The main WebView of this tab.
326 public WebView getWebView() {
331 * @return The geolocation permissions prompt for this tab.
333 public GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
334 return mGeolocationPermissionsPrompt;
338 * Return the subwindow of this tab or null if there is no subwindow.
339 * @return The subwindow of this tab or null.
341 public WebView getSubWebView() {
346 * Get the url of this tab. Valid after calling populatePickerData, but
347 * before calling wipePickerData, or if the webview has been destroyed.
349 * @return The WebView's url or null.
351 public String getUrl() {
352 if (mPickerData != null) {
353 return mPickerData.mUrl;
359 * Get the title of this tab. Valid after calling populatePickerData,
360 * but before calling wipePickerData, or if the webview has been
361 * destroyed. If the url has no title, use the url instead.
363 * @return The WebView's title (or url) or null.
365 public String getTitle() {
366 if (mPickerData != null) {
367 return mPickerData.mTitle;
372 public Bitmap getFavicon() {
373 if (mPickerData != null) {
374 return mPickerData.mFavicon;
379 private void setParentTab(Tab parent) {
381 // This tab may have been freed due to low memory. If that is the
382 // case, the parent tab index is already saved. If we are changing
383 // that index (most likely due to removing the parent tab) we must
384 // update the parent tab index in the saved Bundle.
385 if (mSavedState != null) {
386 if (parent == null) {
387 mSavedState.remove(PARENTTAB);
389 mSavedState.putInt(PARENTTAB, getTabIndex(parent));
395 * When a Tab is created through the content of another Tab, then
396 * we associate the Tabs.
397 * @param child the Tab that was created from this Tab
399 public void addChildTab(Tab child) {
400 if (mChildTabs == null) {
401 mChildTabs = new Vector<Tab>();
403 mChildTabs.add(child);
404 child.setParentTab(this);
407 private void removeFromTree() {
408 // detach the children
409 if (mChildTabs != null) {
410 for(Tab t : mChildTabs) {
411 t.setParentTab(null);
415 // Find myself in my parent list
416 if (mParentTab != null) {
417 mParentTab.mChildTabs.remove(this);
422 * If this Tab was created through another Tab, then this method
424 * @return the Tab parent or null
426 public Tab getParentTab() {
431 * Return whether this tab should be closed when it is backing out of
433 * @return TRUE if this tab should be closed when exit.
435 public boolean closeOnExit() {
439 void setLockIconType(int type) {
440 mSavedLockIconType = type;
443 int getLockIconType() {
444 return mSavedLockIconType;
447 void setPrevLockIconType(int type) {
448 mSavedPrevLockIconType = type;
451 int getPrevLockIconType() {
452 return mSavedPrevLockIconType;
456 // Directory to store thumbnails for each WebView.
457 private final File mThumbnailDir;
460 * Construct a new TabControl object that interfaces with the given
461 * BrowserActivity instance.
462 * @param activity A BrowserActivity instance that TabControl will interface
465 TabControl(BrowserActivity activity) {
466 mActivity = activity;
468 ((LayoutInflater) activity.getSystemService(
469 Context.LAYOUT_INFLATER_SERVICE));
470 mThumbnailDir = activity.getDir("thumbnails", 0);
473 File getThumbnailDir() {
474 return mThumbnailDir;
477 BrowserActivity getBrowserActivity() {
482 * Return the current tab's main WebView. This will always return the main
483 * WebView for a given tab and not a subwindow.
484 * @return The current tab's WebView.
486 WebView getCurrentWebView() {
487 Tab t = getTab(mCurrentTab);
495 * Return the current tab's error console. Creates the console if createIfNEcessary
496 * is true and we haven't already created the console.
497 * @param createIfNecessary Flag to indicate if the console should be created if it has
499 * @return The current tab's error console, or null if one has not been created and
500 * createIfNecessary is false.
502 ErrorConsoleView getCurrentErrorConsole(boolean createIfNecessary) {
503 Tab t = getTab(mCurrentTab);
508 if (createIfNecessary && t.mErrorConsole == null) {
509 t.mErrorConsole = new ErrorConsoleView(mActivity);
510 t.mErrorConsole.setWebView(t.mMainView);
513 return t.mErrorConsole;
517 * Return the current tab's top-level WebView. This can return a subwindow
519 * @return The top-level WebView of the current tab.
521 WebView getCurrentTopWebView() {
522 Tab t = getTab(mCurrentTab);
526 return t.mSubView != null ? t.mSubView : t.mMainView;
530 * Return the current tab's subwindow if it exists.
531 * @return The subwindow of the current tab or null if it doesn't exist.
533 WebView getCurrentSubWindow() {
534 Tab t = getTab(mCurrentTab);
542 * Return the tab at the specified index.
543 * @return The Tab for the specified index or null if the tab does not
546 Tab getTab(int index) {
547 if (index >= 0 && index < mTabs.size()) {
548 return mTabs.get(index);
554 * Return the current tab.
555 * @return The current tab.
557 Tab getCurrentTab() {
558 return getTab(mCurrentTab);
562 * Return the current tab index.
563 * @return The current tab index
565 int getCurrentIndex() {
570 * Given a Tab, find it's index
572 * @return index of Tab or -1 if not found
574 int getTabIndex(Tab tab) {
578 return mTabs.indexOf(tab);
583 * @return The newly createTab or null if we have reached the maximum
584 * number of open tabs.
586 Tab createNewTab(boolean closeOnExit, String appId, String url) {
587 int size = mTabs.size();
588 // Return false if we have maxed out on tabs
589 if (MAX_TABS == size) {
592 final WebView w = createNewWebView();
594 // Create a new tab and add it to the tab list
595 Tab t = new Tab(w, closeOnExit, appId, url, mActivity);
597 // Initially put the tab in the background.
598 putTabInBackground(t);
603 * Create a new tab with default values for closeOnExit(false),
604 * appId(null), and url(null).
607 return createNewTab(false, null, null);
611 * Remove the tab from the list. If the tab is the current tab shown, the
612 * last created tab will be shown.
613 * @param t The tab to be removed.
615 boolean removeTab(Tab t) {
619 // Only remove the tab if it is the current one.
620 if (getCurrentTab() == t) {
621 putTabInBackground(t);
624 // Only destroy the WebView if it still exists.
625 if (t.mMainView != null) {
626 // Take down the sub window.
628 // Remove the WebView's settings from the BrowserSettings list of
630 BrowserSettings.getInstance().deleteObserver(
631 t.mMainView.getSettings());
632 WebView w = t.mMainView;
634 // Destroy the main view
637 // clear it's references to parent and children
640 // Remove it from our list of tabs.
643 // The tab indices have shifted, update all the saved state so we point
644 // to the correct index.
645 for (Tab tab : mTabs) {
646 if (tab.mChildTabs != null) {
647 for (Tab child : tab.mChildTabs) {
648 child.setParentTab(tab);
654 // This tab may have been pushed in to the background and then closed.
655 // If the saved state contains a picture file, delete the file.
656 if (t.mSavedState != null) {
657 if (t.mSavedState.containsKey(CURRPICTURE)) {
658 new File(t.mSavedState.getString(CURRPICTURE)).delete();
662 // Remove it from the queue of viewed tabs.
669 * Clear the back/forward list for all the current tabs.
671 void clearHistory() {
672 int size = getTabCount();
673 for (int i = 0; i < size; i++) {
674 Tab t = mTabs.get(i);
675 // TODO: if a tab is freed due to low memory, its history is not
677 if (t.mMainView != null) {
678 t.mMainView.clearHistory();
680 if (t.mSubView != null) {
681 t.mSubView.clearHistory();
687 * Destroy all the tabs and subwindows
690 BrowserSettings s = BrowserSettings.getInstance();
691 for (Tab t : mTabs) {
692 if (t.mMainView != null) {
694 s.deleteObserver(t.mMainView.getSettings());
695 WebView w = t.mMainView;
705 * Returns the number of tabs created.
706 * @return The number of tabs created.
712 // Used for saving and restoring each Tab
713 private static final String WEBVIEW = "webview";
714 private static final String NUMTABS = "numTabs";
715 private static final String CURRTAB = "currentTab";
716 private static final String CURRURL = "currentUrl";
717 private static final String CURRTITLE = "currentTitle";
718 private static final String CURRPICTURE = "currentPicture";
719 private static final String CLOSEONEXIT = "closeonexit";
720 private static final String PARENTTAB = "parentTab";
721 private static final String APPID = "appid";
722 private static final String ORIGINALURL = "originalUrl";
725 * Save the state of all the Tabs.
726 * @param outState The Bundle to save the state to.
728 void saveState(Bundle outState) {
729 final int numTabs = getTabCount();
730 outState.putInt(NUMTABS, numTabs);
731 final int index = getCurrentIndex();
732 outState.putInt(CURRTAB, (index >= 0 && index < numTabs) ? index : 0);
733 for (int i = 0; i < numTabs; i++) {
734 final Tab t = getTab(i);
736 outState.putBundle(WEBVIEW + i, t.mSavedState);
742 * Restore the state of all the tabs.
743 * @param inState The saved state of all the tabs.
744 * @return True if there were previous tabs that were restored. False if
745 * there was no saved state or restoring the state failed.
747 boolean restoreState(Bundle inState) {
748 final int numTabs = (inState == null)
749 ? -1 : inState.getInt(NUMTABS, -1);
753 final int currentTab = inState.getInt(CURRTAB, -1);
754 for (int i = 0; i < numTabs; i++) {
755 if (i == currentTab) {
756 Tab t = createNewTab();
757 // Me must set the current tab before restoring the state
758 // so that all the client classes are set.
760 if (!restoreState(inState.getBundle(WEBVIEW + i), t)) {
761 Log.w(LOGTAG, "Fail in restoreState, load home page.");
762 t.mMainView.loadUrl(BrowserSettings.getInstance()
766 // Create a new tab and don't restore the state yet, add it
768 Tab t = new Tab(null, false, null, null, mActivity);
769 t.mSavedState = inState.getBundle(WEBVIEW + i);
770 if (t.mSavedState != null) {
771 populatePickerDataFromSavedState(t);
772 // Need to maintain the app id and original url so we
773 // can possibly reuse this tab.
774 t.mAppId = t.mSavedState.getString(APPID);
775 t.mOriginalUrl = t.mSavedState.getString(ORIGINALURL);
781 // Rebuild the tree of tabs. Do this after all tabs have been
782 // created/restored so that the parent tab exists.
783 for (int i = 0; i < numTabs; i++) {
784 final Bundle b = inState.getBundle(WEBVIEW + i);
785 final Tab t = getTab(i);
786 if (b != null && t != null) {
787 final int parentIndex = b.getInt(PARENTTAB, -1);
788 if (parentIndex != -1) {
789 final Tab parent = getTab(parentIndex);
790 if (parent != null) {
791 parent.addChildTab(t);
801 * Free the memory in this order, 1) free the background tab; 2) free the
805 if (getTabCount() == 0) return;
807 // free the least frequently used background tab
808 Tab t = getLeastUsedTab(getCurrentTab());
810 Log.w(LOGTAG, "Free a tab in the browser");
817 // free the WebView's unused memory (this includes the cache)
818 Log.w(LOGTAG, "Free WebView's unused memory and cache");
819 WebView view = getCurrentWebView();
827 private Tab getLeastUsedTab(Tab current) {
828 // Don't do anything if we only have 1 tab or if the current tab is
830 if (getTabCount() == 1 || current == null) {
834 // Rip through the queue starting at the beginning and teardown the
835 // next available tab.
838 final int queueSize = mTabQueue.size();
839 if (queueSize == 0) {
843 t = mTabQueue.get(i++);
844 } while (i < queueSize
845 && ((t != null && t.mMainView == null)
846 || t == current.mParentTab));
848 // Don't do anything if the last remaining tab is the current one or if
849 // the last tab has been freed already.
850 if (t == current || t.mMainView == null) {
857 private void freeTab(Tab t) {
858 // Store the WebView's state.
861 // Tear down the tab.
863 // Remove the WebView's settings from the BrowserSettings list of
865 BrowserSettings.getInstance().deleteObserver(t.mMainView.getSettings());
866 WebView w = t.mMainView;
872 * Create a new subwindow unless a subwindow already exists.
873 * @return True if a new subwindow was created. False if one already exists.
875 void createSubWindow() {
876 Tab t = getTab(mCurrentTab);
877 if (t != null && t.mSubView == null) {
878 final View v = mInflateService.inflate(R.layout.browser_subwindow, null);
879 final WebView w = (WebView) v.findViewById(R.id.webview);
880 w.setMapTrackballToArrowKeys(false); // use trackball directly
881 final SubWindowClient subClient =
882 new SubWindowClient(mActivity.getWebViewClient());
883 final SubWindowChromeClient subChromeClient =
884 new SubWindowChromeClient(t,
885 mActivity.getWebChromeClient());
886 w.setWebViewClient(subClient);
887 w.setWebChromeClient(subChromeClient);
888 w.setDownloadListener(mActivity);
889 w.setOnCreateContextMenuListener(mActivity);
890 final BrowserSettings s = BrowserSettings.getInstance();
891 s.addObserver(w.getSettings()).update(s, null);
893 t.mSubViewClient = subClient;
894 t.mSubViewChromeClient = subChromeClient;
895 // FIXME: I really hate having to know the name of the view
896 // containing the webview.
897 t.mSubViewContainer = v.findViewById(R.id.subwindow_container);
898 final ImageButton cancel =
899 (ImageButton) v.findViewById(R.id.subwindow_close);
900 cancel.setOnClickListener(new OnClickListener() {
901 public void onClick(View v) {
902 subChromeClient.onCloseWindow(w);
909 * Show the tab that contains the given WebView.
910 * @param view The WebView used to find the tab.
912 Tab getTabFromView(WebView view) {
913 final int size = getTabCount();
914 for (int i = 0; i < size; i++) {
915 final Tab t = getTab(i);
916 if (t.mSubView == view || t.mMainView == view) {
924 * Return the tab with the matching application id.
925 * @param id The application identifier.
927 Tab getTabFromId(String id) {
931 final int size = getTabCount();
932 for (int i = 0; i < size; i++) {
933 final Tab t = getTab(i);
934 if (id.equals(t.mAppId)) {
941 void stopAllLoading() {
942 final int size = getTabCount();
943 for (int i = 0; i < size; i++) {
944 final WebView webview = getTab(i).getTopWindow();
945 if (webview != null) {
946 webview.stopLoading();
951 // This method checks if a non-app tab (one created within the browser)
952 // matches the given url.
953 private boolean tabMatchesUrl(Tab t, String url) {
954 if (t.mAppId != null) {
956 } else if (t.mMainView == null) {
958 } else if (url.equals(t.mMainView.getUrl()) ||
959 url.equals(t.mMainView.getOriginalUrl())) {
966 * Return the tab that has no app id associated with it and the url of the
967 * tab matches the given url.
968 * @param url The url to search for.
970 Tab findUnusedTabWithUrl(String url) {
974 // Check the current tab first.
975 Tab t = getCurrentTab();
976 if (t != null && tabMatchesUrl(t, url)) {
979 // Now check all the rest.
980 final int size = getTabCount();
981 for (int i = 0; i < size; i++) {
983 if (tabMatchesUrl(t, url)) {
991 * Recreate the main WebView of the given tab. Returns true if the WebView
994 boolean recreateWebView(Tab t, String url) {
995 final WebView w = t.mMainView;
997 if (url != null && url.equals(t.mOriginalUrl)) {
998 // The original url matches the current url. Just go back to the
999 // first history item so we can load it faster than if we
1000 // rebuilt the WebView.
1001 final WebBackForwardList list = w.copyBackForwardList();
1003 w.goBackOrForward(-list.getCurrentIndex());
1004 w.clearHistory(); // maintains the current page.
1008 // Remove the settings object from the global settings and destroy
1010 BrowserSettings.getInstance().deleteObserver(
1011 t.mMainView.getSettings());
1012 t.mMainView.destroy();
1014 // Create a new WebView. If this tab is the current tab, we need to put
1015 // back all the clients so force it to be the current tab.
1016 t.setWebView(createNewWebView());
1017 if (getCurrentTab() == t) {
1018 setCurrentTab(t, true);
1020 // Clear the saved state except for the app id and close-on-exit
1022 t.mSavedState = null;
1023 t.mPickerData = null;
1024 // Save the new url in order to avoid deleting the WebView.
1025 t.mOriginalUrl = url;
1030 * Creates a new WebView and registers it with the global settings.
1032 private WebView createNewWebView() {
1033 // Create a new WebView
1034 WebView w = new WebView(mActivity);
1035 w.setScrollbarFadingEnabled(true);
1036 w.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
1037 w.setMapTrackballToArrowKeys(false); // use trackball directly
1038 // Enable the built-in zoom
1039 w.getSettings().setBuiltInZoomControls(true);
1040 // Add this WebView to the settings observer list and update the
1042 final BrowserSettings s = BrowserSettings.getInstance();
1043 s.addObserver(w.getSettings()).update(s, null);
1048 * Put the current tab in the background and set newTab as the current tab.
1049 * @param newTab The new tab. If newTab is null, the current tab is not
1052 boolean setCurrentTab(Tab newTab) {
1053 return setCurrentTab(newTab, false);
1056 /*package*/ void pauseCurrentTab() {
1057 Tab t = getCurrentTab();
1059 t.mMainView.onPause();
1060 if (t.mSubView != null) {
1061 t.mSubView.onPause();
1066 /*package*/ void resumeCurrentTab() {
1067 Tab t = getCurrentTab();
1069 t.mMainView.onResume();
1070 if (t.mSubView != null) {
1071 t.mSubView.onResume();
1076 private void putViewInForeground(WebView v, WebViewClient vc,
1077 WebChromeClient cc) {
1078 v.setWebViewClient(vc);
1079 v.setWebChromeClient(cc);
1080 v.setOnCreateContextMenuListener(mActivity);
1081 v.setDownloadListener(mActivity);
1085 private void putViewInBackground(WebView v) {
1086 // Set an empty callback so that default actions are not triggered.
1087 v.setWebViewClient(mEmptyClient);
1088 v.setWebChromeClient(mBackgroundChromeClient);
1089 v.setOnCreateContextMenuListener(null);
1090 // Leave the DownloadManager attached so that downloads can start in
1091 // a non-active window. This can happen when going to a site that does
1092 // a redirect after a period of time. The user could have switched to
1093 // another tab while waiting for the download to start.
1094 v.setDownloadListener(mActivity);
1099 * If force is true, this method skips the check for newTab == current.
1101 private boolean setCurrentTab(Tab newTab, boolean force) {
1102 Tab current = getTab(mCurrentTab);
1103 if (current == newTab && !force) {
1106 if (current != null) {
1107 // Remove the current WebView and the container of the subwindow
1108 putTabInBackground(current);
1111 if (newTab == null) {
1115 // Move the newTab to the end of the queue
1116 int index = mTabQueue.indexOf(newTab);
1118 mTabQueue.remove(index);
1120 mTabQueue.add(newTab);
1124 // Display the new current tab
1125 mCurrentTab = mTabs.indexOf(newTab);
1126 mainView = newTab.mMainView;
1127 boolean needRestore = (mainView == null);
1129 // Same work as in createNewTab() except don't do new Tab()
1130 mainView = createNewWebView();
1131 newTab.setWebView(mainView);
1133 putViewInForeground(mainView, mActivity.getWebViewClient(),
1134 mActivity.getWebChromeClient());
1135 // Add the subwindow if it exists
1136 if (newTab.mSubViewContainer != null) {
1137 putViewInForeground(newTab.mSubView, newTab.mSubViewClient,
1138 newTab.mSubViewChromeClient);
1141 // Have to finish setCurrentTab work before calling restoreState
1142 if (!restoreState(newTab.mSavedState, newTab)) {
1143 mainView.loadUrl(BrowserSettings.getInstance().getHomePage());
1150 * Put the tab in the background using all the empty/background clients.
1152 private void putTabInBackground(Tab t) {
1153 putViewInBackground(t.mMainView);
1154 if (t.mSubView != null) {
1155 putViewInBackground(t.mSubView);
1160 * Dismiss the subwindow for the given tab.
1162 void dismissSubWindow(Tab t) {
1163 if (t != null && t.mSubView != null) {
1164 BrowserSettings.getInstance().deleteObserver(
1165 t.mSubView.getSettings());
1166 t.mSubView.destroy();
1168 t.mSubViewContainer = null;
1173 * Ensure that Tab t has data to display in the tab picker.
1174 * @param t Tab to populate.
1176 /* package */ void populatePickerData(Tab t) {
1181 // mMainView == null indicates that the tab has been freed.
1182 if (t.mMainView == null) {
1183 populatePickerDataFromSavedState(t);
1187 // FIXME: The only place we cared about subwindow was for
1188 // bookmarking (i.e. not when saving state). Was this deliberate?
1189 final WebBackForwardList list = t.mMainView.copyBackForwardList();
1190 final WebHistoryItem item =
1191 list != null ? list.getCurrentItem() : null;
1192 populatePickerData(t, item);
1195 // Create the PickerData and populate it using the saved state of the tab.
1196 private void populatePickerDataFromSavedState(Tab t) {
1197 if (t.mSavedState == null) {
1201 final PickerData data = new PickerData();
1202 final Bundle state = t.mSavedState;
1203 data.mUrl = state.getString(CURRURL);
1204 data.mTitle = state.getString(CURRTITLE);
1205 // XXX: These keys are from WebView.savePicture so if they change, this
1207 data.mScale = state.getFloat("scale", 1.0f);
1208 data.mScrollX = state.getInt("scrollX", 0);
1209 data.mScrollY = state.getInt("scrollY", 0);
1211 // Set the tab's picker data.
1212 t.mPickerData = data;
1215 // Populate the picker data using the given history item and the current
1217 private void populatePickerData(Tab t, WebHistoryItem item) {
1218 final PickerData data = new PickerData();
1220 data.mUrl = item.getUrl();
1221 data.mTitle = item.getTitle();
1222 data.mFavicon = item.getFavicon();
1223 if (data.mTitle == null) {
1224 data.mTitle = data.mUrl;
1227 // We want to display the top window in the tab picker but use the url
1228 // and title of the main window.
1229 final WebView w = t.getTopWindow();
1230 data.mScale = w.getScale();
1231 data.mScrollX = w.getScrollX();
1232 data.mScrollY = w.getScrollY();
1234 t.mPickerData = data;
1238 * Clean up the data for all tabs.
1240 /* package */ void wipeAllPickerData() {
1241 int size = getTabCount();
1242 for (int i = 0; i < size; i++) {
1243 final Tab t = getTab(i);
1244 if (t != null && t.mSavedState == null) {
1245 t.mPickerData = null;
1251 * Save the state for an individual tab.
1253 private boolean saveState(Tab t) {
1255 final WebView w = t.mMainView;
1256 // If the WebView is null it means we ran low on memory and we
1257 // already stored the saved state in mSavedState.
1261 final Bundle b = new Bundle();
1262 final WebBackForwardList list = w.saveState(b);
1264 final File f = new File(mThumbnailDir, w.hashCode()
1266 if (w.savePicture(b, f)) {
1267 b.putString(CURRPICTURE, f.getPath());
1271 // Store some extra info for displaying the tab in the picker.
1272 final WebHistoryItem item =
1273 list != null ? list.getCurrentItem() : null;
1274 populatePickerData(t, item);
1276 // XXX: WebView.savePicture stores the scale and scroll positions
1277 // in the bundle so we don't have to do it here.
1278 final PickerData data = t.mPickerData;
1279 if (data.mUrl != null) {
1280 b.putString(CURRURL, data.mUrl);
1282 if (data.mTitle != null) {
1283 b.putString(CURRTITLE, data.mTitle);
1285 b.putBoolean(CLOSEONEXIT, t.mCloseOnExit);
1286 if (t.mAppId != null) {
1287 b.putString(APPID, t.mAppId);
1289 if (t.mOriginalUrl != null) {
1290 b.putString(ORIGINALURL, t.mOriginalUrl);
1293 // Remember the parent tab so the relationship can be restored.
1294 if (t.mParentTab != null) {
1295 b.putInt(PARENTTAB, getTabIndex(t.mParentTab));
1298 // Remember the saved state.
1306 * Restore the state of the tab.
1308 private boolean restoreState(Bundle b, Tab t) {
1312 // Restore the internal state even if the WebView fails to restore.
1313 // This will maintain the app id, original url and close-on-exit values.
1314 t.mSavedState = null;
1315 t.mPickerData = null;
1316 t.mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1317 t.mAppId = b.getString(APPID);
1318 t.mOriginalUrl = b.getString(ORIGINALURL);
1320 final WebView w = t.mMainView;
1321 final WebBackForwardList list = w.restoreState(b);
1325 if (b.containsKey(CURRPICTURE)) {
1326 final File f = new File(b.getString(CURRPICTURE));
1327 w.restorePicture(b, f);