blob: 581d144e86ffae885653c5356c4eefc1c883cccd [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2007 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 android.content.Context;
Patrick Scott2ed6edb2009-04-22 10:07:45 -040020import android.graphics.Picture;
The Android Open Source Project0c908882009-03-03 19:32:16 -080021import android.net.http.SslError;
22import android.os.Bundle;
23import android.os.Message;
The Android Open Source Project0c908882009-03-03 19:32:16 -080024import android.util.Log;
25import android.view.Gravity;
26import android.view.LayoutInflater;
27import android.view.View;
28import android.view.ViewGroup;
29import android.view.View.OnClickListener;
30import android.webkit.HttpAuthHandler;
31import android.webkit.JsPromptResult;
32import android.webkit.JsResult;
33import android.webkit.SslErrorHandler;
34import android.webkit.WebBackForwardList;
35import android.webkit.WebChromeClient;
36import android.webkit.WebHistoryItem;
37import android.webkit.WebView;
38import android.webkit.WebViewClient;
39import android.widget.FrameLayout;
40import android.widget.ImageButton;
41
42import java.io.File;
Patrick Scott2ed6edb2009-04-22 10:07:45 -040043import java.io.FileInputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import java.util.ArrayList;
45import java.util.Vector;
46
47class TabControl {
48 // Log Tag
49 private static final String LOGTAG = "TabControl";
50 // Maximum number of tabs.
51 static final int MAX_TABS = 8;
52 // Static instance of an empty callback.
53 private static final WebViewClient mEmptyClient =
54 new WebViewClient();
55 // Instance of BackgroundChromeClient for background tabs.
56 private final BackgroundChromeClient mBackgroundChromeClient =
57 new BackgroundChromeClient();
58 // Private array of WebViews that are used as tabs.
59 private ArrayList<Tab> mTabs = new ArrayList<Tab>(MAX_TABS);
60 // Queue of most recently viewed tabs.
61 private ArrayList<Tab> mTabQueue = new ArrayList<Tab>(MAX_TABS);
62 // Current position in mTabs.
63 private int mCurrentTab = -1;
64 // A private instance of BrowserActivity to interface with when adding and
65 // switching between tabs.
66 private final BrowserActivity mActivity;
67 // Inflation service for making subwindows.
68 private final LayoutInflater mInflateService;
69 // Subclass of WebViewClient used in subwindows to notify the main
70 // WebViewClient of certain WebView activities.
71 private class SubWindowClient extends WebViewClient {
72 // The main WebViewClient.
73 private final WebViewClient mClient;
74
75 SubWindowClient(WebViewClient client) {
76 mClient = client;
77 }
78 @Override
79 public void doUpdateVisitedHistory(WebView view, String url,
80 boolean isReload) {
81 mClient.doUpdateVisitedHistory(view, url, isReload);
82 }
83 @Override
84 public boolean shouldOverrideUrlLoading(WebView view, String url) {
85 return mClient.shouldOverrideUrlLoading(view, url);
86 }
87 @Override
88 public void onReceivedSslError(WebView view, SslErrorHandler handler,
89 SslError error) {
90 mClient.onReceivedSslError(view, handler, error);
91 }
92 @Override
93 public void onReceivedHttpAuthRequest(WebView view,
94 HttpAuthHandler handler, String host, String realm) {
95 mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
96 }
97 @Override
98 public void onFormResubmission(WebView view, Message dontResend,
99 Message resend) {
100 mClient.onFormResubmission(view, dontResend, resend);
101 }
102 @Override
103 public void onReceivedError(WebView view, int errorCode,
104 String description, String failingUrl) {
105 mClient.onReceivedError(view, errorCode, description, failingUrl);
106 }
107 }
108 // Subclass of WebChromeClient to display javascript dialogs.
109 private class SubWindowChromeClient extends WebChromeClient {
110 // This subwindow's tab.
111 private final Tab mTab;
112 // The main WebChromeClient.
113 private final WebChromeClient mClient;
114
115 SubWindowChromeClient(Tab t, WebChromeClient client) {
116 mTab = t;
117 mClient = client;
118 }
119 @Override
120 public void onProgressChanged(WebView view, int newProgress) {
121 mClient.onProgressChanged(view, newProgress);
122 }
123 @Override
124 public boolean onCreateWindow(WebView view, boolean dialog,
125 boolean userGesture, android.os.Message resultMsg) {
126 return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
127 }
128 @Override
129 public void onCloseWindow(WebView window) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700130 if (Browser.DEBUG && window != mTab.mSubView) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131 throw new AssertionError("Can't close the window");
132 }
133 mActivity.dismissSubWindow(mTab);
134 }
135 }
136 // Background WebChromeClient for focusing tabs
137 private class BackgroundChromeClient extends WebChromeClient {
138 @Override
139 public void onRequestFocus(WebView view) {
140 Tab t = getTabFromView(view);
141 if (t != getCurrentTab()) {
142 mActivity.showTab(t);
143 }
144 }
145 }
146
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400147 // Extra saved information for displaying the tab in the picker.
148 public static class PickerData {
149 String mUrl;
150 String mTitle;
151 float mScale;
152 int mScrollX;
153 int mScrollY;
154 int mWidth;
155 Picture mPicture;
156 // This can be null. When a new picture comes in, this view should be
157 // invalidated to show the new picture.
158 FakeWebView mFakeWebView;
159 }
160
The Android Open Source Project0c908882009-03-03 19:32:16 -0800161 /**
162 * Private class for maintaining Tabs with a main WebView and a subwindow.
163 */
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400164 public class Tab implements WebView.PictureListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800165 // Main WebView
166 private WebView mMainView;
167 // Subwindow WebView
168 private WebView mSubView;
169 // Subwindow container
170 private View mSubViewContainer;
171 // Subwindow callback
172 private SubWindowClient mSubViewClient;
173 // Subwindow chrome callback
174 private SubWindowChromeClient mSubViewChromeClient;
175 // Saved bundle for when we are running low on memory. It contains the
176 // information needed to restore the WebView if the user goes back to
177 // the tab.
178 private Bundle mSavedState;
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400179 // Data used when displaying the tab in the picker.
180 private PickerData mPickerData;
181
The Android Open Source Project0c908882009-03-03 19:32:16 -0800182 // Parent Tab. This is the Tab that created this Tab, or null
183 // if the Tab was created by the UI
184 private Tab mParentTab;
185 // Tab that constructed by this Tab. This is used when this
186 // Tab is destroyed, it clears all mParentTab values in the
187 // children.
188 private Vector<Tab> mChildTabs;
189
190 private Boolean mCloseOnExit;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700191 // Application identifier used to find tabs that another application
192 // wants to reuse.
193 private String mAppId;
194 // Keep the original url around to avoid killing the old WebView if the
195 // url has not changed.
196 private String mOriginalUrl;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197
198 // Construct a new tab
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700199 private Tab(WebView w, boolean closeOnExit, String appId, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mMainView = w;
201 mCloseOnExit = closeOnExit;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700202 mAppId = appId;
203 mOriginalUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204 }
205
206 /**
207 * Return the top window of this tab; either the subwindow if it is not
208 * null or the main window.
209 * @return The top window of this tab.
210 */
211 public WebView getTopWindow() {
212 if (mSubView != null) {
213 return mSubView;
214 }
215 return mMainView;
216 }
217
218 /**
219 * Return the main window of this tab. Note: if a tab is freed in the
220 * background, this can return null. It is only guaranteed to be
221 * non-null for the current tab.
222 * @return The main WebView of this tab.
223 */
224 public WebView getWebView() {
225 return mMainView;
226 }
227
228 /**
229 * Return the subwindow of this tab or null if there is no subwindow.
230 * @return The subwindow of this tab or null.
231 */
232 public WebView getSubWebView() {
233 return mSubView;
234 }
235
236 /**
237 * Return the subwindow container of this tab or null if there is no
238 * subwindow.
239 * @return The subwindow's container View.
240 */
241 public View getSubWebViewContainer() {
242 return mSubViewContainer;
243 }
244
245 /**
246 * Get the url of this tab. Valid after calling populatePickerData, but
247 * before calling wipePickerData, or if the webview has been destroyed.
248 *
249 * @return The WebView's url or null.
250 */
251 public String getUrl() {
Patrick Scott20abe042009-04-28 08:03:29 -0400252 if (mPickerData != null) {
253 return mPickerData.mUrl;
254 }
255 return null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 }
257
258 /**
259 * Get the title of this tab. Valid after calling populatePickerData,
260 * but before calling wipePickerData, or if the webview has been
261 * destroyed. If the url has no title, use the url instead.
262 *
263 * @return The WebView's title (or url) or null.
264 */
265 public String getTitle() {
Patrick Scott20abe042009-04-28 08:03:29 -0400266 if (mPickerData != null) {
267 return mPickerData.mTitle;
268 }
269 return null;
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400270 }
271
272 /**
273 * Returns the picker data.
274 */
275 public PickerData getPickerData() {
276 return mPickerData;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800277 }
278
279 private void setParentTab(Tab parent) {
280 mParentTab = parent;
281 // This tab may have been freed due to low memory. If that is the
282 // case, the parent tab index is already saved. If we are changing
283 // that index (most likely due to removing the parent tab) we must
284 // update the parent tab index in the saved Bundle.
285 if (mSavedState != null) {
286 if (parent == null) {
287 mSavedState.remove(PARENTTAB);
288 } else {
289 mSavedState.putInt(PARENTTAB, getTabIndex(parent));
290 }
291 }
292 }
293
294 /**
295 * When a Tab is created through the content of another Tab, then
296 * we associate the Tabs.
297 * @param child the Tab that was created from this Tab
298 */
299 public void addChildTab(Tab child) {
300 if (mChildTabs == null) {
301 mChildTabs = new Vector<Tab>();
302 }
303 mChildTabs.add(child);
304 child.setParentTab(this);
305 }
306
307 private void removeFromTree() {
308 // detach the children
309 if (mChildTabs != null) {
310 for(Tab t : mChildTabs) {
311 t.setParentTab(null);
312 }
313 }
314
315 // Find myself in my parent list
316 if (mParentTab != null) {
317 mParentTab.mChildTabs.remove(this);
318 }
319 }
320
321 /**
322 * If this Tab was created through another Tab, then this method
323 * returns that Tab.
324 * @return the Tab parent or null
325 */
326 public Tab getParentTab() {
327 return mParentTab;
328 }
329
330 /**
331 * Return whether this tab should be closed when it is backing out of
332 * the first page.
333 * @return TRUE if this tab should be closed when exit.
334 */
335 public boolean closeOnExit() {
336 return mCloseOnExit;
337 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400338
339 public void onNewPicture(WebView view, Picture p) {
340 if (mPickerData == null) {
341 return;
342 }
343
344 mPickerData.mPicture = p;
345 // Tell the FakeWebView to redraw.
346 if (mPickerData.mFakeWebView != null) {
347 mPickerData.mFakeWebView.invalidate();
348 }
349 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 };
351
352 // Directory to store thumbnails for each WebView.
353 private final File mThumbnailDir;
354
355 /**
356 * Construct a new TabControl object that interfaces with the given
357 * BrowserActivity instance.
358 * @param activity A BrowserActivity instance that TabControl will interface
359 * with.
360 */
361 TabControl(BrowserActivity activity) {
362 mActivity = activity;
363 mInflateService =
364 ((LayoutInflater) activity.getSystemService(
365 Context.LAYOUT_INFLATER_SERVICE));
366 mThumbnailDir = activity.getDir("thumbnails", 0);
367 }
368
369 File getThumbnailDir() {
370 return mThumbnailDir;
371 }
372
373 BrowserActivity getBrowserActivity() {
374 return mActivity;
375 }
376
377 /**
378 * Return the current tab's main WebView. This will always return the main
379 * WebView for a given tab and not a subwindow.
380 * @return The current tab's WebView.
381 */
382 WebView getCurrentWebView() {
383 Tab t = getTab(mCurrentTab);
384 if (t == null) {
385 return null;
386 }
387 return t.mMainView;
388 }
389
390 /**
391 * Return the current tab's top-level WebView. This can return a subwindow
392 * if one exists.
393 * @return The top-level WebView of the current tab.
394 */
395 WebView getCurrentTopWebView() {
396 Tab t = getTab(mCurrentTab);
397 if (t == null) {
398 return null;
399 }
400 return t.mSubView != null ? t.mSubView : t.mMainView;
401 }
402
403 /**
404 * Return the current tab's subwindow if it exists.
405 * @return The subwindow of the current tab or null if it doesn't exist.
406 */
407 WebView getCurrentSubWindow() {
408 Tab t = getTab(mCurrentTab);
409 if (t == null) {
410 return null;
411 }
412 return t.mSubView;
413 }
414
415 /**
416 * Return the tab at the specified index.
417 * @return The Tab for the specified index or null if the tab does not
418 * exist.
419 */
420 Tab getTab(int index) {
421 if (index >= 0 && index < mTabs.size()) {
422 return mTabs.get(index);
423 }
424 return null;
425 }
426
427 /**
428 * Return the current tab.
429 * @return The current tab.
430 */
431 Tab getCurrentTab() {
432 return getTab(mCurrentTab);
433 }
434
435 /**
436 * Return the current tab index.
437 * @return The current tab index
438 */
439 int getCurrentIndex() {
440 return mCurrentTab;
441 }
442
443 /**
444 * Given a Tab, find it's index
445 * @param Tab to find
446 * @return index of Tab or -1 if not found
447 */
448 int getTabIndex(Tab tab) {
449 return mTabs.indexOf(tab);
450 }
451
452 /**
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700453 * Create a new tab.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800454 * @return The newly createTab or null if we have reached the maximum
455 * number of open tabs.
456 */
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700457 Tab createNewTab(boolean closeOnExit, String appId, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800458 int size = mTabs.size();
459 // Return false if we have maxed out on tabs
460 if (MAX_TABS == size) {
461 return null;
462 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700463 final WebView w = createNewWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800464 // Create a new tab and add it to the tab list
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700465 Tab t = new Tab(w, closeOnExit, appId, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 mTabs.add(t);
The Android Open Source Project4e5f5872009-03-09 11:52:14 -0700467 // Initially put the tab in the background.
468 putTabInBackground(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800469 return t;
470 }
471
472 /**
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700473 * Create a new tab with default values for closeOnExit(false),
474 * appId(null), and url(null).
475 */
476 Tab createNewTab() {
477 return createNewTab(false, null, null);
478 }
479
480 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800481 * Remove the tab from the list. If the tab is the current tab shown, the
482 * last created tab will be shown.
483 * @param t The tab to be removed.
484 */
485 boolean removeTab(Tab t) {
486 if (t == null) {
487 return false;
488 }
489 // Only remove the tab if it is the current one.
490 if (getCurrentTab() == t) {
491 putTabInBackground(t);
492 }
493
494 // Only destroy the WebView if it still exists.
495 if (t.mMainView != null) {
496 // Take down the sub window.
497 dismissSubWindow(t);
498 // Remove the WebView's settings from the BrowserSettings list of
499 // observers.
500 BrowserSettings.getInstance().deleteObserver(
501 t.mMainView.getSettings());
502 // Destroy the main view and subview
503 t.mMainView.destroy();
504 t.mMainView = null;
505 }
506 // clear it's references to parent and children
507 t.removeFromTree();
508
509 // Remove it from our list of tabs.
510 mTabs.remove(t);
511
512 // The tab indices have shifted, update all the saved state so we point
513 // to the correct index.
514 for (Tab tab : mTabs) {
515 if (tab.mChildTabs != null) {
516 for (Tab child : tab.mChildTabs) {
517 child.setParentTab(tab);
518 }
519 }
520 }
521
522
523 // This tab may have been pushed in to the background and then closed.
524 // If the saved state contains a picture file, delete the file.
525 if (t.mSavedState != null) {
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400526 if (t.mSavedState.containsKey(CURRPICTURE)) {
527 new File(t.mSavedState.getString(CURRPICTURE)).delete();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800528 }
529 }
530
531 // Remove it from the queue of viewed tabs.
532 mTabQueue.remove(t);
533 mCurrentTab = -1;
534 return true;
535 }
536
537 /**
538 * Clear the back/forward list for all the current tabs.
539 */
540 void clearHistory() {
541 int size = getTabCount();
542 for (int i = 0; i < size; i++) {
543 Tab t = mTabs.get(i);
544 // TODO: if a tab is freed due to low memory, its history is not
545 // cleared here.
546 if (t.mMainView != null) {
547 t.mMainView.clearHistory();
548 }
549 if (t.mSubView != null) {
550 t.mSubView.clearHistory();
551 }
552 }
553 }
554
555 /**
556 * Destroy all the tabs and subwindows
557 */
558 void destroy() {
559 BrowserSettings s = BrowserSettings.getInstance();
560 for (Tab t : mTabs) {
561 if (t.mMainView != null) {
562 dismissSubWindow(t);
563 s.deleteObserver(t.mMainView.getSettings());
564 t.mMainView.destroy();
565 t.mMainView = null;
566 }
567 }
568 mTabs.clear();
569 mTabQueue.clear();
570 }
571
572 /**
573 * Returns the number of tabs created.
574 * @return The number of tabs created.
575 */
576 int getTabCount() {
577 return mTabs.size();
578 }
579
580 // Used for saving and restoring each Tab
581 private static final String WEBVIEW = "webview";
582 private static final String NUMTABS = "numTabs";
583 private static final String CURRTAB = "currentTab";
584 private static final String CURRURL = "currentUrl";
585 private static final String CURRTITLE = "currentTitle";
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400586 private static final String CURRWIDTH = "currentWidth";
587 private static final String CURRPICTURE = "currentPicture";
The Android Open Source Project0c908882009-03-03 19:32:16 -0800588 private static final String CLOSEONEXIT = "closeonexit";
589 private static final String PARENTTAB = "parentTab";
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700590 private static final String APPID = "appid";
591 private static final String ORIGINALURL = "originalUrl";
The Android Open Source Project0c908882009-03-03 19:32:16 -0800592
593 /**
594 * Save the state of all the Tabs.
595 * @param outState The Bundle to save the state to.
596 */
597 void saveState(Bundle outState) {
598 final int numTabs = getTabCount();
599 outState.putInt(NUMTABS, numTabs);
600 final int index = getCurrentIndex();
601 outState.putInt(CURRTAB, (index >= 0 && index < numTabs) ? index : 0);
602 for (int i = 0; i < numTabs; i++) {
603 final Tab t = getTab(i);
604 if (saveState(t)) {
605 outState.putBundle(WEBVIEW + i, t.mSavedState);
606 }
607 }
608 }
609
610 /**
611 * Restore the state of all the tabs.
612 * @param inState The saved state of all the tabs.
613 * @return True if there were previous tabs that were restored. False if
614 * there was no saved state or restoring the state failed.
615 */
616 boolean restoreState(Bundle inState) {
617 final int numTabs = (inState == null)
618 ? -1 : inState.getInt(NUMTABS, -1);
619 if (numTabs == -1) {
620 return false;
621 } else {
622 final int currentTab = inState.getInt(CURRTAB, -1);
623 for (int i = 0; i < numTabs; i++) {
624 if (i == currentTab) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700625 Tab t = createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800626 // Me must set the current tab before restoring the state
627 // so that all the client classes are set.
628 setCurrentTab(t);
629 if (!restoreState(inState.getBundle(WEBVIEW + i), t)) {
630 Log.w(LOGTAG, "Fail in restoreState, load home page.");
631 t.mMainView.loadUrl(BrowserSettings.getInstance()
632 .getHomePage());
633 }
634 } else {
635 // Create a new tab and don't restore the state yet, add it
636 // to the tab list
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700637 Tab t = new Tab(null, false, null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800638 t.mSavedState = inState.getBundle(WEBVIEW + i);
639 if (t.mSavedState != null) {
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400640 populatePickerDataFromSavedState(t);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700641 // Need to maintain the app id and original url so we
642 // can possibly reuse this tab.
643 t.mAppId = t.mSavedState.getString(APPID);
644 t.mOriginalUrl = t.mSavedState.getString(ORIGINALURL);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800645 }
646 mTabs.add(t);
647 mTabQueue.add(t);
648 }
649 }
650 // Rebuild the tree of tabs. Do this after all tabs have been
651 // created/restored so that the parent tab exists.
652 for (int i = 0; i < numTabs; i++) {
653 final Bundle b = inState.getBundle(WEBVIEW + i);
654 final Tab t = getTab(i);
655 if (b != null && t != null) {
656 final int parentIndex = b.getInt(PARENTTAB, -1);
657 if (parentIndex != -1) {
658 final Tab parent = getTab(parentIndex);
659 if (parent != null) {
660 parent.addChildTab(t);
661 }
662 }
663 }
664 }
665 }
666 return true;
667 }
668
669 /**
670 * Free the memory in this order, 1) free the background tab; 2) free the
671 * WebView cache;
672 */
673 void freeMemory() {
674 // free the least frequently used background tab
675 Tab t = getLeastUsedTab();
676 if (t != null) {
677 Log.w(LOGTAG, "Free a tab in the browser");
678 freeTab(t);
679 // force a gc
680 System.gc();
681 return;
682 }
683
684 // free the WebView cache
685 Log.w(LOGTAG, "Free WebView cache");
686 WebView view = getCurrentWebView();
687 if (view != null) {
688 view.clearCache(false);
689 }
690 // force a gc
691 System.gc();
692 }
693
694 private Tab getLeastUsedTab() {
695 // Don't do anything if we only have 1 tab.
696 if (getTabCount() == 1) {
697 return null;
698 }
699
700 // Rip through the queue starting at the beginning and teardown the
701 // next available tab.
702 Tab t = null;
703 int i = 0;
704 final int queueSize = mTabQueue.size();
705 if (queueSize == 0) {
706 return null;
707 }
708 do {
709 t = mTabQueue.get(i++);
710 } while (i < queueSize && t != null && t.mMainView == null);
711
712 // Don't do anything if the last remaining tab is the current one.
713 if (t == getCurrentTab()) {
714 return null;
715 }
716
717 return t;
718 }
719
720 private void freeTab(Tab t) {
721 // Store the WebView's state.
722 saveState(t);
723
724 // Tear down the tab.
725 dismissSubWindow(t);
726 // Remove the WebView's settings from the BrowserSettings list of
727 // observers.
728 BrowserSettings.getInstance().deleteObserver(t.mMainView.getSettings());
729 t.mMainView.destroy();
730 t.mMainView = null;
731 }
732
733 /**
734 * Create a new subwindow unless a subwindow already exists.
735 * @return True if a new subwindow was created. False if one already exists.
736 */
737 void createSubWindow() {
738 Tab t = getTab(mCurrentTab);
739 if (t != null && t.mSubView == null) {
740 final View v = mInflateService.inflate(R.layout.browser_subwindow, null);
741 final WebView w = (WebView) v.findViewById(R.id.webview);
742 w.setMapTrackballToArrowKeys(false); // use trackball directly
743 final SubWindowClient subClient =
744 new SubWindowClient(mActivity.getWebViewClient());
745 final SubWindowChromeClient subChromeClient =
746 new SubWindowChromeClient(t,
747 mActivity.getWebChromeClient());
748 w.setWebViewClient(subClient);
749 w.setWebChromeClient(subChromeClient);
750 w.setDownloadListener(mActivity);
751 w.setOnCreateContextMenuListener(mActivity);
752 final BrowserSettings s = BrowserSettings.getInstance();
753 s.addObserver(w.getSettings()).update(s, null);
754 t.mSubView = w;
755 t.mSubViewClient = subClient;
756 t.mSubViewChromeClient = subChromeClient;
757 // FIXME: I really hate having to know the name of the view
758 // containing the webview.
759 t.mSubViewContainer = v.findViewById(R.id.subwindow_container);
760 final ImageButton cancel =
761 (ImageButton) v.findViewById(R.id.subwindow_close);
762 cancel.setOnClickListener(new OnClickListener() {
763 public void onClick(View v) {
764 subChromeClient.onCloseWindow(w);
765 }
766 });
767 }
768 }
769
770 /**
771 * Show the tab that contains the given WebView.
772 * @param view The WebView used to find the tab.
773 */
774 Tab getTabFromView(WebView view) {
775 final int size = getTabCount();
776 for (int i = 0; i < size; i++) {
777 final Tab t = getTab(i);
778 if (t.mSubView == view || t.mMainView == view) {
779 return t;
780 }
781 }
782 return null;
783 }
784
785 /**
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700786 * Return the tab with the matching application id.
787 * @param id The application identifier.
788 */
789 Tab getTabFromId(String id) {
790 if (id == null) {
791 return null;
792 }
793 final int size = getTabCount();
794 for (int i = 0; i < size; i++) {
795 final Tab t = getTab(i);
796 if (id.equals(t.mAppId)) {
797 return t;
798 }
799 }
800 return null;
801 }
802
803 /**
804 * Recreate the main WebView of the given tab. Returns true if the WebView
805 * was deleted.
806 */
807 boolean recreateWebView(Tab t, String url) {
808 final WebView w = t.mMainView;
809 if (w != null) {
810 if (url != null && url.equals(t.mOriginalUrl)) {
811 // The original url matches the current url. Just go back to the
812 // first history item so we can load it faster than if we
813 // rebuilt the WebView.
814 final WebBackForwardList list = w.copyBackForwardList();
815 if (list != null) {
816 w.goBackOrForward(-list.getCurrentIndex());
817 w.clearHistory(); // maintains the current page.
818 return false;
819 }
820 }
821 // Remove the settings object from the global settings and destroy
822 // the WebView.
823 BrowserSettings.getInstance().deleteObserver(
824 t.mMainView.getSettings());
825 t.mMainView.destroy();
826 }
827 // Create a new WebView. If this tab is the current tab, we need to put
828 // back all the clients so force it to be the current tab.
829 t.mMainView = createNewWebView();
830 if (getCurrentTab() == t) {
831 setCurrentTab(t, true);
832 }
833 // Clear the saved state except for the app id and close-on-exit
834 // values.
835 t.mSavedState = null;
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400836 t.mPickerData = null;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700837 // Save the new url in order to avoid deleting the WebView.
838 t.mOriginalUrl = url;
839 return true;
840 }
841
842 /**
843 * Creates a new WebView and registers it with the global settings.
844 */
845 private WebView createNewWebView() {
846 // Create a new WebView
847 WebView w = new WebView(mActivity);
848 w.setMapTrackballToArrowKeys(false); // use trackball directly
The Android Open Source Projecta3c0aab2009-03-18 17:39:48 -0700849 // Enable the built-in zoom
850 w.getSettings().setBuiltInZoomControls(true);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700851 // Add this WebView to the settings observer list and update the
852 // settings
853 final BrowserSettings s = BrowserSettings.getInstance();
854 s.addObserver(w.getSettings()).update(s, null);
855 return w;
856 }
857
858 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800859 * Put the current tab in the background and set newTab as the current tab.
860 * @param newTab The new tab. If newTab is null, the current tab is not
861 * set.
862 */
863 boolean setCurrentTab(Tab newTab) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700864 return setCurrentTab(newTab, false);
865 }
866
867 /**
868 * If force is true, this method skips the check for newTab == current.
869 */
870 private boolean setCurrentTab(Tab newTab, boolean force) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800871 Tab current = getTab(mCurrentTab);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700872 if (current == newTab && !force) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800873 return true;
874 }
875 if (current != null) {
876 // Remove the current WebView and the container of the subwindow
877 putTabInBackground(current);
878 }
879
880 if (newTab == null) {
881 return false;
882 }
883
884 // Move the newTab to the end of the queue
885 int index = mTabQueue.indexOf(newTab);
886 if (index != -1) {
887 mTabQueue.remove(index);
888 }
889 mTabQueue.add(newTab);
890
891 WebView mainView;
892 WebView subView;
893
894 // Display the new current tab
895 mCurrentTab = mTabs.indexOf(newTab);
896 mainView = newTab.mMainView;
897 boolean needRestore = (mainView == null);
898 if (needRestore) {
899 // Same work as in createNewTab() except don't do new Tab()
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700900 newTab.mMainView = mainView = createNewWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800901 }
902 mainView.setWebViewClient(mActivity.getWebViewClient());
903 mainView.setWebChromeClient(mActivity.getWebChromeClient());
904 mainView.setOnCreateContextMenuListener(mActivity);
905 mainView.setDownloadListener(mActivity);
906 // Add the subwindow if it exists
907 if (newTab.mSubViewContainer != null) {
908 subView = newTab.mSubView;
909 subView.setWebViewClient(newTab.mSubViewClient);
910 subView.setWebChromeClient(newTab.mSubViewChromeClient);
911 subView.setOnCreateContextMenuListener(mActivity);
912 subView.setDownloadListener(mActivity);
913 }
914 if (needRestore) {
915 // Have to finish setCurrentTab work before calling restoreState
916 if (!restoreState(newTab.mSavedState, newTab)) {
917 mainView.loadUrl(BrowserSettings.getInstance().getHomePage());
918 }
919 }
920 return true;
921 }
922
923 /*
924 * Put the tab in the background using all the empty/background clients.
925 */
926 private void putTabInBackground(Tab t) {
927 WebView mainView = t.mMainView;
928 // Set an empty callback so that default actions are not triggered.
929 mainView.setWebViewClient(mEmptyClient);
930 mainView.setWebChromeClient(mBackgroundChromeClient);
931 mainView.setOnCreateContextMenuListener(null);
932 // Leave the DownloadManager attached so that downloads can start in
933 // a non-active window. This can happen when going to a site that does
934 // a redirect after a period of time. The user could have switched to
935 // another tab while waiting for the download to start.
936 mainView.setDownloadListener(mActivity);
937 WebView subView = t.mSubView;
938 if (subView != null) {
939 // Set an empty callback so that default actions are not triggered.
940 subView.setWebViewClient(mEmptyClient);
941 subView.setWebChromeClient(mBackgroundChromeClient);
942 subView.setOnCreateContextMenuListener(null);
943 subView.setDownloadListener(mActivity);
944 }
945 }
946
947 /*
948 * Dismiss the subwindow for the given tab.
949 */
950 void dismissSubWindow(Tab t) {
951 if (t != null && t.mSubView != null) {
952 BrowserSettings.getInstance().deleteObserver(
953 t.mSubView.getSettings());
954 t.mSubView.destroy();
955 t.mSubView = null;
956 t.mSubViewContainer = null;
957 }
958 }
959
960 /**
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400961 * Ensure that Tab t has data to display in the tab picker.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800962 * @param t Tab to populate.
963 */
964 /* package */ void populatePickerData(Tab t) {
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400965 if (t == null) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 return;
967 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400968
969 // mMainView == null indicates that the tab has been freed.
970 if (t.mMainView == null) {
971 populatePickerDataFromSavedState(t);
972 return;
973 }
974
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 // FIXME: The only place we cared about subwindow was for
976 // bookmarking (i.e. not when saving state). Was this deliberate?
977 final WebBackForwardList list = t.mMainView.copyBackForwardList();
978 final WebHistoryItem item =
979 list != null ? list.getCurrentItem() : null;
980 populatePickerData(t, item);
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400981
982 // This method is only called during the tab picker creation. At this
983 // point we need to listen for new pictures since the WebView is still
984 // active.
985 final WebView w = t.getTopWindow();
986 w.setPictureListener(t);
987 // Capture the picture here instead of populatePickerData since it can
988 // be called when saving the state of a tab.
989 t.mPickerData.mPicture = w.capturePicture();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800990 }
991
Patrick Scott2ed6edb2009-04-22 10:07:45 -0400992 // Create the PickerData and populate it using the saved state of the tab.
993 private void populatePickerDataFromSavedState(Tab t) {
994 if (t.mSavedState == null) {
995 return;
996 }
997
998 final PickerData data = new PickerData();
999 final Bundle state = t.mSavedState;
1000 data.mUrl = state.getString(CURRURL);
1001 data.mTitle = state.getString(CURRTITLE);
1002 data.mWidth = state.getInt(CURRWIDTH, 0);
1003 // XXX: These keys are from WebView.savePicture so if they change, this
1004 // will break.
1005 data.mScale = state.getFloat("scale", 1.0f);
1006 data.mScrollX = state.getInt("scrollX", 0);
1007 data.mScrollY = state.getInt("scrollY", 0);
1008
1009 if (state.containsKey(CURRPICTURE)) {
1010 final File f = new File(t.mSavedState.getString(CURRPICTURE));
1011 try {
1012 final FileInputStream in = new FileInputStream(f);
1013 data.mPicture = Picture.createFromStream(in);
1014 in.close();
1015 } catch (Exception ex) {
1016 // Ignore any problems with inflating the picture. We just
1017 // won't draw anything.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 }
1019 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001020
1021 // Set the tab's picker data.
1022 t.mPickerData = data;
1023 }
1024
1025 // Populate the picker data using the given history item and the current
1026 // top WebView.
1027 private void populatePickerData(Tab t, WebHistoryItem item) {
1028 final PickerData data = new PickerData();
1029 if (item != null) {
1030 data.mUrl = item.getUrl();
1031 data.mTitle = item.getTitle();
1032 if (data.mTitle == null) {
1033 data.mTitle = data.mUrl;
1034 }
1035 }
1036 // We want to display the top window in the tab picker but use the url
1037 // and title of the main window.
1038 final WebView w = t.getTopWindow();
1039 data.mWidth = w.getWidth();
1040 data.mScale = w.getScale();
1041 data.mScrollX = w.getScrollX();
1042 data.mScrollY = w.getScrollY();
1043 t.mPickerData = data;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045
1046 /**
1047 * Clean up the data for all tabs.
1048 */
1049 /* package */ void wipeAllPickerData() {
1050 int size = getTabCount();
1051 for (int i = 0; i < size; i++) {
1052 final Tab t = getTab(i);
1053 if (t != null && t.mSavedState == null) {
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001054 t.mPickerData = null;
1055 }
1056 if (t.mMainView != null) {
1057 // Clear the picture listeners.
1058 t.mMainView.setPictureListener(null);
1059 if (t.mSubView != null) {
1060 t.mSubView.setPictureListener(null);
1061 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001062 }
1063 }
1064 }
1065
1066 /*
1067 * Save the state for an individual tab.
1068 */
1069 private boolean saveState(Tab t) {
1070 if (t != null) {
1071 final WebView w = t.mMainView;
1072 // If the WebView is null it means we ran low on memory and we
1073 // already stored the saved state in mSavedState.
1074 if (w == null) {
1075 return true;
1076 }
1077 final Bundle b = new Bundle();
1078 final WebBackForwardList list = w.saveState(b);
1079 if (list != null) {
1080 final File f = new File(mThumbnailDir, w.hashCode()
1081 + "_pic.save");
1082 if (w.savePicture(b, f)) {
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001083 b.putString(CURRPICTURE, f.getPath());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 }
1085 }
1086
1087 // Store some extra info for displaying the tab in the picker.
1088 final WebHistoryItem item =
1089 list != null ? list.getCurrentItem() : null;
1090 populatePickerData(t, item);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001091
1092 // XXX: WebView.savePicture stores the scale and scroll positions
1093 // in the bundle so we don't have to do it here.
1094 final PickerData data = t.mPickerData;
1095 if (data.mUrl != null) {
1096 b.putString(CURRURL, data.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001097 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001098 if (data.mTitle != null) {
1099 b.putString(CURRTITLE, data.mTitle);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001101 b.putInt(CURRWIDTH, data.mWidth);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001102 b.putBoolean(CLOSEONEXIT, t.mCloseOnExit);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001103 if (t.mAppId != null) {
1104 b.putString(APPID, t.mAppId);
1105 }
1106 if (t.mOriginalUrl != null) {
1107 b.putString(ORIGINALURL, t.mOriginalUrl);
1108 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109
1110 // Remember the parent tab so the relationship can be restored.
1111 if (t.mParentTab != null) {
1112 b.putInt(PARENTTAB, getTabIndex(t.mParentTab));
1113 }
1114
1115 // Remember the saved state.
1116 t.mSavedState = b;
1117 return true;
1118 }
1119 return false;
1120 }
1121
1122 /*
1123 * Restore the state of the tab.
1124 */
1125 private boolean restoreState(Bundle b, Tab t) {
1126 if (b == null) {
1127 return false;
1128 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001129 // Restore the internal state even if the WebView fails to restore.
1130 // This will maintain the app id, original url and close-on-exit values.
1131 t.mSavedState = null;
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001132 t.mPickerData = null;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001133 t.mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1134 t.mAppId = b.getString(APPID);
1135 t.mOriginalUrl = b.getString(ORIGINALURL);
1136
The Android Open Source Project0c908882009-03-03 19:32:16 -08001137 final WebView w = t.mMainView;
1138 final WebBackForwardList list = w.restoreState(b);
1139 if (list == null) {
1140 return false;
1141 }
Patrick Scott2ed6edb2009-04-22 10:07:45 -04001142 if (b.containsKey(CURRPICTURE)) {
1143 final File f = new File(b.getString(CURRPICTURE));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001144 w.restorePicture(b, f);
1145 f.delete();
1146 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001147 return true;
1148 }
1149}