OSDN Git Service

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