OSDN Git Service

am 80529427: (-s ours) Import revised translations. DO NOT MERGE
[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.
850          * @param message The error message to report.
851          * @param lineNumber The line number of the error.
852          * @param sourceID The name of the source file that caused the error.
853          */
854         @Override
855         public void addMessageToConsole(String message, int lineNumber,
856                 String sourceID) {
857             if (mInForeground) {
858                 // call getErrorConsole(true) so it will create one if needed
859                 ErrorConsoleView errorConsole = getErrorConsole(true);
860                 errorConsole.addErrorMessage(message, sourceID, lineNumber);
861                 if (mActivity.shouldShowErrorConsole()
862                         && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
863                     errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
864                 }
865             }
866             Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":"
867                     + lineNumber);
868         }
869
870         /**
871          * Ask the browser for an icon to represent a <video> element.
872          * This icon will be used if the Web page did not specify a poster attribute.
873          * @return Bitmap The icon or null if no such icon is available.
874          */
875         @Override
876         public Bitmap getDefaultVideoPoster() {
877             if (mInForeground) {
878                 return mActivity.getDefaultVideoPoster();
879             }
880             return null;
881         }
882
883         /**
884          * Ask the host application for a custom progress view to show while
885          * a <video> is loading.
886          * @return View The progress view.
887          */
888         @Override
889         public View getVideoLoadingProgressView() {
890             if (mInForeground) {
891                 return mActivity.getVideoLoadingProgressView();
892             }
893             return null;
894         }
895
896         @Override
897         public void openFileChooser(ValueCallback<Uri> uploadMsg) {
898             if (mInForeground) {
899                 mActivity.openFileChooser(uploadMsg);
900             } else {
901                 uploadMsg.onReceiveValue(null);
902             }
903         }
904
905         /**
906          * Deliver a list of already-visited URLs
907          */
908         @Override
909         public void getVisitedHistory(final ValueCallback<String[]> callback) {
910             AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
911                 public String[] doInBackground(Void... unused) {
912                     return Browser.getVisitedHistory(mActivity
913                             .getContentResolver());
914                 }
915                 public void onPostExecute(String[] result) {
916                     callback.onReceiveValue(result);
917                 };
918             };
919             task.execute();
920         };
921     };
922
923     // -------------------------------------------------------------------------
924     // WebViewClient implementation for the sub window
925     // -------------------------------------------------------------------------
926
927     // Subclass of WebViewClient used in subwindows to notify the main
928     // WebViewClient of certain WebView activities.
929     private static class SubWindowClient extends WebViewClient {
930         // The main WebViewClient.
931         private final WebViewClient mClient;
932
933         SubWindowClient(WebViewClient client) {
934             mClient = client;
935         }
936         @Override
937         public void doUpdateVisitedHistory(WebView view, String url,
938                 boolean isReload) {
939             mClient.doUpdateVisitedHistory(view, url, isReload);
940         }
941         @Override
942         public boolean shouldOverrideUrlLoading(WebView view, String url) {
943             return mClient.shouldOverrideUrlLoading(view, url);
944         }
945         @Override
946         public void onReceivedSslError(WebView view, SslErrorHandler handler,
947                 SslError error) {
948             mClient.onReceivedSslError(view, handler, error);
949         }
950         @Override
951         public void onReceivedHttpAuthRequest(WebView view,
952                 HttpAuthHandler handler, String host, String realm) {
953             mClient.onReceivedHttpAuthRequest(view, handler, host, realm);
954         }
955         @Override
956         public void onFormResubmission(WebView view, Message dontResend,
957                 Message resend) {
958             mClient.onFormResubmission(view, dontResend, resend);
959         }
960         @Override
961         public void onReceivedError(WebView view, int errorCode,
962                 String description, String failingUrl) {
963             mClient.onReceivedError(view, errorCode, description, failingUrl);
964         }
965         @Override
966         public boolean shouldOverrideKeyEvent(WebView view,
967                 android.view.KeyEvent event) {
968             return mClient.shouldOverrideKeyEvent(view, event);
969         }
970         @Override
971         public void onUnhandledKeyEvent(WebView view,
972                 android.view.KeyEvent event) {
973             mClient.onUnhandledKeyEvent(view, event);
974         }
975     }
976
977     // -------------------------------------------------------------------------
978     // WebChromeClient implementation for the sub window
979     // -------------------------------------------------------------------------
980
981     private class SubWindowChromeClient extends WebChromeClient {
982         // The main WebChromeClient.
983         private final WebChromeClient mClient;
984
985         SubWindowChromeClient(WebChromeClient client) {
986             mClient = client;
987         }
988         @Override
989         public void onProgressChanged(WebView view, int newProgress) {
990             mClient.onProgressChanged(view, newProgress);
991         }
992         @Override
993         public boolean onCreateWindow(WebView view, boolean dialog,
994                 boolean userGesture, android.os.Message resultMsg) {
995             return mClient.onCreateWindow(view, dialog, userGesture, resultMsg);
996         }
997         @Override
998         public void onCloseWindow(WebView window) {
999             if (window != mSubView) {
1000                 Log.e(LOGTAG, "Can't close the window");
1001             }
1002             mActivity.dismissSubWindow(Tab.this);
1003         }
1004     }
1005
1006     // -------------------------------------------------------------------------
1007
1008     // Construct a new tab
1009     Tab(BrowserActivity activity, WebView w, boolean closeOnExit, String appId,
1010             String url) {
1011         mActivity = activity;
1012         mCloseOnExit = closeOnExit;
1013         mAppId = appId;
1014         mOriginalUrl = url;
1015         mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1016         mPrevLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1017         mInLoad = false;
1018         mInForeground = false;
1019
1020         mInflateService = LayoutInflater.from(activity);
1021
1022         // The tab consists of a container view, which contains the main
1023         // WebView, as well as any other UI elements associated with the tab.
1024         mContainer = mInflateService.inflate(R.layout.tab, null);
1025
1026         mGeolocationPermissionsPrompt =
1027             (GeolocationPermissionsPrompt) mContainer.findViewById(
1028                 R.id.geolocation_permissions_prompt);
1029
1030         setWebView(w);
1031     }
1032
1033     /**
1034      * Sets the WebView for this tab, correctly removing the old WebView from
1035      * the container view.
1036      */
1037     void setWebView(WebView w) {
1038         if (mMainView == w) {
1039             return;
1040         }
1041         // If the WebView is changing, the page will be reloaded, so any ongoing
1042         // Geolocation permission requests are void.
1043         mGeolocationPermissionsPrompt.hide();
1044
1045         // Just remove the old one.
1046         FrameLayout wrapper =
1047                 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1048         wrapper.removeView(mMainView);
1049
1050         // set the new one
1051         mMainView = w;
1052         // attached the WebViewClient and WebChromeClient
1053         if (mMainView != null) {
1054             mMainView.setWebViewClient(mWebViewClient);
1055             mMainView.setWebChromeClient(mWebChromeClient);
1056         }
1057     }
1058
1059     /**
1060      * Destroy the tab's main WebView and subWindow if any
1061      */
1062     void destroy() {
1063         if (mMainView != null) {
1064             dismissSubWindow();
1065             BrowserSettings.getInstance().deleteObserver(mMainView.getSettings());
1066             // save the WebView to call destroy() after detach it from the tab
1067             WebView webView = mMainView;
1068             setWebView(null);
1069             webView.destroy();
1070         }
1071     }
1072
1073     /**
1074      * Remove the tab from the parent
1075      */
1076     void removeFromTree() {
1077         // detach the children
1078         if (mChildTabs != null) {
1079             for(Tab t : mChildTabs) {
1080                 t.setParentTab(null);
1081             }
1082         }
1083         // remove itself from the parent list
1084         if (mParentTab != null) {
1085             mParentTab.mChildTabs.remove(this);
1086         }
1087     }
1088
1089     /**
1090      * Create a new subwindow unless a subwindow already exists.
1091      * @return True if a new subwindow was created. False if one already exists.
1092      */
1093     boolean createSubWindow() {
1094         if (mSubView == null) {
1095             mSubViewContainer = mInflateService.inflate(
1096                     R.layout.browser_subwindow, null);
1097             mSubView = (WebView) mSubViewContainer.findViewById(R.id.webview);
1098             // use trackball directly
1099             mSubView.setMapTrackballToArrowKeys(false);
1100             mSubView.setWebViewClient(new SubWindowClient(mWebViewClient));
1101             mSubView.setWebChromeClient(new SubWindowChromeClient(
1102                     mWebChromeClient));
1103             mSubView.setDownloadListener(mActivity);
1104             mSubView.setOnCreateContextMenuListener(mActivity);
1105             final BrowserSettings s = BrowserSettings.getInstance();
1106             s.addObserver(mSubView.getSettings()).update(s, null);
1107             final ImageButton cancel = (ImageButton) mSubViewContainer
1108                     .findViewById(R.id.subwindow_close);
1109             cancel.setOnClickListener(new OnClickListener() {
1110                 public void onClick(View v) {
1111                     mSubView.getWebChromeClient().onCloseWindow(mSubView);
1112                 }
1113             });
1114             return true;
1115         }
1116         return false;
1117     }
1118
1119     /**
1120      * Dismiss the subWindow for the tab.
1121      */
1122     void dismissSubWindow() {
1123         if (mSubView != null) {
1124             BrowserSettings.getInstance().deleteObserver(
1125                     mSubView.getSettings());
1126             mSubView.destroy();
1127             mSubView = null;
1128             mSubViewContainer = null;
1129         }
1130     }
1131
1132     /**
1133      * Attach the sub window to the content view.
1134      */
1135     void attachSubWindow(ViewGroup content) {
1136         if (mSubView != null) {
1137             content.addView(mSubViewContainer,
1138                     BrowserActivity.COVER_SCREEN_PARAMS);
1139         }
1140     }
1141
1142     /**
1143      * Remove the sub window from the content view.
1144      */
1145     void removeSubWindow(ViewGroup content) {
1146         if (mSubView != null) {
1147             content.removeView(mSubViewContainer);
1148         }
1149     }
1150
1151     /**
1152      * This method attaches both the WebView and any sub window to the
1153      * given content view.
1154      */
1155     void attachTabToContentView(ViewGroup content) {
1156         if (mMainView == null) {
1157             return;
1158         }
1159
1160         // Attach the WebView to the container and then attach the
1161         // container to the content view.
1162         FrameLayout wrapper =
1163                 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1164         wrapper.addView(mMainView);
1165         content.addView(mContainer, BrowserActivity.COVER_SCREEN_PARAMS);
1166         attachSubWindow(content);
1167     }
1168
1169     /**
1170      * Remove the WebView and any sub window from the given content view.
1171      */
1172     void removeTabFromContentView(ViewGroup content) {
1173         if (mMainView == null) {
1174             return;
1175         }
1176
1177         // Remove the container from the content and then remove the
1178         // WebView from the container. This will trigger a focus change
1179         // needed by WebView.
1180         FrameLayout wrapper =
1181                 (FrameLayout) mContainer.findViewById(R.id.webview_wrapper);
1182         wrapper.removeView(mMainView);
1183         content.removeView(mContainer);
1184         removeSubWindow(content);
1185     }
1186
1187     /**
1188      * Set the parent tab of this tab.
1189      */
1190     void setParentTab(Tab parent) {
1191         mParentTab = parent;
1192         // This tab may have been freed due to low memory. If that is the case,
1193         // the parent tab index is already saved. If we are changing that index
1194         // (most likely due to removing the parent tab) we must update the
1195         // parent tab index in the saved Bundle.
1196         if (mSavedState != null) {
1197             if (parent == null) {
1198                 mSavedState.remove(PARENTTAB);
1199             } else {
1200                 mSavedState.putInt(PARENTTAB, mActivity.getTabControl()
1201                         .getTabIndex(parent));
1202             }
1203         }
1204     }
1205
1206     /**
1207      * When a Tab is created through the content of another Tab, then we
1208      * associate the Tabs.
1209      * @param child the Tab that was created from this Tab
1210      */
1211     void addChildTab(Tab child) {
1212         if (mChildTabs == null) {
1213             mChildTabs = new Vector<Tab>();
1214         }
1215         mChildTabs.add(child);
1216         child.setParentTab(this);
1217     }
1218
1219     Vector<Tab> getChildTabs() {
1220         return mChildTabs;
1221     }
1222
1223     void resume() {
1224         if (mMainView != null) {
1225             mMainView.onResume();
1226             if (mSubView != null) {
1227                 mSubView.onResume();
1228             }
1229         }
1230     }
1231
1232     void pause() {
1233         if (mMainView != null) {
1234             mMainView.onPause();
1235             if (mSubView != null) {
1236                 mSubView.onPause();
1237             }
1238         }
1239     }
1240
1241     void putInForeground() {
1242         mInForeground = true;
1243         resume();
1244         mMainView.setOnCreateContextMenuListener(mActivity);
1245         if (mSubView != null) {
1246             mSubView.setOnCreateContextMenuListener(mActivity);
1247         }
1248         // Show the pending error dialog if the queue is not empty
1249         if (mQueuedErrors != null && mQueuedErrors.size() >  0) {
1250             showError(mQueuedErrors.getFirst());
1251         }
1252     }
1253
1254     void putInBackground() {
1255         mInForeground = false;
1256         pause();
1257         mMainView.setOnCreateContextMenuListener(null);
1258         if (mSubView != null) {
1259             mSubView.setOnCreateContextMenuListener(null);
1260         }
1261     }
1262
1263     /**
1264      * Return the top window of this tab; either the subwindow if it is not
1265      * null or the main window.
1266      * @return The top window of this tab.
1267      */
1268     WebView getTopWindow() {
1269         if (mSubView != null) {
1270             return mSubView;
1271         }
1272         return mMainView;
1273     }
1274
1275     /**
1276      * Return the main window of this tab. Note: if a tab is freed in the
1277      * background, this can return null. It is only guaranteed to be
1278      * non-null for the current tab.
1279      * @return The main WebView of this tab.
1280      */
1281     WebView getWebView() {
1282         return mMainView;
1283     }
1284
1285     /**
1286      * Return the subwindow of this tab or null if there is no subwindow.
1287      * @return The subwindow of this tab or null.
1288      */
1289     WebView getSubWebView() {
1290         return mSubView;
1291     }
1292
1293     /**
1294      * @return The geolocation permissions prompt for this tab.
1295      */
1296     GeolocationPermissionsPrompt getGeolocationPermissionsPrompt() {
1297         return mGeolocationPermissionsPrompt;
1298     }
1299
1300     /**
1301      * @return The application id string
1302      */
1303     String getAppId() {
1304         return mAppId;
1305     }
1306
1307     /**
1308      * Set the application id string
1309      * @param id
1310      */
1311     void setAppId(String id) {
1312         mAppId = id;
1313     }
1314
1315     /**
1316      * @return The original url associated with this Tab
1317      */
1318     String getOriginalUrl() {
1319         return mOriginalUrl;
1320     }
1321
1322     /**
1323      * Set the original url associated with this tab
1324      */
1325     void setOriginalUrl(String url) {
1326         mOriginalUrl = url;
1327     }
1328
1329     /**
1330      * Get the url of this tab. Valid after calling populatePickerData, but
1331      * before calling wipePickerData, or if the webview has been destroyed.
1332      * @return The WebView's url or null.
1333      */
1334     String getUrl() {
1335         if (mPickerData != null) {
1336             return mPickerData.mUrl;
1337         }
1338         return null;
1339     }
1340
1341     /**
1342      * Get the title of this tab. Valid after calling populatePickerData, but
1343      * before calling wipePickerData, or if the webview has been destroyed. If
1344      * the url has no title, use the url instead.
1345      * @return The WebView's title (or url) or null.
1346      */
1347     String getTitle() {
1348         if (mPickerData != null) {
1349             return mPickerData.mTitle;
1350         }
1351         return null;
1352     }
1353
1354     /**
1355      * Get the favicon of this tab. Valid after calling populatePickerData, but
1356      * before calling wipePickerData, or if the webview has been destroyed.
1357      * @return The WebView's favicon or null.
1358      */
1359     Bitmap getFavicon() {
1360         if (mPickerData != null) {
1361             return mPickerData.mFavicon;
1362         }
1363         return null;
1364     }
1365
1366     /**
1367      * Return the tab's error console. Creates the console if createIfNEcessary
1368      * is true and we haven't already created the console.
1369      * @param createIfNecessary Flag to indicate if the console should be
1370      *            created if it has not been already.
1371      * @return The tab's error console, or null if one has not been created and
1372      *         createIfNecessary is false.
1373      */
1374     ErrorConsoleView getErrorConsole(boolean createIfNecessary) {
1375         if (createIfNecessary && mErrorConsole == null) {
1376             mErrorConsole = new ErrorConsoleView(mActivity);
1377             mErrorConsole.setWebView(mMainView);
1378         }
1379         return mErrorConsole;
1380     }
1381
1382     /**
1383      * If this Tab was created through another Tab, then this method returns
1384      * that Tab.
1385      * @return the Tab parent or null
1386      */
1387     public Tab getParentTab() {
1388         return mParentTab;
1389     }
1390
1391     /**
1392      * Return whether this tab should be closed when it is backing out of the
1393      * first page.
1394      * @return TRUE if this tab should be closed when exit.
1395      */
1396     boolean closeOnExit() {
1397         return mCloseOnExit;
1398     }
1399
1400     /**
1401      * Saves the current lock-icon state before resetting the lock icon. If we
1402      * have an error, we may need to roll back to the previous state.
1403      */
1404     void resetLockIcon(String url) {
1405         mPrevLockIconType = mLockIconType;
1406         mLockIconType = BrowserActivity.LOCK_ICON_UNSECURE;
1407         if (URLUtil.isHttpsUrl(url)) {
1408             mLockIconType = BrowserActivity.LOCK_ICON_SECURE;
1409         }
1410     }
1411
1412     /**
1413      * Reverts the lock-icon state to the last saved state, for example, if we
1414      * had an error, and need to cancel the load.
1415      */
1416     void revertLockIcon() {
1417         mLockIconType = mPrevLockIconType;
1418     }
1419
1420     /**
1421      * @return The tab's lock icon type.
1422      */
1423     int getLockIconType() {
1424         return mLockIconType;
1425     }
1426
1427     /**
1428      * @return TRUE if onPageStarted is called while onPageFinished is not
1429      *         called yet.
1430      */
1431     boolean inLoad() {
1432         return mInLoad;
1433     }
1434
1435     // force mInLoad to be false. This should only be called before closing the
1436     // tab to ensure BrowserActivity's pauseWebViewTimers() is called correctly.
1437     void clearInLoad() {
1438         mInLoad = false;
1439     }
1440
1441     void populatePickerData() {
1442         if (mMainView == null) {
1443             populatePickerDataFromSavedState();
1444             return;
1445         }
1446
1447         // FIXME: The only place we cared about subwindow was for
1448         // bookmarking (i.e. not when saving state). Was this deliberate?
1449         final WebBackForwardList list = mMainView.copyBackForwardList();
1450         final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1451         populatePickerData(item);
1452     }
1453
1454     // Populate the picker data using the given history item and the current top
1455     // WebView.
1456     private void populatePickerData(WebHistoryItem item) {
1457         mPickerData = new PickerData();
1458         if (item != null) {
1459             mPickerData.mUrl = item.getUrl();
1460             mPickerData.mTitle = item.getTitle();
1461             mPickerData.mFavicon = item.getFavicon();
1462             if (mPickerData.mTitle == null) {
1463                 mPickerData.mTitle = mPickerData.mUrl;
1464             }
1465         }
1466     }
1467
1468     // Create the PickerData and populate it using the saved state of the tab.
1469     void populatePickerDataFromSavedState() {
1470         if (mSavedState == null) {
1471             return;
1472         }
1473         mPickerData = new PickerData();
1474         mPickerData.mUrl = mSavedState.getString(CURRURL);
1475         mPickerData.mTitle = mSavedState.getString(CURRTITLE);
1476     }
1477
1478     void clearPickerData() {
1479         mPickerData = null;
1480     }
1481
1482     /**
1483      * Get the saved state bundle.
1484      * @return
1485      */
1486     Bundle getSavedState() {
1487         return mSavedState;
1488     }
1489
1490     /**
1491      * Set the saved state.
1492      */
1493     void setSavedState(Bundle state) {
1494         mSavedState = state;
1495     }
1496
1497     /**
1498      * @return TRUE if succeed in saving the state.
1499      */
1500     boolean saveState() {
1501         // If the WebView is null it means we ran low on memory and we already
1502         // stored the saved state in mSavedState.
1503         if (mMainView == null) {
1504             return mSavedState != null;
1505         }
1506
1507         mSavedState = new Bundle();
1508         final WebBackForwardList list = mMainView.saveState(mSavedState);
1509         if (list != null) {
1510             final File f = new File(mActivity.getTabControl().getThumbnailDir(),
1511                     mMainView.hashCode() + "_pic.save");
1512             if (mMainView.savePicture(mSavedState, f)) {
1513                 mSavedState.putString(CURRPICTURE, f.getPath());
1514             }
1515         }
1516
1517         // Store some extra info for displaying the tab in the picker.
1518         final WebHistoryItem item = list != null ? list.getCurrentItem() : null;
1519         populatePickerData(item);
1520
1521         if (mPickerData.mUrl != null) {
1522             mSavedState.putString(CURRURL, mPickerData.mUrl);
1523         }
1524         if (mPickerData.mTitle != null) {
1525             mSavedState.putString(CURRTITLE, mPickerData.mTitle);
1526         }
1527         mSavedState.putBoolean(CLOSEONEXIT, mCloseOnExit);
1528         if (mAppId != null) {
1529             mSavedState.putString(APPID, mAppId);
1530         }
1531         if (mOriginalUrl != null) {
1532             mSavedState.putString(ORIGINALURL, mOriginalUrl);
1533         }
1534         // Remember the parent tab so the relationship can be restored.
1535         if (mParentTab != null) {
1536             mSavedState.putInt(PARENTTAB, mActivity.getTabControl().getTabIndex(
1537                     mParentTab));
1538         }
1539         return true;
1540     }
1541
1542     /*
1543      * Restore the state of the tab.
1544      */
1545     boolean restoreState(Bundle b) {
1546         if (b == null) {
1547             return false;
1548         }
1549         // Restore the internal state even if the WebView fails to restore.
1550         // This will maintain the app id, original url and close-on-exit values.
1551         mSavedState = null;
1552         mPickerData = null;
1553         mCloseOnExit = b.getBoolean(CLOSEONEXIT);
1554         mAppId = b.getString(APPID);
1555         mOriginalUrl = b.getString(ORIGINALURL);
1556
1557         final WebBackForwardList list = mMainView.restoreState(b);
1558         if (list == null) {
1559             return false;
1560         }
1561         if (b.containsKey(CURRPICTURE)) {
1562             final File f = new File(b.getString(CURRPICTURE));
1563             mMainView.restorePicture(b, f);
1564             f.delete();
1565         }
1566         return true;
1567     }
1568 }