OSDN Git Service

refactor draghandler dispatch in about:debug.drag#
[android-x86/packages-apps-Browser.git] / src / com / android / browser / BrowserActivity.java
1 /*
2  * Copyright (C) 2006 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 android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.app.SearchManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentResolver;
27 import android.content.ContentUris;
28 import android.content.ContentValues;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.pm.ResolveInfo;
36 import android.content.res.Configuration;
37 import android.content.res.Resources;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Canvas;
42 import android.graphics.Picture;
43 import android.graphics.PixelFormat;
44 import android.graphics.Rect;
45 import android.graphics.drawable.Drawable;
46 import android.net.ConnectivityManager;
47 import android.net.Uri;
48 import android.net.WebAddress;
49 import android.net.http.SslCertificate;
50 import android.net.http.SslError;
51 import android.os.AsyncTask;
52 import android.os.Bundle;
53 import android.os.Debug;
54 import android.os.Environment;
55 import android.os.Handler;
56 import android.os.Message;
57 import android.os.PowerManager;
58 import android.os.Process;
59 import android.os.ServiceManager;
60 import android.os.SystemClock;
61 import android.provider.Browser;
62 import android.provider.ContactsContract;
63 import android.provider.ContactsContract.Intents.Insert;
64 import android.provider.Downloads;
65 import android.provider.MediaStore;
66 import android.text.IClipboard;
67 import android.text.TextUtils;
68 import android.text.format.DateFormat;
69 import android.util.AttributeSet;
70 import android.util.Log;
71 import android.view.ContextMenu;
72 import android.view.Gravity;
73 import android.view.KeyEvent;
74 import android.view.LayoutInflater;
75 import android.view.Menu;
76 import android.view.MenuInflater;
77 import android.view.MenuItem;
78 import android.view.View;
79 import android.view.ViewGroup;
80 import android.view.Window;
81 import android.view.WindowManager;
82 import android.view.ContextMenu.ContextMenuInfo;
83 import android.view.MenuItem.OnMenuItemClickListener;
84 import android.webkit.CookieManager;
85 import android.webkit.CookieSyncManager;
86 import android.webkit.DownloadListener;
87 import android.webkit.HttpAuthHandler;
88 import android.webkit.PluginManager;
89 import android.webkit.SslErrorHandler;
90 import android.webkit.URLUtil;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebChromeClient;
93 import android.webkit.WebHistoryItem;
94 import android.webkit.WebIconDatabase;
95 import android.webkit.WebView;
96 import android.widget.EditText;
97 import android.widget.FrameLayout;
98 import android.widget.LinearLayout;
99 import android.widget.TextView;
100 import android.widget.Toast;
101 import android.accounts.Account;
102 import android.accounts.AccountManager;
103 import android.accounts.AccountManagerFuture;
104 import android.accounts.AuthenticatorException;
105 import android.accounts.OperationCanceledException;
106 import android.accounts.AccountManagerCallback;
107
108 import com.android.common.Patterns;
109
110 import com.google.android.googlelogin.GoogleLoginServiceConstants;
111
112 import java.io.ByteArrayOutputStream;
113 import java.io.File;
114 import java.io.IOException;
115 import java.io.InputStream;
116 import java.net.MalformedURLException;
117 import java.net.URI;
118 import java.net.URISyntaxException;
119 import java.net.URL;
120 import java.net.URLEncoder;
121 import java.text.ParseException;
122 import java.util.Date;
123 import java.util.HashMap;
124 import java.util.regex.Matcher;
125 import java.util.regex.Pattern;
126
127 public class BrowserActivity extends Activity
128     implements View.OnCreateContextMenuListener, DownloadListener,
129         AccountManagerCallback<Account[]> {
130
131     /* Define some aliases to make these debugging flags easier to refer to.
132      * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133      */
134     private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135     private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136     private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
138     // These are single-character shortcuts for searching popular sources.
139     private static final int SHORTCUT_INVALID = 0;
140     private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141     private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142     private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143     private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
145     private Account[] mAccountsGoogle;
146     private Account[] mAccountsPreferHosted;
147
148     private void startReadOfGoogleAccounts() {
149         mAccountsGoogle = null;
150         mAccountsPreferHosted = null;
151
152         AccountManager.get(this).getAccountsByTypeAndFeatures(
153                 GoogleLoginServiceConstants.ACCOUNT_TYPE,
154                 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
155                 this, null);
156     }
157
158     /** This implements AccountManagerCallback<Account[]> */
159     public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
160         try {
161             if (mAccountsGoogle == null) {
162                 mAccountsGoogle = accountManagerFuture.getResult();
163
164                 AccountManager.get(this).getAccountsByTypeAndFeatures(
165                         GoogleLoginServiceConstants.ACCOUNT_TYPE,
166                         new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
167                         this, null);
168             } else {
169                 mAccountsPreferHosted = accountManagerFuture.getResult();
170                 setupHomePage();
171             }
172         } catch (OperationCanceledException e) {
173             setupHomePage();
174         } catch (IOException e) {
175             setupHomePage();
176         } catch (AuthenticatorException e) {
177             setupHomePage();
178         }
179     }
180
181     private void setupHomePage() {
182         // get the default home page
183         String homepage = mSettings.getHomePage();
184
185         if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
186             // three cases:
187             //
188             //   hostedUser == googleUser
189             //      The device has only a google account
190             //
191             //   hostedUser != googleUser
192             //      The device has a hosted account and a google account
193             //
194             //   hostedUser != null, googleUser == null
195             //      The device has only a hosted account (so far)
196             String hostedUser = mAccountsPreferHosted.length == 0 
197                     ? null
198                     : mAccountsPreferHosted[0].name;
199             String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
200
201             // developers might have no accounts at all
202             if (hostedUser == null) return;
203
204             if (googleUser == null || !hostedUser.equals(googleUser)) {
205                 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
206                 homepage = homepage.replace("?", "/a/" + domain + "?");
207             }
208         }
209
210         mSettings.setHomePage(BrowserActivity.this, homepage);
211         resumeAfterCredentials();
212     }
213
214     private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
215         @Override
216         public Void doInBackground(File... files) {
217             if (files != null) {
218                 for (File f : files) {
219                     if (!f.delete()) {
220                       Log.e(LOGTAG, f.getPath() + " was not deleted");
221                     }
222                 }
223             }
224             return null;
225         }
226     }
227
228     /**
229      * This layout holds everything you see below the status bar, including the
230      * error console, the custom view container, and the webviews.
231      */
232     private FrameLayout mBrowserFrameLayout;
233
234     @Override
235     public void onCreate(Bundle icicle) {
236         if (LOGV_ENABLED) {
237             Log.v(LOGTAG, this + " onStart");
238         }
239         super.onCreate(icicle);
240         // test the browser in OpenGL
241         // requestWindowFeature(Window.FEATURE_OPENGL);
242
243         setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
244
245         mResolver = getContentResolver();
246
247         // If this was a web search request, pass it on to the default web
248         // search provider and finish this activity.
249         if (handleWebSearchIntent(getIntent())) {
250             finish();
251             return;
252         }
253
254         mSecLockIcon = Resources.getSystem().getDrawable(
255                 android.R.drawable.ic_secure);
256         mMixLockIcon = Resources.getSystem().getDrawable(
257                 android.R.drawable.ic_partial_secure);
258
259         FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
260                 .findViewById(com.android.internal.R.id.content);
261         mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
262                 .inflate(R.layout.custom_screen, null);
263         mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
264                 R.id.main_content);
265         mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
266                 .findViewById(R.id.error_console);
267         mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
268                 .findViewById(R.id.fullscreen_custom_content);
269         frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
270         mTitleBar = new TitleBar(this);
271         mFakeTitleBar = new TitleBar(this);
272
273         // Create the tab control and our initial tab
274         mTabControl = new TabControl(this);
275
276         // Open the icon database and retain all the bookmark urls for favicons
277         retainIconsOnStartup();
278
279         // Keep a settings instance handy.
280         mSettings = BrowserSettings.getInstance();
281         mSettings.setTabControl(mTabControl);
282         mSettings.loadFromDb(this);
283
284         PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
285         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
286
287         /* enables registration for changes in network status from
288            http stack */
289         mNetworkStateChangedFilter = new IntentFilter();
290         mNetworkStateChangedFilter.addAction(
291                 ConnectivityManager.CONNECTIVITY_ACTION);
292         mNetworkStateIntentReceiver = new BroadcastReceiver() {
293                 @Override
294                 public void onReceive(Context context, Intent intent) {
295                     if (intent.getAction().equals(
296                             ConnectivityManager.CONNECTIVITY_ACTION)) {
297                         boolean noConnectivity = intent.getBooleanExtra(
298                                 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
299                         onNetworkToggle(!noConnectivity);
300                     }
301                 }
302             };
303
304         IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
305         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
306         filter.addDataScheme("package");
307         mPackageInstallationReceiver = new BroadcastReceiver() {
308             @Override
309             public void onReceive(Context context, Intent intent) {
310                 final String action = intent.getAction();
311                 final String packageName = intent.getData()
312                         .getSchemeSpecificPart();
313                 final boolean replacing = intent.getBooleanExtra(
314                         Intent.EXTRA_REPLACING, false);
315                 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
316                     // if it is replacing, refreshPlugins() when adding
317                     return;
318                 }
319                 PackageManager pm = BrowserActivity.this.getPackageManager();
320                 PackageInfo pkgInfo = null;
321                 try {
322                     pkgInfo = pm.getPackageInfo(packageName,
323                             PackageManager.GET_PERMISSIONS);
324                 } catch (PackageManager.NameNotFoundException e) {
325                     return;
326                 }
327                 if (pkgInfo != null) {
328                     String permissions[] = pkgInfo.requestedPermissions;
329                     if (permissions == null) {
330                         return;
331                     }
332                     boolean permissionOk = false;
333                     for (String permit : permissions) {
334                         if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
335                             permissionOk = true;
336                             break;
337                         }
338                     }
339                     if (permissionOk) {
340                         PluginManager.getInstance(BrowserActivity.this)
341                                 .refreshPlugins(
342                                         Intent.ACTION_PACKAGE_ADDED
343                                                 .equals(action));
344                     }
345                 }
346             }
347         };
348         registerReceiver(mPackageInstallationReceiver, filter);
349
350         if (!mTabControl.restoreState(icicle)) {
351             // clear up the thumbnail directory if we can't restore the state as
352             // none of the files in the directory are referenced any more.
353             new ClearThumbnails().execute(
354                     mTabControl.getThumbnailDir().listFiles());
355             // there is no quit on Android. But if we can't restore the state,
356             // we can treat it as a new Browser, remove the old session cookies.
357             CookieManager.getInstance().removeSessionCookie();
358             final Intent intent = getIntent();
359             final Bundle extra = intent.getExtras();
360             // Create an initial tab.
361             // If the intent is ACTION_VIEW and data is not null, the Browser is
362             // invoked to view the content by another application. In this case,
363             // the tab will be close when exit.
364             UrlData urlData = getUrlDataFromIntent(intent);
365
366             final Tab t = mTabControl.createNewTab(
367                     Intent.ACTION_VIEW.equals(intent.getAction()) &&
368                     intent.getData() != null,
369                     intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
370             mTabControl.setCurrentTab(t);
371             attachTabToContentView(t);
372             WebView webView = t.getWebView();
373             if (extra != null) {
374                 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
375                 if (scale > 0 && scale <= 1000) {
376                     webView.setInitialScale(scale);
377                 }
378             }
379             // If we are not restoring from an icicle, then there is a high
380             // likely hood this is the first run. So, check to see if the
381             // homepage needs to be configured and copy any plugins from our
382             // asset directory to the data partition.
383             if ((extra == null || !extra.getBoolean("testing"))
384                     && !mSettings.isLoginInitialized()) {
385                 startReadOfGoogleAccounts();
386             }
387
388             if (urlData.isEmpty()) {
389                 if (mSettings.isLoginInitialized()) {
390                     webView.loadUrl(mSettings.getHomePage());
391                 } else {
392                     waitForCredentials();
393                 }
394             } else {
395                 if (extra != null) {
396                     urlData.setPostData(extra
397                             .getByteArray(Browser.EXTRA_POST_DATA));
398                 }
399                 urlData.loadIn(webView);
400             }
401         } else {
402             // TabControl.restoreState() will create a new tab even if
403             // restoring the state fails.
404             attachTabToContentView(mTabControl.getCurrentTab());
405         }
406
407         // Read JavaScript flags if it exists.
408         String jsFlags = mSettings.getJsFlags();
409         if (jsFlags.trim().length() != 0) {
410             mTabControl.getCurrentWebView().setJsFlags(jsFlags);
411         }
412     }
413
414     @Override
415     protected void onNewIntent(Intent intent) {
416         Tab current = mTabControl.getCurrentTab();
417         // When a tab is closed on exit, the current tab index is set to -1.
418         // Reset before proceed as Browser requires the current tab to be set.
419         if (current == null) {
420             // Try to reset the tab in case the index was incorrect.
421             current = mTabControl.getTab(0);
422             if (current == null) {
423                 // No tabs at all so just ignore this intent.
424                 return;
425             }
426             mTabControl.setCurrentTab(current);
427             attachTabToContentView(current);
428             resetTitleAndIcon(current.getWebView());
429         }
430         final String action = intent.getAction();
431         final int flags = intent.getFlags();
432         if (Intent.ACTION_MAIN.equals(action) ||
433                 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
434             // just resume the browser
435             return;
436         }
437         if (Intent.ACTION_VIEW.equals(action)
438                 || Intent.ACTION_SEARCH.equals(action)
439                 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
440                 || Intent.ACTION_WEB_SEARCH.equals(action)) {
441             // If this was a search request (e.g. search query directly typed into the address bar),
442             // pass it on to the default web search provider.
443             if (handleWebSearchIntent(intent)) {
444                 return;
445             }
446
447             UrlData urlData = getUrlDataFromIntent(intent);
448             if (urlData.isEmpty()) {
449                 urlData = new UrlData(mSettings.getHomePage());
450             }
451             urlData.setPostData(intent
452                     .getByteArrayExtra(Browser.EXTRA_POST_DATA));
453
454             final String appId = intent
455                     .getStringExtra(Browser.EXTRA_APPLICATION_ID);
456             if (Intent.ACTION_VIEW.equals(action)
457                     && !getPackageName().equals(appId)
458                     && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
459                 Tab appTab = mTabControl.getTabFromId(appId);
460                 if (appTab != null) {
461                     Log.i(LOGTAG, "Reusing tab for " + appId);
462                     // Dismiss the subwindow if applicable.
463                     dismissSubWindow(appTab);
464                     // Since we might kill the WebView, remove it from the
465                     // content view first.
466                     removeTabFromContentView(appTab);
467                     // Recreate the main WebView after destroying the old one.
468                     // If the WebView has the same original url and is on that
469                     // page, it can be reused.
470                     boolean needsLoad =
471                             mTabControl.recreateWebView(appTab, urlData.mUrl);
472
473                     if (current != appTab) {
474                         switchToTab(mTabControl.getTabIndex(appTab));
475                         if (needsLoad) {
476                             urlData.loadIn(appTab.getWebView());
477                         }
478                     } else {
479                         // If the tab was the current tab, we have to attach
480                         // it to the view system again.
481                         attachTabToContentView(appTab);
482                         if (needsLoad) {
483                             urlData.loadIn(appTab.getWebView());
484                         }
485                     }
486                     return;
487                 } else {
488                     // No matching application tab, try to find a regular tab
489                     // with a matching url.
490                     appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
491                     if (appTab != null) {
492                         if (current != appTab) {
493                             switchToTab(mTabControl.getTabIndex(appTab));
494                         }
495                         // Otherwise, we are already viewing the correct tab.
496                     } else {
497                         // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
498                         // will be opened in a new tab unless we have reached
499                         // MAX_TABS. Then the url will be opened in the current
500                         // tab. If a new tab is created, it will have "true" for
501                         // exit on close.
502                         openTabAndShow(urlData, true, appId);
503                     }
504                 }
505             } else {
506                 if (!urlData.isEmpty()
507                         && urlData.mUrl.startsWith("about:debug")) {
508                     if ("about:debug.dom".equals(urlData.mUrl)) {
509                         current.getWebView().dumpDomTree(false);
510                     } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
511                         current.getWebView().dumpDomTree(true);
512                     } else if ("about:debug.render".equals(urlData.mUrl)) {
513                         current.getWebView().dumpRenderTree(false);
514                     } else if ("about:debug.render.file".equals(urlData.mUrl)) {
515                         current.getWebView().dumpRenderTree(true);
516                     } else if ("about:debug.display".equals(urlData.mUrl)) {
517                         current.getWebView().dumpDisplayTree();
518                     } else if (urlData.mUrl.startsWith("about:debug.drag")) {
519                         int index = urlData.mUrl.codePointAt(16) - '0';
520                         if (index <= 0 || index > 9) {
521                             current.getWebView().setDragTracker(null);
522                         } else {
523                             current.getWebView().setDragTracker(new MeshTracker(index));
524                         }
525                     } else {
526                         mSettings.toggleDebugSettings();
527                     }
528                     return;
529                 }
530                 // Get rid of the subwindow if it exists
531                 dismissSubWindow(current);
532                 urlData.loadIn(current.getWebView());
533             }
534         }
535     }
536
537     private int parseUrlShortcut(String url) {
538         if (url == null) return SHORTCUT_INVALID;
539
540         // FIXME: quick search, need to be customized by setting
541         if (url.length() > 2 && url.charAt(1) == ' ') {
542             switch (url.charAt(0)) {
543             case 'g': return SHORTCUT_GOOGLE_SEARCH;
544             case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
545             case 'd': return SHORTCUT_DICTIONARY_SEARCH;
546             case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
547             }
548         }
549         return SHORTCUT_INVALID;
550     }
551
552     /**
553      * Launches the default web search activity with the query parameters if the given intent's data
554      * are identified as plain search terms and not URLs/shortcuts.
555      * @return true if the intent was handled and web search activity was launched, false if not.
556      */
557     private boolean handleWebSearchIntent(Intent intent) {
558         if (intent == null) return false;
559
560         String url = null;
561         final String action = intent.getAction();
562         if (Intent.ACTION_VIEW.equals(action)) {
563             Uri data = intent.getData();
564             if (data != null) url = data.toString();
565         } else if (Intent.ACTION_SEARCH.equals(action)
566                 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
567                 || Intent.ACTION_WEB_SEARCH.equals(action)) {
568             url = intent.getStringExtra(SearchManager.QUERY);
569         }
570         return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
571                 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
572     }
573
574     /**
575      * Launches the default web search activity with the query parameters if the given url string
576      * was identified as plain search terms and not URL/shortcut.
577      * @return true if the request was handled and web search activity was launched, false if not.
578      */
579     private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
580         if (inUrl == null) return false;
581
582         // In general, we shouldn't modify URL from Intent.
583         // But currently, we get the user-typed URL from search box as well.
584         String url = fixUrl(inUrl).trim();
585
586         // URLs and site specific search shortcuts are handled by the regular flow of control, so
587         // return early.
588         if (Patterns.WEB_URL.matcher(url).matches()
589                 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
590                 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
591             return false;
592         }
593
594         Browser.updateVisitedHistory(mResolver, url, false);
595         Browser.addSearchUrl(mResolver, url);
596
597         Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
598         intent.addCategory(Intent.CATEGORY_DEFAULT);
599         intent.putExtra(SearchManager.QUERY, url);
600         if (appData != null) {
601             intent.putExtra(SearchManager.APP_DATA, appData);
602         }
603         if (extraData != null) {
604             intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
605         }
606         intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
607         startActivity(intent);
608
609         return true;
610     }
611
612     private UrlData getUrlDataFromIntent(Intent intent) {
613         String url = null;
614         if (intent != null) {
615             final String action = intent.getAction();
616             if (Intent.ACTION_VIEW.equals(action)) {
617                 url = smartUrlFilter(intent.getData());
618                 if (url != null && url.startsWith("content:")) {
619                     /* Append mimetype so webview knows how to display */
620                     String mimeType = intent.resolveType(getContentResolver());
621                     if (mimeType != null) {
622                         url += "?" + mimeType;
623                     }
624                 }
625                 if ("inline:".equals(url)) {
626                     return new InlinedUrlData(
627                             intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
628                             intent.getType(),
629                             intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
630                             intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
631                 }
632             } else if (Intent.ACTION_SEARCH.equals(action)
633                     || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
634                     || Intent.ACTION_WEB_SEARCH.equals(action)) {
635                 url = intent.getStringExtra(SearchManager.QUERY);
636                 if (url != null) {
637                     mLastEnteredUrl = url;
638                     Browser.updateVisitedHistory(mResolver, url, false);
639                     // In general, we shouldn't modify URL from Intent.
640                     // But currently, we get the user-typed URL from search box as well.
641                     url = fixUrl(url);
642                     url = smartUrlFilter(url);
643                     String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
644                     if (url.contains(searchSource)) {
645                         String source = null;
646                         final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
647                         if (appData != null) {
648                             source = appData.getString(SearchManager.SOURCE);
649                         }
650                         if (TextUtils.isEmpty(source)) {
651                             source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
652                         }
653                         url = url.replace(searchSource, "&source=android-"+source+"&");
654                     }
655                 }
656             }
657         }
658         return new UrlData(url);
659     }
660
661     /* package */ static String fixUrl(String inUrl) {
662         // FIXME: Converting the url to lower case
663         // duplicates functionality in smartUrlFilter().
664         // However, changing all current callers of fixUrl to
665         // call smartUrlFilter in addition may have unwanted
666         // consequences, and is deferred for now.
667         int colon = inUrl.indexOf(':');
668         boolean allLower = true;
669         for (int index = 0; index < colon; index++) {
670             char ch = inUrl.charAt(index);
671             if (!Character.isLetter(ch)) {
672                 break;
673             }
674             allLower &= Character.isLowerCase(ch);
675             if (index == colon - 1 && !allLower) {
676                 inUrl = inUrl.substring(0, colon).toLowerCase()
677                         + inUrl.substring(colon);
678             }
679         }
680         if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
681             return inUrl;
682         if (inUrl.startsWith("http:") ||
683                 inUrl.startsWith("https:")) {
684             if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
685                 inUrl = inUrl.replaceFirst("/", "//");
686             } else inUrl = inUrl.replaceFirst(":", "://");
687         }
688         return inUrl;
689     }
690
691     @Override
692     protected void onResume() {
693         super.onResume();
694         if (LOGV_ENABLED) {
695             Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
696         }
697
698         if (!mActivityInPause) {
699             Log.e(LOGTAG, "BrowserActivity is already resumed.");
700             return;
701         }
702
703         mTabControl.resumeCurrentTab();
704         mActivityInPause = false;
705         resumeWebViewTimers();
706
707         if (mWakeLock.isHeld()) {
708             mHandler.removeMessages(RELEASE_WAKELOCK);
709             mWakeLock.release();
710         }
711
712         if (mCredsDlg != null) {
713             if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
714              // In case credential request never comes back
715                 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
716             }
717         }
718
719         registerReceiver(mNetworkStateIntentReceiver,
720                          mNetworkStateChangedFilter);
721         WebView.enablePlatformNotifications();
722     }
723
724     /**
725      * Since the actual title bar is embedded in the WebView, and removing it
726      * would change its appearance, use a different TitleBar to show overlayed
727      * at the top of the screen, when the menu is open or the page is loading.
728      */
729     private TitleBar mFakeTitleBar;
730
731     /**
732      * Holder for the fake title bar.  It will have a foreground shadow, as well
733      * as a white background, so the fake title bar looks like the real one.
734      */
735     private ViewGroup mFakeTitleBarHolder;
736
737     /**
738      * Layout parameters for the fake title bar within mFakeTitleBarHolder
739      */
740     private FrameLayout.LayoutParams mFakeTitleBarParams
741             = new FrameLayout.LayoutParams(
742             ViewGroup.LayoutParams.MATCH_PARENT,
743             ViewGroup.LayoutParams.WRAP_CONTENT);
744     /**
745      * Keeps track of whether the options menu is open.  This is important in
746      * determining whether to show or hide the title bar overlay.
747      */
748     private boolean mOptionsMenuOpen;
749
750     /**
751      * Only meaningful when mOptionsMenuOpen is true.  This variable keeps track
752      * of whether the configuration has changed.  The first onMenuOpened call
753      * after a configuration change is simply a reopening of the same menu
754      * (i.e. mIconView did not change).
755      */
756     private boolean mConfigChanged;
757
758     /**
759      * Whether or not the options menu is in its smaller, icon menu form.  When
760      * true, we want the title bar overlay to be up.  When false, we do not.
761      * Only meaningful if mOptionsMenuOpen is true.
762      */
763     private boolean mIconView;
764
765     @Override
766     public boolean onMenuOpened(int featureId, Menu menu) {
767         if (Window.FEATURE_OPTIONS_PANEL == featureId) {
768             if (mOptionsMenuOpen) {
769                 if (mConfigChanged) {
770                     // We do not need to make any changes to the state of the
771                     // title bar, since the only thing that happened was a
772                     // change in orientation
773                     mConfigChanged = false;
774                 } else {
775                     if (mIconView) {
776                         // Switching the menu to expanded view, so hide the
777                         // title bar.
778                         hideFakeTitleBar();
779                         mIconView = false;
780                     } else {
781                         // Switching the menu back to icon view, so show the
782                         // title bar once again.
783                         showFakeTitleBar();
784                         mIconView = true;
785                     }
786                 }
787             } else {
788                 // The options menu is closed, so open it, and show the title
789                 showFakeTitleBar();
790                 mOptionsMenuOpen = true;
791                 mConfigChanged = false;
792                 mIconView = true;
793             }
794         }
795         return true;
796     }
797
798     /**
799      * Special class used exclusively for the shadow drawn underneath the fake
800      * title bar.  The shadow does not need to be drawn if the WebView
801      * underneath is scrolled to the top, because it will draw directly on top
802      * of the embedded shadow.
803      */
804     private static class Shadow extends View {
805         private WebView mWebView;
806
807         public Shadow(Context context, AttributeSet attrs) {
808             super(context, attrs);
809         }
810
811         public void setWebView(WebView view) {
812             mWebView = view;
813         }
814
815         @Override
816         public void draw(Canvas canvas) {
817             // In general onDraw is the method to override, but we care about
818             // whether or not the background gets drawn, which happens in draw()
819             if (mWebView == null || mWebView.getScrollY() > getHeight()) {
820                 super.draw(canvas);
821             }
822             // Need to invalidate so that if the scroll position changes, we
823             // still draw as appropriate.
824             invalidate();
825         }
826     }
827
828     private void showFakeTitleBar() {
829         final View decor = getWindow().peekDecorView();
830         if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
831                 && !mActivityInPause && decor != null
832                 && decor.getWindowToken() != null) {
833             Rect visRect = new Rect();
834             if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
835                 if (LOGD_ENABLED) {
836                     Log.d(LOGTAG, "showFakeTitleBar visRect failed");
837                 }
838                 return;
839             }
840
841             WindowManager manager
842                     = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
843
844             // Add the title bar to the window manager so it can receive touches
845             // while the menu is up
846             WindowManager.LayoutParams params
847                     = new WindowManager.LayoutParams(
848                     ViewGroup.LayoutParams.MATCH_PARENT,
849                     ViewGroup.LayoutParams.WRAP_CONTENT,
850                     WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
851                     WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
852                     PixelFormat.TRANSLUCENT);
853             params.gravity = Gravity.TOP;
854             WebView mainView = mTabControl.getCurrentWebView();
855             boolean atTop = mainView != null && mainView.getScrollY() == 0;
856             params.windowAnimations = atTop ? 0 : R.style.TitleBar;
857             // XXX : Without providing an offset, the fake title bar will be
858             // placed underneath the status bar.  Use the global visible rect
859             // of mBrowserFrameLayout to determine the bottom of the status bar
860             params.y = visRect.top;
861             // Add a holder for the title bar.  It also holds a shadow to show
862             // below the title bar.
863             if (mFakeTitleBarHolder == null) {
864                 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
865                     .inflate(R.layout.title_bar_bg, null);
866             }
867             Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
868                     R.id.shadow);
869             shadow.setWebView(mainView);
870             mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
871             manager.addView(mFakeTitleBarHolder, params);
872         }
873     }
874
875     @Override
876     public void onOptionsMenuClosed(Menu menu) {
877         mOptionsMenuOpen = false;
878         if (!mInLoad) {
879             hideFakeTitleBar();
880         } else if (!mIconView) {
881             // The page is currently loading, and we are in expanded mode, so
882             // we were not showing the menu.  Show it once again.  It will be
883             // removed when the page finishes.
884             showFakeTitleBar();
885         }
886     }
887
888     private void hideFakeTitleBar() {
889         if (mFakeTitleBar.getParent() == null) return;
890         WindowManager.LayoutParams params = (WindowManager.LayoutParams)
891                 mFakeTitleBarHolder.getLayoutParams();
892         WebView mainView = mTabControl.getCurrentWebView();
893         // Although we decided whether or not to animate based on the current
894         // scroll position, the scroll position may have changed since the
895         // fake title bar was displayed.  Make sure it has the appropriate
896         // animation/lack thereof before removing.
897         params.windowAnimations = mainView != null && mainView.getScrollY() == 0
898                 ? 0 : R.style.TitleBar;
899         WindowManager manager
900                     = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
901         manager.updateViewLayout(mFakeTitleBarHolder, params);
902         mFakeTitleBarHolder.removeView(mFakeTitleBar);
903         manager.removeView(mFakeTitleBarHolder);
904     }
905
906     /**
907      * Special method for the fake title bar to call when displaying its context
908      * menu, since it is in its own Window, and its parent does not show a
909      * context menu.
910      */
911     /* package */ void showTitleBarContextMenu() {
912         if (null == mTitleBar.getParent()) {
913             return;
914         }
915         openContextMenu(mTitleBar);
916     }
917
918     @Override
919     public void onContextMenuClosed(Menu menu) {
920         super.onContextMenuClosed(menu);
921         if (mInLoad) {
922             showFakeTitleBar();
923         }
924     }
925
926     /**
927      *  onSaveInstanceState(Bundle map)
928      *  onSaveInstanceState is called right before onStop(). The map contains
929      *  the saved state.
930      */
931     @Override
932     protected void onSaveInstanceState(Bundle outState) {
933         if (LOGV_ENABLED) {
934             Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
935         }
936         // the default implementation requires each view to have an id. As the
937         // browser handles the state itself and it doesn't use id for the views,
938         // don't call the default implementation. Otherwise it will trigger the
939         // warning like this, "couldn't save which view has focus because the
940         // focused view XXX has no id".
941
942         // Save all the tabs
943         mTabControl.saveState(outState);
944     }
945
946     @Override
947     protected void onPause() {
948         super.onPause();
949
950         if (mActivityInPause) {
951             Log.e(LOGTAG, "BrowserActivity is already paused.");
952             return;
953         }
954
955         mTabControl.pauseCurrentTab();
956         mActivityInPause = true;
957         if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
958             mWakeLock.acquire();
959             mHandler.sendMessageDelayed(mHandler
960                     .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
961         }
962
963         // Clear the credentials toast if it is up
964         if (mCredsDlg != null && mCredsDlg.isShowing()) {
965             mCredsDlg.dismiss();
966         }
967         mCredsDlg = null;
968
969         // FIXME: This removes the active tabs page and resets the menu to
970         // MAIN_MENU.  A better solution might be to do this work in onNewIntent
971         // but then we would need to save it in onSaveInstanceState and restore
972         // it in onCreate/onRestoreInstanceState
973         if (mActiveTabsPage != null) {
974             removeActiveTabPage(true);
975         }
976
977         cancelStopToast();
978
979         // unregister network state listener
980         unregisterReceiver(mNetworkStateIntentReceiver);
981         WebView.disablePlatformNotifications();
982     }
983
984     @Override
985     protected void onDestroy() {
986         if (LOGV_ENABLED) {
987             Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988         }
989         super.onDestroy();
990
991         if (mUploadMessage != null) {
992             mUploadMessage.onReceiveValue(null);
993             mUploadMessage = null;
994         }
995
996         if (mTabControl == null) return;
997
998         // Remove the fake title bar if it is there
999         hideFakeTitleBar();
1000
1001         // Remove the current tab and sub window
1002         Tab t = mTabControl.getCurrentTab();
1003         if (t != null) {
1004             dismissSubWindow(t);
1005             removeTabFromContentView(t);
1006         }
1007         // Destroy all the tabs
1008         mTabControl.destroy();
1009         WebIconDatabase.getInstance().close();
1010
1011         unregisterReceiver(mPackageInstallationReceiver);
1012     }
1013
1014     @Override
1015     public void onConfigurationChanged(Configuration newConfig) {
1016         mConfigChanged = true;
1017         super.onConfigurationChanged(newConfig);
1018
1019         if (mPageInfoDialog != null) {
1020             mPageInfoDialog.dismiss();
1021             showPageInfo(
1022                 mPageInfoView,
1023                 mPageInfoFromShowSSLCertificateOnError);
1024         }
1025         if (mSSLCertificateDialog != null) {
1026             mSSLCertificateDialog.dismiss();
1027             showSSLCertificate(
1028                 mSSLCertificateView);
1029         }
1030         if (mSSLCertificateOnErrorDialog != null) {
1031             mSSLCertificateOnErrorDialog.dismiss();
1032             showSSLCertificateOnError(
1033                 mSSLCertificateOnErrorView,
1034                 mSSLCertificateOnErrorHandler,
1035                 mSSLCertificateOnErrorError);
1036         }
1037         if (mHttpAuthenticationDialog != null) {
1038             String title = ((TextView) mHttpAuthenticationDialog
1039                     .findViewById(com.android.internal.R.id.alertTitle)).getText()
1040                     .toString();
1041             String name = ((TextView) mHttpAuthenticationDialog
1042                     .findViewById(R.id.username_edit)).getText().toString();
1043             String password = ((TextView) mHttpAuthenticationDialog
1044                     .findViewById(R.id.password_edit)).getText().toString();
1045             int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1046                     .getId();
1047             mHttpAuthenticationDialog.dismiss();
1048             showHttpAuthentication(mHttpAuthHandler, null, null, title,
1049                     name, password, focusId);
1050         }
1051     }
1052
1053     @Override
1054     public void onLowMemory() {
1055         super.onLowMemory();
1056         mTabControl.freeMemory();
1057     }
1058
1059     private boolean resumeWebViewTimers() {
1060         Tab tab = mTabControl.getCurrentTab();
1061         boolean inLoad = tab.inLoad();
1062         if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1063             CookieSyncManager.getInstance().startSync();
1064             WebView w = tab.getWebView();
1065             if (w != null) {
1066                 w.resumeTimers();
1067             }
1068             return true;
1069         } else {
1070             return false;
1071         }
1072     }
1073
1074     private boolean pauseWebViewTimers() {
1075         Tab tab = mTabControl.getCurrentTab();
1076         boolean inLoad = tab.inLoad();
1077         if (mActivityInPause && !inLoad) {
1078             CookieSyncManager.getInstance().stopSync();
1079             WebView w = mTabControl.getCurrentWebView();
1080             if (w != null) {
1081                 w.pauseTimers();
1082             }
1083             return true;
1084         } else {
1085             return false;
1086         }
1087     }
1088
1089     // FIXME: Do we want to call this when loading google for the first time?
1090     /*
1091      * This function is called when we are launching for the first time. We
1092      * are waiting for the login credentials before loading Google home
1093      * pages. This way the user will be logged in straight away.
1094      */
1095     private void waitForCredentials() {
1096         // Show a toast
1097         mCredsDlg = new ProgressDialog(this);
1098         mCredsDlg.setIndeterminate(true);
1099         mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1100         // If the user cancels the operation, then cancel the Google
1101         // Credentials request.
1102         mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1103         mCredsDlg.show();
1104
1105         // We set a timeout for the retrieval of credentials in onResume()
1106         // as that is when we have freed up some CPU time to get
1107         // the login credentials.
1108     }
1109
1110     /*
1111      * If we have received the credentials or we have timed out and we are
1112      * showing the credentials dialog, then it is time to move on.
1113      */
1114     private void resumeAfterCredentials() {
1115         if (mCredsDlg == null) {
1116             return;
1117         }
1118
1119         // Clear the toast
1120         if (mCredsDlg.isShowing()) {
1121             mCredsDlg.dismiss();
1122         }
1123         mCredsDlg = null;
1124
1125         // Clear any pending timeout
1126         mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1127
1128         // Load the page
1129         WebView w = mTabControl.getCurrentWebView();
1130         if (w != null) {
1131             w.loadUrl(mSettings.getHomePage());
1132         }
1133
1134         // Update the settings, need to do this last as it can take a moment
1135         // to persist the settings. In the mean time we could be loading
1136         // content.
1137         mSettings.setLoginInitialized(this);
1138     }
1139
1140     // Open the icon database and retain all the icons for visited sites.
1141     private void retainIconsOnStartup() {
1142         final WebIconDatabase db = WebIconDatabase.getInstance();
1143         db.open(getDir("icons", 0).getPath());
1144         try {
1145             Cursor c = Browser.getAllBookmarks(mResolver);
1146             if (!c.moveToFirst()) {
1147                 c.deactivate();
1148                 return;
1149             }
1150             int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1151             do {
1152                 String url = c.getString(urlIndex);
1153                 db.retainIconForPageUrl(url);
1154             } while (c.moveToNext());
1155             c.deactivate();
1156         } catch (IllegalStateException e) {
1157             Log.e(LOGTAG, "retainIconsOnStartup", e);
1158         }
1159     }
1160
1161     // Helper method for getting the top window.
1162     WebView getTopWindow() {
1163         return mTabControl.getCurrentTopWebView();
1164     }
1165
1166     TabControl getTabControl() {
1167         return mTabControl;
1168     }
1169
1170     @Override
1171     public boolean onCreateOptionsMenu(Menu menu) {
1172         super.onCreateOptionsMenu(menu);
1173
1174         MenuInflater inflater = getMenuInflater();
1175         inflater.inflate(R.menu.browser, menu);
1176         mMenu = menu;
1177         updateInLoadMenuItems();
1178         return true;
1179     }
1180
1181     /**
1182      * As the menu can be open when loading state changes
1183      * we must manually update the state of the stop/reload menu
1184      * item
1185      */
1186     private void updateInLoadMenuItems() {
1187         if (mMenu == null) {
1188             return;
1189         }
1190         MenuItem src = mInLoad ?
1191                 mMenu.findItem(R.id.stop_menu_id):
1192                     mMenu.findItem(R.id.reload_menu_id);
1193         MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1194         dest.setIcon(src.getIcon());
1195         dest.setTitle(src.getTitle());
1196     }
1197
1198     @Override
1199     public boolean onContextItemSelected(MenuItem item) {
1200         // chording is not an issue with context menus, but we use the same
1201         // options selector, so set mCanChord to true so we can access them.
1202         mCanChord = true;
1203         int id = item.getItemId();
1204         switch (id) {
1205             // For the context menu from the title bar
1206             case R.id.title_bar_share_page_url:
1207             case R.id.title_bar_copy_page_url:
1208                 WebView mainView = mTabControl.getCurrentWebView();
1209                 if (null == mainView) {
1210                     return false;
1211                 }
1212                 if (id == R.id.title_bar_share_page_url) {
1213                     Browser.sendString(this, mainView.getUrl());
1214                 } else {
1215                     copy(mainView.getUrl());
1216                 }
1217                 break;
1218             // -- Browser context menu
1219             case R.id.open_context_menu_id:
1220             case R.id.open_newtab_context_menu_id:
1221             case R.id.bookmark_context_menu_id:
1222             case R.id.save_link_context_menu_id:
1223             case R.id.share_link_context_menu_id:
1224             case R.id.copy_link_context_menu_id:
1225                 final WebView webView = getTopWindow();
1226                 if (null == webView) {
1227                     return false;
1228                 }
1229                 final HashMap hrefMap = new HashMap();
1230                 hrefMap.put("webview", webView);
1231                 final Message msg = mHandler.obtainMessage(
1232                         FOCUS_NODE_HREF, id, 0, hrefMap);
1233                 webView.requestFocusNodeHref(msg);
1234                 break;
1235
1236             default:
1237                 // For other context menus
1238                 return onOptionsItemSelected(item);
1239         }
1240         mCanChord = false;
1241         return true;
1242     }
1243
1244     private Bundle createGoogleSearchSourceBundle(String source) {
1245         Bundle bundle = new Bundle();
1246         bundle.putString(SearchManager.SOURCE, source);
1247         return bundle;
1248     }
1249
1250     /**
1251      * Overriding this to insert a local information bundle
1252      */
1253     @Override
1254     public boolean onSearchRequested() {
1255         if (mOptionsMenuOpen) closeOptionsMenu();
1256         String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1257         startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1258                 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1259         return true;
1260     }
1261
1262     @Override
1263     public void startSearch(String initialQuery, boolean selectInitialQuery,
1264             Bundle appSearchData, boolean globalSearch) {
1265         if (appSearchData == null) {
1266             appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1267         }
1268         super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1269     }
1270
1271     /**
1272      * Switch tabs.  Called by the TitleBarSet when sliding the title bar
1273      * results in changing tabs.
1274      * @param index Index of the tab to change to, as defined by
1275      *              mTabControl.getTabIndex(Tab t).
1276      * @return boolean True if we successfully switched to a different tab.  If
1277      *                 the indexth tab is null, or if that tab is the same as
1278      *                 the current one, return false.
1279      */
1280     /* package */ boolean switchToTab(int index) {
1281         Tab tab = mTabControl.getTab(index);
1282         Tab currentTab = mTabControl.getCurrentTab();
1283         if (tab == null || tab == currentTab) {
1284             return false;
1285         }
1286         if (currentTab != null) {
1287             // currentTab may be null if it was just removed.  In that case,
1288             // we do not need to remove it
1289             removeTabFromContentView(currentTab);
1290         }
1291         mTabControl.setCurrentTab(tab);
1292         attachTabToContentView(tab);
1293         resetTitleIconAndProgress();
1294         updateLockIconToLatest();
1295         return true;
1296     }
1297
1298     /* package */ Tab openTabToHomePage() {
1299         return openTabAndShow(mSettings.getHomePage(), false, null);
1300     }
1301
1302     /* package */ void closeCurrentWindow() {
1303         final Tab current = mTabControl.getCurrentTab();
1304         if (mTabControl.getTabCount() == 1) {
1305             // This is the last tab.  Open a new one, with the home
1306             // page and close the current one.
1307             openTabToHomePage();
1308             closeTab(current);
1309             return;
1310         }
1311         final Tab parent = current.getParentTab();
1312         int indexToShow = -1;
1313         if (parent != null) {
1314             indexToShow = mTabControl.getTabIndex(parent);
1315         } else {
1316             final int currentIndex = mTabControl.getCurrentIndex();
1317             // Try to move to the tab to the right
1318             indexToShow = currentIndex + 1;
1319             if (indexToShow > mTabControl.getTabCount() - 1) {
1320                 // Try to move to the tab to the left
1321                 indexToShow = currentIndex - 1;
1322             }
1323         }
1324         if (switchToTab(indexToShow)) {
1325             // Close window
1326             closeTab(current);
1327         }
1328     }
1329
1330     private ActiveTabsPage mActiveTabsPage;
1331
1332     /**
1333      * Remove the active tabs page.
1334      * @param needToAttach If true, the active tabs page did not attach a tab
1335      *                     to the content view, so we need to do that here.
1336      */
1337     /* package */ void removeActiveTabPage(boolean needToAttach) {
1338         mContentView.removeView(mActiveTabsPage);
1339         mActiveTabsPage = null;
1340         mMenuState = R.id.MAIN_MENU;
1341         if (needToAttach) {
1342             attachTabToContentView(mTabControl.getCurrentTab());
1343         }
1344         getTopWindow().requestFocus();
1345     }
1346
1347     @Override
1348     public boolean onOptionsItemSelected(MenuItem item) {
1349         if (!mCanChord) {
1350             // The user has already fired a shortcut with this hold down of the
1351             // menu key.
1352             return false;
1353         }
1354         if (null == getTopWindow()) {
1355             return false;
1356         }
1357         if (mMenuIsDown) {
1358             // The shortcut action consumes the MENU. Even if it is still down,
1359             // it won't trigger the next shortcut action. In the case of the
1360             // shortcut action triggering a new activity, like Bookmarks, we
1361             // won't get onKeyUp for MENU. So it is important to reset it here.
1362             mMenuIsDown = false;
1363         }
1364         switch (item.getItemId()) {
1365             // -- Main menu
1366             case R.id.new_tab_menu_id:
1367                 openTabToHomePage();
1368                 break;
1369
1370             case R.id.goto_menu_id:
1371                 onSearchRequested();
1372                 break;
1373
1374             case R.id.bookmarks_menu_id:
1375                 bookmarksOrHistoryPicker(false);
1376                 break;
1377
1378             case R.id.active_tabs_menu_id:
1379                 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1380                 removeTabFromContentView(mTabControl.getCurrentTab());
1381                 hideFakeTitleBar();
1382                 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1383                 mActiveTabsPage.requestFocus();
1384                 mMenuState = EMPTY_MENU;
1385                 break;
1386
1387             case R.id.add_bookmark_menu_id:
1388                 Intent i = new Intent(BrowserActivity.this,
1389                         AddBookmarkPage.class);
1390                 WebView w = getTopWindow();
1391                 i.putExtra("url", w.getUrl());
1392                 i.putExtra("title", w.getTitle());
1393                 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1394                 i.putExtra("thumbnail", createScreenshot(w));
1395                 startActivity(i);
1396                 break;
1397
1398             case R.id.stop_reload_menu_id:
1399                 if (mInLoad) {
1400                     stopLoading();
1401                 } else {
1402                     getTopWindow().reload();
1403                 }
1404                 break;
1405
1406             case R.id.back_menu_id:
1407                 getTopWindow().goBack();
1408                 break;
1409
1410             case R.id.forward_menu_id:
1411                 getTopWindow().goForward();
1412                 break;
1413
1414             case R.id.close_menu_id:
1415                 // Close the subwindow if it exists.
1416                 if (mTabControl.getCurrentSubWindow() != null) {
1417                     dismissSubWindow(mTabControl.getCurrentTab());
1418                     break;
1419                 }
1420                 closeCurrentWindow();
1421                 break;
1422
1423             case R.id.homepage_menu_id:
1424                 Tab current = mTabControl.getCurrentTab();
1425                 if (current != null) {
1426                     dismissSubWindow(current);
1427                     current.getWebView().loadUrl(mSettings.getHomePage());
1428                 }
1429                 break;
1430
1431             case R.id.preferences_menu_id:
1432                 Intent intent = new Intent(this,
1433                         BrowserPreferencesPage.class);
1434                 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1435                         getTopWindow().getUrl());
1436                 startActivityForResult(intent, PREFERENCES_PAGE);
1437                 break;
1438
1439             case R.id.find_menu_id:
1440                 if (null == mFindDialog) {
1441                     mFindDialog = new FindDialog(this);
1442                 }
1443                 mFindDialog.setWebView(getTopWindow());
1444                 mFindDialog.show();
1445                 mMenuState = EMPTY_MENU;
1446                 break;
1447
1448             case R.id.select_text_id:
1449                 getTopWindow().emulateShiftHeld();
1450                 break;
1451             case R.id.page_info_menu_id:
1452                 showPageInfo(mTabControl.getCurrentTab(), false);
1453                 break;
1454
1455             case R.id.classic_history_menu_id:
1456                 bookmarksOrHistoryPicker(true);
1457                 break;
1458
1459             case R.id.share_page_menu_id:
1460                 Browser.sendString(this, getTopWindow().getUrl(),
1461                         getText(R.string.choosertitle_sharevia).toString());
1462                 break;
1463
1464             case R.id.dump_nav_menu_id:
1465                 getTopWindow().debugDump();
1466                 break;
1467
1468             case R.id.zoom_in_menu_id:
1469                 getTopWindow().zoomIn();
1470                 break;
1471
1472             case R.id.zoom_out_menu_id:
1473                 getTopWindow().zoomOut();
1474                 break;
1475
1476             case R.id.view_downloads_menu_id:
1477                 viewDownloads(null);
1478                 break;
1479
1480             case R.id.window_one_menu_id:
1481             case R.id.window_two_menu_id:
1482             case R.id.window_three_menu_id:
1483             case R.id.window_four_menu_id:
1484             case R.id.window_five_menu_id:
1485             case R.id.window_six_menu_id:
1486             case R.id.window_seven_menu_id:
1487             case R.id.window_eight_menu_id:
1488                 {
1489                     int menuid = item.getItemId();
1490                     for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1491                         if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1492                             Tab desiredTab = mTabControl.getTab(id);
1493                             if (desiredTab != null &&
1494                                     desiredTab != mTabControl.getCurrentTab()) {
1495                                 switchToTab(id);
1496                             }
1497                             break;
1498                         }
1499                     }
1500                 }
1501                 break;
1502
1503             default:
1504                 if (!super.onOptionsItemSelected(item)) {
1505                     return false;
1506                 }
1507                 // Otherwise fall through.
1508         }
1509         mCanChord = false;
1510         return true;
1511     }
1512
1513     public void closeFind() {
1514         mMenuState = R.id.MAIN_MENU;
1515     }
1516
1517     @Override
1518     public boolean onPrepareOptionsMenu(Menu menu) {
1519         // This happens when the user begins to hold down the menu key, so
1520         // allow them to chord to get a shortcut.
1521         mCanChord = true;
1522         // Note: setVisible will decide whether an item is visible; while
1523         // setEnabled() will decide whether an item is enabled, which also means
1524         // whether the matching shortcut key will function.
1525         super.onPrepareOptionsMenu(menu);
1526         switch (mMenuState) {
1527             case EMPTY_MENU:
1528                 if (mCurrentMenuState != mMenuState) {
1529                     menu.setGroupVisible(R.id.MAIN_MENU, false);
1530                     menu.setGroupEnabled(R.id.MAIN_MENU, false);
1531                     menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1532                 }
1533                 break;
1534             default:
1535                 if (mCurrentMenuState != mMenuState) {
1536                     menu.setGroupVisible(R.id.MAIN_MENU, true);
1537                     menu.setGroupEnabled(R.id.MAIN_MENU, true);
1538                     menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1539                 }
1540                 final WebView w = getTopWindow();
1541                 boolean canGoBack = false;
1542                 boolean canGoForward = false;
1543                 boolean isHome = false;
1544                 if (w != null) {
1545                     canGoBack = w.canGoBack();
1546                     canGoForward = w.canGoForward();
1547                     isHome = mSettings.getHomePage().equals(w.getUrl());
1548                 }
1549                 final MenuItem back = menu.findItem(R.id.back_menu_id);
1550                 back.setEnabled(canGoBack);
1551
1552                 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1553                 home.setEnabled(!isHome);
1554
1555                 menu.findItem(R.id.forward_menu_id)
1556                         .setEnabled(canGoForward);
1557
1558                 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1559                         mTabControl.canCreateNewTab());
1560
1561                 // decide whether to show the share link option
1562                 PackageManager pm = getPackageManager();
1563                 Intent send = new Intent(Intent.ACTION_SEND);
1564                 send.setType("text/plain");
1565                 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1566                 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1567
1568                 boolean isNavDump = mSettings.isNavDump();
1569                 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1570                 nav.setVisible(isNavDump);
1571                 nav.setEnabled(isNavDump);
1572                 break;
1573         }
1574         mCurrentMenuState = mMenuState;
1575         return true;
1576     }
1577
1578     @Override
1579     public void onCreateContextMenu(ContextMenu menu, View v,
1580             ContextMenuInfo menuInfo) {
1581         WebView webview = (WebView) v;
1582         WebView.HitTestResult result = webview.getHitTestResult();
1583         if (result == null) {
1584             return;
1585         }
1586
1587         int type = result.getType();
1588         if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1589             Log.w(LOGTAG,
1590                     "We should not show context menu when nothing is touched");
1591             return;
1592         }
1593         if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1594             // let TextView handles context menu
1595             return;
1596         }
1597
1598         // Note, http://b/issue?id=1106666 is requesting that
1599         // an inflated menu can be used again. This is not available
1600         // yet, so inflate each time (yuk!)
1601         MenuInflater inflater = getMenuInflater();
1602         inflater.inflate(R.menu.browsercontext, menu);
1603
1604         // Show the correct menu group
1605         String extra = result.getExtra();
1606         menu.setGroupVisible(R.id.PHONE_MENU,
1607                 type == WebView.HitTestResult.PHONE_TYPE);
1608         menu.setGroupVisible(R.id.EMAIL_MENU,
1609                 type == WebView.HitTestResult.EMAIL_TYPE);
1610         menu.setGroupVisible(R.id.GEO_MENU,
1611                 type == WebView.HitTestResult.GEO_TYPE);
1612         menu.setGroupVisible(R.id.IMAGE_MENU,
1613                 type == WebView.HitTestResult.IMAGE_TYPE
1614                 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1615         menu.setGroupVisible(R.id.ANCHOR_MENU,
1616                 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1617                 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1618
1619         // Setup custom handling depending on the type
1620         switch (type) {
1621             case WebView.HitTestResult.PHONE_TYPE:
1622                 menu.setHeaderTitle(Uri.decode(extra));
1623                 menu.findItem(R.id.dial_context_menu_id).setIntent(
1624                         new Intent(Intent.ACTION_VIEW, Uri
1625                                 .parse(WebView.SCHEME_TEL + extra)));
1626                 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1627                 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1628                 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1629                 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1630                         addIntent);
1631                 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1632                         new Copy(extra));
1633                 break;
1634
1635             case WebView.HitTestResult.EMAIL_TYPE:
1636                 menu.setHeaderTitle(extra);
1637                 menu.findItem(R.id.email_context_menu_id).setIntent(
1638                         new Intent(Intent.ACTION_VIEW, Uri
1639                                 .parse(WebView.SCHEME_MAILTO + extra)));
1640                 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1641                         new Copy(extra));
1642                 break;
1643
1644             case WebView.HitTestResult.GEO_TYPE:
1645                 menu.setHeaderTitle(extra);
1646                 menu.findItem(R.id.map_context_menu_id).setIntent(
1647                         new Intent(Intent.ACTION_VIEW, Uri
1648                                 .parse(WebView.SCHEME_GEO
1649                                         + URLEncoder.encode(extra))));
1650                 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1651                         new Copy(extra));
1652                 break;
1653
1654             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1655             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1656                 TextView titleView = (TextView) LayoutInflater.from(this)
1657                         .inflate(android.R.layout.browser_link_context_header,
1658                         null);
1659                 titleView.setText(extra);
1660                 menu.setHeaderView(titleView);
1661                 // decide whether to show the open link in new tab option
1662                 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1663                         mTabControl.canCreateNewTab());
1664                 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1665                         Bookmarks.urlHasAcceptableScheme(extra));
1666                 PackageManager pm = getPackageManager();
1667                 Intent send = new Intent(Intent.ACTION_SEND);
1668                 send.setType("text/plain");
1669                 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1670                 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1671                 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1672                     break;
1673                 }
1674                 // otherwise fall through to handle image part
1675             case WebView.HitTestResult.IMAGE_TYPE:
1676                 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1677                     menu.setHeaderTitle(extra);
1678                 }
1679                 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1680                         new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1681                 menu.findItem(R.id.download_context_menu_id).
1682                         setOnMenuItemClickListener(new Download(extra));
1683                 menu.findItem(R.id.set_wallpaper_context_menu_id).
1684                         setOnMenuItemClickListener(new SetAsWallpaper(extra));
1685                 break;
1686
1687             default:
1688                 Log.w(LOGTAG, "We should not get here.");
1689                 break;
1690         }
1691         hideFakeTitleBar();
1692     }
1693
1694     // Attach the given tab to the content view.
1695     // this should only be called for the current tab.
1696     private void attachTabToContentView(Tab t) {
1697         // Attach the container that contains the main WebView and any other UI
1698         // associated with the tab.
1699         t.attachTabToContentView(mContentView);
1700
1701         if (mShouldShowErrorConsole) {
1702             ErrorConsoleView errorConsole = t.getErrorConsole(true);
1703             if (errorConsole.numberOfErrors() == 0) {
1704                 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1705             } else {
1706                 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1707             }
1708
1709             mErrorConsoleContainer.addView(errorConsole,
1710                     new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1711                                                   ViewGroup.LayoutParams.WRAP_CONTENT));
1712         }
1713
1714         WebView view = t.getWebView();
1715         view.setEmbeddedTitleBar(mTitleBar);
1716         // Request focus on the top window.
1717         t.getTopWindow().requestFocus();
1718     }
1719
1720     // Attach a sub window to the main WebView of the given tab.
1721     void attachSubWindow(Tab t) {
1722         t.attachSubWindow(mContentView);
1723         getTopWindow().requestFocus();
1724     }
1725
1726     // Remove the given tab from the content view.
1727     private void removeTabFromContentView(Tab t) {
1728         // Remove the container that contains the main WebView.
1729         t.removeTabFromContentView(mContentView);
1730
1731         ErrorConsoleView errorConsole = t.getErrorConsole(false);
1732         if (errorConsole != null) {
1733             mErrorConsoleContainer.removeView(errorConsole);
1734         }
1735
1736         WebView view = t.getWebView();
1737         if (view != null) {
1738             view.setEmbeddedTitleBar(null);
1739         }
1740     }
1741
1742     // Remove the sub window if it exists. Also called by TabControl when the
1743     // user clicks the 'X' to dismiss a sub window.
1744     /* package */ void dismissSubWindow(Tab t) {
1745         t.removeSubWindow(mContentView);
1746         // dismiss the subwindow. This will destroy the WebView.
1747         t.dismissSubWindow();
1748         getTopWindow().requestFocus();
1749     }
1750
1751     // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1752     // that accepts url as string.
1753     private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1754         return openTabAndShow(new UrlData(url), closeOnExit, appId);
1755     }
1756
1757     // This method does a ton of stuff. It will attempt to create a new tab
1758     // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1759     // url isn't null, it will load the given url.
1760     /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1761             String appId) {
1762         final Tab currentTab = mTabControl.getCurrentTab();
1763         if (mTabControl.canCreateNewTab()) {
1764             final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1765                     urlData.mUrl);
1766             WebView webview = tab.getWebView();
1767             // If the last tab was removed from the active tabs page, currentTab
1768             // will be null.
1769             if (currentTab != null) {
1770                 removeTabFromContentView(currentTab);
1771             }
1772             // We must set the new tab as the current tab to reflect the old
1773             // animation behavior.
1774             mTabControl.setCurrentTab(tab);
1775             attachTabToContentView(tab);
1776             if (!urlData.isEmpty()) {
1777                 urlData.loadIn(webview);
1778             }
1779             return tab;
1780         } else {
1781             // Get rid of the subwindow if it exists
1782             dismissSubWindow(currentTab);
1783             if (!urlData.isEmpty()) {
1784                 // Load the given url.
1785                 urlData.loadIn(currentTab.getWebView());
1786             }
1787         }
1788         return currentTab;
1789     }
1790
1791     private Tab openTab(String url) {
1792         if (mSettings.openInBackground()) {
1793             Tab t = mTabControl.createNewTab();
1794             if (t != null) {
1795                 WebView view = t.getWebView();
1796                 view.loadUrl(url);
1797             }
1798             return t;
1799         } else {
1800             return openTabAndShow(url, false, null);
1801         }
1802     }
1803
1804     private class Copy implements OnMenuItemClickListener {
1805         private CharSequence mText;
1806
1807         public boolean onMenuItemClick(MenuItem item) {
1808             copy(mText);
1809             return true;
1810         }
1811
1812         public Copy(CharSequence toCopy) {
1813             mText = toCopy;
1814         }
1815     }
1816
1817     private class Download implements OnMenuItemClickListener {
1818         private String mText;
1819
1820         public boolean onMenuItemClick(MenuItem item) {
1821             onDownloadStartNoStream(mText, null, null, null, -1);
1822             return true;
1823         }
1824
1825         public Download(String toDownload) {
1826             mText = toDownload;
1827         }
1828     }
1829
1830     private class SetAsWallpaper extends Thread implements
1831             OnMenuItemClickListener, DialogInterface.OnCancelListener {
1832         private URL mUrl;
1833         private ProgressDialog mWallpaperProgress;
1834         private boolean mCanceled = false;
1835
1836         public SetAsWallpaper(String url) {
1837             try {
1838                 mUrl = new URL(url);
1839             } catch (MalformedURLException e) {
1840                 mUrl = null;
1841             }
1842         }
1843
1844         public void onCancel(DialogInterface dialog) {
1845             mCanceled = true;
1846         }
1847
1848         public boolean onMenuItemClick(MenuItem item) {
1849             if (mUrl != null) {
1850                 // The user may have tried to set a image with a large file size as their
1851                 // background so it may take a few moments to perform the operation. Display
1852                 // a progress spinner while it is working.
1853                 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1854                 mWallpaperProgress.setIndeterminate(true);
1855                 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1856                 mWallpaperProgress.setCancelable(true);
1857                 mWallpaperProgress.setOnCancelListener(this);
1858                 mWallpaperProgress.show();
1859                 start();
1860             }
1861             return true;
1862         }
1863
1864         public void run() {
1865             Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1866             try {
1867                 // TODO: This will cause the resource to be downloaded again, when we
1868                 // should in most cases be able to grab it from the cache. To fix this
1869                 // we should query WebCore to see if we can access a cached version and
1870                 // instead open an input stream on that. This pattern could also be used
1871                 // in the download manager where the same problem exists.
1872                 InputStream inputstream = mUrl.openStream();
1873                 if (inputstream != null) {
1874                     setWallpaper(inputstream);
1875                 }
1876             } catch (IOException e) {
1877                 Log.e(LOGTAG, "Unable to set new wallpaper");
1878                 // Act as though the user canceled the operation so we try to
1879                 // restore the old wallpaper.
1880                 mCanceled = true;
1881             }
1882
1883             if (mCanceled) {
1884                 // Restore the old wallpaper if the user cancelled whilst we were setting
1885                 // the new wallpaper.
1886                 int width = oldWallpaper.getIntrinsicWidth();
1887                 int height = oldWallpaper.getIntrinsicHeight();
1888                 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1889                 Canvas canvas = new Canvas(bm);
1890                 oldWallpaper.setBounds(0, 0, width, height);
1891                 oldWallpaper.draw(canvas);
1892                 try {
1893                     setWallpaper(bm);
1894                 } catch (IOException e) {
1895                     Log.e(LOGTAG, "Unable to restore old wallpaper.");
1896                 }
1897                 mCanceled = false;
1898             }
1899
1900             if (mWallpaperProgress.isShowing()) {
1901                 mWallpaperProgress.dismiss();
1902             }
1903         }
1904     }
1905
1906     private void copy(CharSequence text) {
1907         try {
1908             IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1909             if (clip != null) {
1910                 clip.setClipboardText(text);
1911             }
1912         } catch (android.os.RemoteException e) {
1913             Log.e(LOGTAG, "Copy failed", e);
1914         }
1915     }
1916
1917     /**
1918      * Resets the browser title-view to whatever it must be
1919      * (for example, if we had a loading error)
1920      * When we have a new page, we call resetTitle, when we
1921      * have to reset the titlebar to whatever it used to be
1922      * (for example, if the user chose to stop loading), we
1923      * call resetTitleAndRevertLockIcon.
1924      */
1925     /* package */ void resetTitleAndRevertLockIcon() {
1926         mTabControl.getCurrentTab().revertLockIcon();
1927         updateLockIconToLatest();
1928         resetTitleIconAndProgress();
1929     }
1930
1931     /**
1932      * Reset the title, favicon, and progress.
1933      */
1934     private void resetTitleIconAndProgress() {
1935         WebView current = mTabControl.getCurrentWebView();
1936         if (current == null) {
1937             return;
1938         }
1939         resetTitleAndIcon(current);
1940         int progress = current.getProgress();
1941         current.getWebChromeClient().onProgressChanged(current, progress);
1942     }
1943
1944     // Reset the title and the icon based on the given item.
1945     private void resetTitleAndIcon(WebView view) {
1946         WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1947         if (item != null) {
1948             setUrlTitle(item.getUrl(), item.getTitle());
1949             setFavicon(item.getFavicon());
1950         } else {
1951             setUrlTitle(null, null);
1952             setFavicon(null);
1953         }
1954     }
1955
1956     /**
1957      * Sets a title composed of the URL and the title string.
1958      * @param url The URL of the site being loaded.
1959      * @param title The title of the site being loaded.
1960      */
1961     void setUrlTitle(String url, String title) {
1962         mUrl = url;
1963         mTitle = title;
1964
1965         mTitleBar.setTitleAndUrl(title, url);
1966         mFakeTitleBar.setTitleAndUrl(title, url);
1967     }
1968
1969     /**
1970      * @param url The URL to build a title version of the URL from.
1971      * @return The title version of the URL or null if fails.
1972      * The title version of the URL can be either the URL hostname,
1973      * or the hostname with an "https://" prefix (for secure URLs),
1974      * or an empty string if, for example, the URL in question is a
1975      * file:// URL with no hostname.
1976      */
1977     /* package */ static String buildTitleUrl(String url) {
1978         String titleUrl = null;
1979
1980         if (url != null) {
1981             try {
1982                 // parse the url string
1983                 URL urlObj = new URL(url);
1984                 if (urlObj != null) {
1985                     titleUrl = "";
1986
1987                     String protocol = urlObj.getProtocol();
1988                     String host = urlObj.getHost();
1989
1990                     if (host != null && 0 < host.length()) {
1991                         titleUrl = host;
1992                         if (protocol != null) {
1993                             // if a secure site, add an "https://" prefix!
1994                             if (protocol.equalsIgnoreCase("https")) {
1995                                 titleUrl = protocol + "://" + host;
1996                             }
1997                         }
1998                     }
1999                 }
2000             } catch (MalformedURLException e) {}
2001         }
2002
2003         return titleUrl;
2004     }
2005
2006     // Set the favicon in the title bar.
2007     void setFavicon(Bitmap icon) {
2008         mTitleBar.setFavicon(icon);
2009         mFakeTitleBar.setFavicon(icon);
2010     }
2011
2012     /**
2013      * Close the tab, remove its associated title bar, and adjust mTabControl's
2014      * current tab to a valid value.
2015      */
2016     /* package */ void closeTab(Tab t) {
2017         int currentIndex = mTabControl.getCurrentIndex();
2018         int removeIndex = mTabControl.getTabIndex(t);
2019         mTabControl.removeTab(t);
2020         if (currentIndex >= removeIndex && currentIndex != 0) {
2021             currentIndex--;
2022         }
2023         mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2024         resetTitleIconAndProgress();
2025     }
2026
2027     private void goBackOnePageOrQuit() {
2028         Tab current = mTabControl.getCurrentTab();
2029         if (current == null) {
2030             /*
2031              * Instead of finishing the activity, simply push this to the back
2032              * of the stack and let ActivityManager to choose the foreground
2033              * activity. As BrowserActivity is singleTask, it will be always the
2034              * root of the task. So we can use either true or false for
2035              * moveTaskToBack().
2036              */
2037             moveTaskToBack(true);
2038             return;
2039         }
2040         WebView w = current.getWebView();
2041         if (w.canGoBack()) {
2042             w.goBack();
2043         } else {
2044             // Check to see if we are closing a window that was created by
2045             // another window. If so, we switch back to that window.
2046             Tab parent = current.getParentTab();
2047             if (parent != null) {
2048                 switchToTab(mTabControl.getTabIndex(parent));
2049                 // Now we close the other tab
2050                 closeTab(current);
2051             } else {
2052                 if (current.closeOnExit()) {
2053                     // force the tab's inLoad() to be false as we are going to
2054                     // either finish the activity or remove the tab. This will
2055                     // ensure pauseWebViewTimers() taking action.
2056                     mTabControl.getCurrentTab().clearInLoad();
2057                     if (mTabControl.getTabCount() == 1) {
2058                         finish();
2059                         return;
2060                     }
2061                     // call pauseWebViewTimers() now, we won't be able to call
2062                     // it in onPause() as the WebView won't be valid.
2063                     // Temporarily change mActivityInPause to be true as
2064                     // pauseWebViewTimers() will do nothing if mActivityInPause
2065                     // is false.
2066                     boolean savedState = mActivityInPause;
2067                     if (savedState) {
2068                         Log.e(LOGTAG, "BrowserActivity is already paused "
2069                                 + "while handing goBackOnePageOrQuit.");
2070                     }
2071                     mActivityInPause = true;
2072                     pauseWebViewTimers();
2073                     mActivityInPause = savedState;
2074                     removeTabFromContentView(current);
2075                     mTabControl.removeTab(current);
2076                 }
2077                 /*
2078                  * Instead of finishing the activity, simply push this to the back
2079                  * of the stack and let ActivityManager to choose the foreground
2080                  * activity. As BrowserActivity is singleTask, it will be always the
2081                  * root of the task. So we can use either true or false for
2082                  * moveTaskToBack().
2083                  */
2084                 moveTaskToBack(true);
2085             }
2086         }
2087     }
2088
2089     boolean isMenuDown() {
2090         return mMenuIsDown;
2091     }
2092
2093     @Override
2094     public boolean onKeyDown(int keyCode, KeyEvent event) {
2095         // Even if MENU is already held down, we need to call to super to open
2096         // the IME on long press.
2097         if (KeyEvent.KEYCODE_MENU == keyCode) {
2098             mMenuIsDown = true;
2099             return super.onKeyDown(keyCode, event);
2100         }
2101         // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2102         // still down, we don't want to trigger the search. Pretend to consume
2103         // the key and do nothing.
2104         if (mMenuIsDown) return true;
2105
2106         switch(keyCode) {
2107             case KeyEvent.KEYCODE_SPACE:
2108                 // WebView/WebTextView handle the keys in the KeyDown. As
2109                 // the Activity's shortcut keys are only handled when WebView
2110                 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2111                 if (event.isShiftPressed()) {
2112                     getTopWindow().pageUp(false);
2113                 } else {
2114                     getTopWindow().pageDown(false);
2115                 }
2116                 return true;
2117             case KeyEvent.KEYCODE_BACK:
2118                 if (event.getRepeatCount() == 0) {
2119                     event.startTracking();
2120                     return true;
2121                 } else if (mCustomView == null && mActiveTabsPage == null
2122                         && event.isLongPress()) {
2123                     bookmarksOrHistoryPicker(true);
2124                     return true;
2125                 }
2126                 break;
2127         }
2128         return super.onKeyDown(keyCode, event);
2129     }
2130
2131     @Override
2132     public boolean onKeyUp(int keyCode, KeyEvent event) {
2133         switch(keyCode) {
2134             case KeyEvent.KEYCODE_MENU:
2135                 mMenuIsDown = false;
2136                 break;
2137             case KeyEvent.KEYCODE_BACK:
2138                 if (event.isTracking() && !event.isCanceled()) {
2139                     if (mCustomView != null) {
2140                         // if a custom view is showing, hide it
2141                         mTabControl.getCurrentWebView().getWebChromeClient()
2142                                 .onHideCustomView();
2143                     } else if (mActiveTabsPage != null) {
2144                         // if tab page is showing, hide it
2145                         removeActiveTabPage(true);
2146                     } else {
2147                         WebView subwindow = mTabControl.getCurrentSubWindow();
2148                         if (subwindow != null) {
2149                             if (subwindow.canGoBack()) {
2150                                 subwindow.goBack();
2151                             } else {
2152                                 dismissSubWindow(mTabControl.getCurrentTab());
2153                             }
2154                         } else {
2155                             goBackOnePageOrQuit();
2156                         }
2157                     }
2158                     return true;
2159                 }
2160                 break;
2161         }
2162         return super.onKeyUp(keyCode, event);
2163     }
2164
2165     /* package */ void stopLoading() {
2166         mDidStopLoad = true;
2167         resetTitleAndRevertLockIcon();
2168         WebView w = getTopWindow();
2169         w.stopLoading();
2170         // FIXME: before refactor, it is using mWebViewClient. So I keep the
2171         // same logic here. But for subwindow case, should we call into the main
2172         // WebView's onPageFinished as we never call its onPageStarted and if
2173         // the page finishes itself, we don't call onPageFinished.
2174         mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2175                 w.getUrl());
2176
2177         cancelStopToast();
2178         mStopToast = Toast
2179                 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2180         mStopToast.show();
2181     }
2182
2183     boolean didUserStopLoading() {
2184         return mDidStopLoad;
2185     }
2186
2187     private void cancelStopToast() {
2188         if (mStopToast != null) {
2189             mStopToast.cancel();
2190             mStopToast = null;
2191         }
2192     }
2193
2194     // called by a UI or non-UI thread to post the message
2195     public void postMessage(int what, int arg1, int arg2, Object obj,
2196             long delayMillis) {
2197         mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2198                 obj), delayMillis);
2199     }
2200
2201     // called by a UI or non-UI thread to remove the message
2202     void removeMessages(int what, Object object) {
2203         mHandler.removeMessages(what, object);
2204     }
2205
2206     // public message ids
2207     public final static int LOAD_URL                = 1001;
2208     public final static int STOP_LOAD               = 1002;
2209
2210     // Message Ids
2211     private static final int FOCUS_NODE_HREF         = 102;
2212     private static final int CANCEL_CREDS_REQUEST    = 103;
2213     private static final int RELEASE_WAKELOCK        = 107;
2214
2215     static final int UPDATE_BOOKMARK_THUMBNAIL       = 108;
2216
2217     // Private handler for handling javascript and saving passwords
2218     private Handler mHandler = new Handler() {
2219
2220         public void handleMessage(Message msg) {
2221             switch (msg.what) {
2222                 case FOCUS_NODE_HREF:
2223                 {
2224                     String url = (String) msg.getData().get("url");
2225                     String title = (String) msg.getData().get("title");
2226                     if (url == null || url.length() == 0) {
2227                         break;
2228                     }
2229                     HashMap focusNodeMap = (HashMap) msg.obj;
2230                     WebView view = (WebView) focusNodeMap.get("webview");
2231                     // Only apply the action if the top window did not change.
2232                     if (getTopWindow() != view) {
2233                         break;
2234                     }
2235                     switch (msg.arg1) {
2236                         case R.id.open_context_menu_id:
2237                         case R.id.view_image_context_menu_id:
2238                             loadURL(getTopWindow(), url);
2239                             break;
2240                         case R.id.open_newtab_context_menu_id:
2241                             final Tab parent = mTabControl.getCurrentTab();
2242                             final Tab newTab = openTab(url);
2243                             if (newTab != parent) {
2244                                 parent.addChildTab(newTab);
2245                             }
2246                             break;
2247                         case R.id.bookmark_context_menu_id:
2248                             Intent intent = new Intent(BrowserActivity.this,
2249                                     AddBookmarkPage.class);
2250                             intent.putExtra("url", url);
2251                             intent.putExtra("title", title);
2252                             startActivity(intent);
2253                             break;
2254                         case R.id.share_link_context_menu_id:
2255                             Browser.sendString(BrowserActivity.this, url,
2256                                     getText(R.string.choosertitle_sharevia).toString());
2257                             break;
2258                         case R.id.copy_link_context_menu_id:
2259                             copy(url);
2260                             break;
2261                         case R.id.save_link_context_menu_id:
2262                         case R.id.download_context_menu_id:
2263                             onDownloadStartNoStream(url, null, null, null, -1);
2264                             break;
2265                     }
2266                     break;
2267                 }
2268
2269                 case LOAD_URL:
2270                     loadURL(getTopWindow(), (String) msg.obj);
2271                     break;
2272
2273                 case STOP_LOAD:
2274                     stopLoading();
2275                     break;
2276
2277                 case CANCEL_CREDS_REQUEST:
2278                     resumeAfterCredentials();
2279                     break;
2280
2281                 case RELEASE_WAKELOCK:
2282                     if (mWakeLock.isHeld()) {
2283                         mWakeLock.release();
2284                         // if we reach here, Browser should be still in the
2285                         // background loading after WAKELOCK_TIMEOUT (5-min).
2286                         // To avoid burning the battery, stop loading.
2287                         mTabControl.stopAllLoading();
2288                     }
2289                     break;
2290
2291                 case UPDATE_BOOKMARK_THUMBNAIL:
2292                     WebView view = (WebView) msg.obj;
2293                     if (view != null) {
2294                         updateScreenshot(view);
2295                     }
2296                     break;
2297             }
2298         }
2299     };
2300
2301     private void updateScreenshot(WebView view) {
2302         // If this is a bookmarked site, add a screenshot to the database.
2303         // FIXME: When should we update?  Every time?
2304         // FIXME: Would like to make sure there is actually something to
2305         // draw, but the API for that (WebViewCore.pictureReady()) is not
2306         // currently accessible here.
2307
2308         ContentResolver cr = getContentResolver();
2309         final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2310                 cr, view.getOriginalUrl(), view.getUrl(), true);
2311         if (c != null) {
2312             boolean succeed = c.moveToFirst();
2313             ContentValues values = null;
2314             while (succeed) {
2315                 if (values == null) {
2316                     final ByteArrayOutputStream os
2317                             = new ByteArrayOutputStream();
2318                     Bitmap bm = createScreenshot(view);
2319                     if (bm == null) {
2320                         c.close();
2321                         return;
2322                     }
2323                     bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2324                     values = new ContentValues();
2325                     values.put(Browser.BookmarkColumns.THUMBNAIL,
2326                             os.toByteArray());
2327                 }
2328                 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2329                         c.getInt(0)), values, null, null);
2330                 succeed = c.moveToNext();
2331             }
2332             c.close();
2333         }
2334     }
2335
2336     /**
2337      * Values for the size of the thumbnail created when taking a screenshot.
2338      * Lazily initialized.  Instead of using these directly, use
2339      * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2340      */
2341     private static int THUMBNAIL_WIDTH = 0;
2342     private static int THUMBNAIL_HEIGHT = 0;
2343
2344     /**
2345      * Return the desired width for thumbnail screenshots, which are stored in
2346      * the database, and used on the bookmarks screen.
2347      * @param context Context for finding out the density of the screen.
2348      * @return int desired width for thumbnail screenshot.
2349      */
2350     /* package */ static int getDesiredThumbnailWidth(Context context) {
2351         if (THUMBNAIL_WIDTH == 0) {
2352             float density = context.getResources().getDisplayMetrics().density;
2353             THUMBNAIL_WIDTH = (int) (90 * density);
2354             THUMBNAIL_HEIGHT = (int) (80 * density);
2355         }
2356         return THUMBNAIL_WIDTH;
2357     }
2358
2359     /**
2360      * Return the desired height for thumbnail screenshots, which are stored in
2361      * the database, and used on the bookmarks screen.
2362      * @param context Context for finding out the density of the screen.
2363      * @return int desired height for thumbnail screenshot.
2364      */
2365     /* package */ static int getDesiredThumbnailHeight(Context context) {
2366         // To ensure that they are both initialized.
2367         getDesiredThumbnailWidth(context);
2368         return THUMBNAIL_HEIGHT;
2369     }
2370
2371     private Bitmap createScreenshot(WebView view) {
2372         Picture thumbnail = view.capturePicture();
2373         if (thumbnail == null) {
2374             return null;
2375         }
2376         Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2377                 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2378         Canvas canvas = new Canvas(bm);
2379         // May need to tweak these values to determine what is the
2380         // best scale factor
2381         int thumbnailWidth = thumbnail.getWidth();
2382         int thumbnailHeight = thumbnail.getHeight();
2383         float scaleFactorX = 1.0f;
2384         float scaleFactorY = 1.0f;
2385         if (thumbnailWidth > 0) {
2386             scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2387                     (float)thumbnailWidth;
2388         } else {
2389             return null;
2390         }
2391
2392         if (view.getWidth() > view.getHeight() &&
2393                 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2394             // If the device is in landscape and the page is shorter
2395             // than the height of the view, stretch the thumbnail to fill the
2396             // space.
2397             scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2398                     (float)thumbnailHeight;
2399         } else {
2400             // In the portrait case, this looks nice.
2401             scaleFactorY = scaleFactorX;
2402         }
2403
2404         canvas.scale(scaleFactorX, scaleFactorY);
2405
2406         thumbnail.draw(canvas);
2407         return bm;
2408     }
2409
2410     // -------------------------------------------------------------------------
2411     // Helper function for WebViewClient.
2412     //-------------------------------------------------------------------------
2413
2414     // Use in overrideUrlLoading
2415     /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2416     /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2417     /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2418     /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2419
2420     void onPageStarted(WebView view, String url, Bitmap favicon) {
2421         // when BrowserActivity just starts, onPageStarted may be called before
2422         // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2423         // to start the timer. As we won't switch tabs while an activity is in
2424         // pause state, we can ensure calling resume and pause in pair.
2425         if (mActivityInPause) resumeWebViewTimers();
2426
2427         resetLockIcon(url);
2428         setUrlTitle(url, null);
2429         setFavicon(favicon);
2430         // Keep this initial progress in sync with initialProgressValue (* 100)
2431         // in ProgressTracker.cpp
2432         // Show some progress so that the user knows the page is beginning to
2433         // load
2434         onProgressChanged(view, 10);
2435         mDidStopLoad = false;
2436         if (!mIsNetworkUp) createAndShowNetworkDialog();
2437
2438         if (mSettings.isTracing()) {
2439             String host;
2440             try {
2441                 WebAddress uri = new WebAddress(url);
2442                 host = uri.mHost;
2443             } catch (android.net.ParseException ex) {
2444                 host = "browser";
2445             }
2446             host = host.replace('.', '_');
2447             host += ".trace";
2448             mInTrace = true;
2449             Debug.startMethodTracing(host, 20 * 1024 * 1024);
2450         }
2451
2452         // Performance probe
2453         if (false) {
2454             mStart = SystemClock.uptimeMillis();
2455             mProcessStart = Process.getElapsedCpuTime();
2456             long[] sysCpu = new long[7];
2457             if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2458                     sysCpu, null)) {
2459                 mUserStart = sysCpu[0] + sysCpu[1];
2460                 mSystemStart = sysCpu[2];
2461                 mIdleStart = sysCpu[3];
2462                 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2463             }
2464             mUiStart = SystemClock.currentThreadTimeMillis();
2465         }
2466     }
2467
2468     void onPageFinished(WebView view, String url) {
2469         // Reset the title and icon in case we stopped a provisional load.
2470         resetTitleAndIcon(view);
2471         // Update the lock icon image only once we are done loading
2472         updateLockIconToLatest();
2473         // pause the WebView timer and release the wake lock if it is finished
2474         // while BrowserActivity is in pause state.
2475         if (mActivityInPause && pauseWebViewTimers()) {
2476             if (mWakeLock.isHeld()) {
2477                 mHandler.removeMessages(RELEASE_WAKELOCK);
2478                 mWakeLock.release();
2479             }
2480         }
2481
2482         // Performance probe
2483         if (false) {
2484             long[] sysCpu = new long[7];
2485             if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2486                     sysCpu, null)) {
2487                 String uiInfo = "UI thread used "
2488                         + (SystemClock.currentThreadTimeMillis() - mUiStart)
2489                         + " ms";
2490                 if (LOGD_ENABLED) {
2491                     Log.d(LOGTAG, uiInfo);
2492                 }
2493                 //The string that gets written to the log
2494                 String performanceString = "It took total "
2495                         + (SystemClock.uptimeMillis() - mStart)
2496                         + " ms clock time to load the page."
2497                         + "\nbrowser process used "
2498                         + (Process.getElapsedCpuTime() - mProcessStart)
2499                         + " ms, user processes used "
2500                         + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2501                         + " ms, kernel used "
2502                         + (sysCpu[2] - mSystemStart) * 10
2503                         + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2504                         + " ms and irq took "
2505                         + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2506                         * 10 + " ms, " + uiInfo;
2507                 if (LOGD_ENABLED) {
2508                     Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2509                 }
2510                 if (url != null) {
2511                     // strip the url to maintain consistency
2512                     String newUrl = new String(url);
2513                     if (newUrl.startsWith("http://www.")) {
2514                         newUrl = newUrl.substring(11);
2515                     } else if (newUrl.startsWith("http://")) {
2516                         newUrl = newUrl.substring(7);
2517                     } else if (newUrl.startsWith("https://www.")) {
2518                         newUrl = newUrl.substring(12);
2519                     } else if (newUrl.startsWith("https://")) {
2520                         newUrl = newUrl.substring(8);
2521                     }
2522                     if (LOGD_ENABLED) {
2523                         Log.d(LOGTAG, newUrl + " loaded");
2524                     }
2525                 }
2526             }
2527          }
2528
2529         if (mInTrace) {
2530             mInTrace = false;
2531             Debug.stopMethodTracing();
2532         }
2533     }
2534
2535     boolean shouldOverrideUrlLoading(WebView view, String url) {
2536         if (url.startsWith(SCHEME_WTAI)) {
2537             // wtai://wp/mc;number
2538             // number=string(phone-number)
2539             if (url.startsWith(SCHEME_WTAI_MC)) {
2540                 Intent intent = new Intent(Intent.ACTION_VIEW,
2541                         Uri.parse(WebView.SCHEME_TEL +
2542                         url.substring(SCHEME_WTAI_MC.length())));
2543                 startActivity(intent);
2544                 return true;
2545             }
2546             // wtai://wp/sd;dtmf
2547             // dtmf=string(dialstring)
2548             if (url.startsWith(SCHEME_WTAI_SD)) {
2549                 // TODO: only send when there is active voice connection
2550                 return false;
2551             }
2552             // wtai://wp/ap;number;name
2553             // number=string(phone-number)
2554             // name=string
2555             if (url.startsWith(SCHEME_WTAI_AP)) {
2556                 // TODO
2557                 return false;
2558             }
2559         }
2560
2561         // The "about:" schemes are internal to the browser; don't want these to
2562         // be dispatched to other apps.
2563         if (url.startsWith("about:")) {
2564             return false;
2565         }
2566
2567         Intent intent;
2568         // perform generic parsing of the URI to turn it into an Intent.
2569         try {
2570             intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2571         } catch (URISyntaxException ex) {
2572             Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2573             return false;
2574         }
2575
2576         // check whether the intent can be resolved. If not, we will see
2577         // whether we can download it from the Market.
2578         if (getPackageManager().resolveActivity(intent, 0) == null) {
2579             String packagename = intent.getPackage();
2580             if (packagename != null) {
2581                 intent = new Intent(Intent.ACTION_VIEW, Uri
2582                         .parse("market://search?q=pname:" + packagename));
2583                 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2584                 startActivity(intent);
2585                 return true;
2586             } else {
2587                 return false;
2588             }
2589         }
2590
2591         // sanitize the Intent, ensuring web pages can not bypass browser
2592         // security (only access to BROWSABLE activities).
2593         intent.addCategory(Intent.CATEGORY_BROWSABLE);
2594         intent.setComponent(null);
2595         try {
2596             if (startActivityIfNeeded(intent, -1)) {
2597                 return true;
2598             }
2599         } catch (ActivityNotFoundException ex) {
2600             // ignore the error. If no application can handle the URL,
2601             // eg about:blank, assume the browser can handle it.
2602         }
2603
2604         if (mMenuIsDown) {
2605             openTab(url);
2606             closeOptionsMenu();
2607             return true;
2608         }
2609         return false;
2610     }
2611
2612     // -------------------------------------------------------------------------
2613     // Helper function for WebChromeClient
2614     // -------------------------------------------------------------------------
2615
2616     void onProgressChanged(WebView view, int newProgress) {
2617         mTitleBar.setProgress(newProgress);
2618         mFakeTitleBar.setProgress(newProgress);
2619
2620         if (newProgress == 100) {
2621             // onProgressChanged() may continue to be called after the main
2622             // frame has finished loading, as any remaining sub frames continue
2623             // to load. We'll only get called once though with newProgress as
2624             // 100 when everything is loaded. (onPageFinished is called once
2625             // when the main frame completes loading regardless of the state of
2626             // any sub frames so calls to onProgressChanges may continue after
2627             // onPageFinished has executed)
2628             if (mInLoad) {
2629                 mInLoad = false;
2630                 updateInLoadMenuItems();
2631                 // If the options menu is open, leave the title bar
2632                 if (!mOptionsMenuOpen || !mIconView) {
2633                     hideFakeTitleBar();
2634                 }
2635             }
2636         } else if (!mInLoad) {
2637             // onPageFinished may have already been called but a subframe is
2638             // still loading and updating the progress. Reset mInLoad and update
2639             // the menu items.
2640             mInLoad = true;
2641             updateInLoadMenuItems();
2642             if (!mOptionsMenuOpen || mIconView) {
2643                 // This page has begun to load, so show the title bar
2644                 showFakeTitleBar();
2645             }
2646         }
2647     }
2648
2649     void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2650         // if a view already exists then immediately terminate the new one
2651         if (mCustomView != null) {
2652             callback.onCustomViewHidden();
2653             return;
2654         }
2655
2656         // Add the custom view to its container.
2657         mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2658         mCustomView = view;
2659         mCustomViewCallback = callback;
2660         // Save the menu state and set it to empty while the custom
2661         // view is showing.
2662         mOldMenuState = mMenuState;
2663         mMenuState = EMPTY_MENU;
2664         // Hide the content view.
2665         mContentView.setVisibility(View.GONE);
2666         // Finally show the custom view container.
2667         setStatusBarVisibility(false);
2668         mCustomViewContainer.setVisibility(View.VISIBLE);
2669         mCustomViewContainer.bringToFront();
2670     }
2671
2672     void onHideCustomView() {
2673         if (mCustomView == null)
2674             return;
2675
2676         // Hide the custom view.
2677         mCustomView.setVisibility(View.GONE);
2678         // Remove the custom view from its container.
2679         mCustomViewContainer.removeView(mCustomView);
2680         mCustomView = null;
2681         // Reset the old menu state.
2682         mMenuState = mOldMenuState;
2683         mOldMenuState = EMPTY_MENU;
2684         mCustomViewContainer.setVisibility(View.GONE);
2685         mCustomViewCallback.onCustomViewHidden();
2686         // Show the content view.
2687         setStatusBarVisibility(true);
2688         mContentView.setVisibility(View.VISIBLE);
2689     }
2690
2691     Bitmap getDefaultVideoPoster() {
2692         if (mDefaultVideoPoster == null) {
2693             mDefaultVideoPoster = BitmapFactory.decodeResource(
2694                     getResources(), R.drawable.default_video_poster);
2695         }
2696         return mDefaultVideoPoster;
2697     }
2698
2699     View getVideoLoadingProgressView() {
2700         if (mVideoProgressView == null) {
2701             LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2702             mVideoProgressView = inflater.inflate(
2703                     R.layout.video_loading_progress, null);
2704         }
2705         return mVideoProgressView;
2706     }
2707
2708     /*
2709      * The Object used to inform the WebView of the file to upload.
2710      */
2711     private ValueCallback<Uri> mUploadMessage;
2712
2713     void openFileChooser(ValueCallback<Uri> uploadMsg) {
2714         if (mUploadMessage != null) return;
2715         mUploadMessage = uploadMsg;
2716         Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2717         i.addCategory(Intent.CATEGORY_OPENABLE);
2718         i.setType("*/*");
2719         BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2720                 getString(R.string.choose_upload)), FILE_SELECTED);
2721     }
2722
2723     // -------------------------------------------------------------------------
2724     // Implement functions for DownloadListener
2725     // -------------------------------------------------------------------------
2726
2727     /**
2728      * Notify the host application a download should be done, or that
2729      * the data should be streamed if a streaming viewer is available.
2730      * @param url The full url to the content that should be downloaded
2731      * @param contentDisposition Content-disposition http header, if
2732      *                           present.
2733      * @param mimetype The mimetype of the content reported by the server
2734      * @param contentLength The file size reported by the server
2735      */
2736     public void onDownloadStart(String url, String userAgent,
2737             String contentDisposition, String mimetype, long contentLength) {
2738         // if we're dealing wih A/V content that's not explicitly marked
2739         //     for download, check if it's streamable.
2740         if (contentDisposition == null
2741                 || !contentDisposition.regionMatches(
2742                         true, 0, "attachment", 0, 10)) {
2743             // query the package manager to see if there's a registered handler
2744             //     that matches.
2745             Intent intent = new Intent(Intent.ACTION_VIEW);
2746             intent.setDataAndType(Uri.parse(url), mimetype);
2747             ResolveInfo info = getPackageManager().resolveActivity(intent,
2748                     PackageManager.MATCH_DEFAULT_ONLY);
2749             if (info != null) {
2750                 ComponentName myName = getComponentName();
2751                 // If we resolved to ourselves, we don't want to attempt to
2752                 // load the url only to try and download it again.
2753                 if (!myName.getPackageName().equals(
2754                         info.activityInfo.packageName)
2755                         || !myName.getClassName().equals(
2756                                 info.activityInfo.name)) {
2757                     // someone (other than us) knows how to handle this mime
2758                     // type with this scheme, don't download.
2759                     try {
2760                         startActivity(intent);
2761                         return;
2762                     } catch (ActivityNotFoundException ex) {
2763                         if (LOGD_ENABLED) {
2764                             Log.d(LOGTAG, "activity not found for " + mimetype
2765                                     + " over " + Uri.parse(url).getScheme(),
2766                                     ex);
2767                         }
2768                         // Best behavior is to fall back to a download in this
2769                         // case
2770                     }
2771                 }
2772             }
2773         }
2774         onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2775     }
2776
2777     /**
2778      * Notify the host application a download should be done, even if there
2779      * is a streaming viewer available for thise type.
2780      * @param url The full url to the content that should be downloaded
2781      * @param contentDisposition Content-disposition http header, if
2782      *                           present.
2783      * @param mimetype The mimetype of the content reported by the server
2784      * @param contentLength The file size reported by the server
2785      */
2786     /*package */ void onDownloadStartNoStream(String url, String userAgent,
2787             String contentDisposition, String mimetype, long contentLength) {
2788
2789         String filename = URLUtil.guessFileName(url,
2790                 contentDisposition, mimetype);
2791
2792         // Check to see if we have an SDCard
2793         String status = Environment.getExternalStorageState();
2794         if (!status.equals(Environment.MEDIA_MOUNTED)) {
2795             int title;
2796             String msg;
2797
2798             // Check to see if the SDCard is busy, same as the music app
2799             if (status.equals(Environment.MEDIA_SHARED)) {
2800                 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2801                 title = R.string.download_sdcard_busy_dlg_title;
2802             } else {
2803                 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2804                 title = R.string.download_no_sdcard_dlg_title;
2805             }
2806
2807             new AlertDialog.Builder(this)
2808                 .setTitle(title)
2809                 .setIcon(android.R.drawable.ic_dialog_alert)
2810                 .setMessage(msg)
2811                 .setPositiveButton(R.string.ok, null)
2812                 .show();
2813             return;
2814         }
2815
2816         // java.net.URI is a lot stricter than KURL so we have to undo
2817         // KURL's percent-encoding and redo the encoding using java.net.URI.
2818         URI uri = null;
2819         try {
2820             // Undo the percent-encoding that KURL may have done.
2821             String newUrl = new String(URLUtil.decode(url.getBytes()));
2822             // Parse the url into pieces
2823             WebAddress w = new WebAddress(newUrl);
2824             String frag = null;
2825             String query = null;
2826             String path = w.mPath;
2827             // Break the path into path, query, and fragment
2828             if (path.length() > 0) {
2829                 // Strip the fragment
2830                 int idx = path.lastIndexOf('#');
2831                 if (idx != -1) {
2832                     frag = path.substring(idx + 1);
2833                     path = path.substring(0, idx);
2834                 }
2835                 idx = path.lastIndexOf('?');
2836                 if (idx != -1) {
2837                     query = path.substring(idx + 1);
2838                     path = path.substring(0, idx);
2839                 }
2840             }
2841             uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2842                     query, frag);
2843         } catch (Exception e) {
2844             Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2845             return;
2846         }
2847
2848         // XXX: Have to use the old url since the cookies were stored using the
2849         // old percent-encoded url.
2850         String cookies = CookieManager.getInstance().getCookie(url);
2851
2852         ContentValues values = new ContentValues();
2853         values.put(Downloads.COLUMN_URI, uri.toString());
2854         values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2855         values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2856         values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
2857                 getPackageName());
2858         values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
2859                 BrowserDownloadPage.class.getCanonicalName());
2860         values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2861         values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2862         values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2863         values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
2864         if (contentLength > 0) {
2865             values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
2866         }
2867         if (mimetype == null) {
2868             // We must have long pressed on a link or image to download it. We
2869             // are not sure of the mimetype in this case, so do a head request
2870             new FetchUrlMimeType(this).execute(values);
2871         } else {
2872             final Uri contentUri =
2873                     getContentResolver().insert(Downloads.CONTENT_URI, values);
2874             viewDownloads(contentUri);
2875         }
2876
2877     }
2878
2879     // -------------------------------------------------------------------------
2880
2881     /**
2882      * Resets the lock icon. This method is called when we start a new load and
2883      * know the url to be loaded.
2884      */
2885     private void resetLockIcon(String url) {
2886         // Save the lock-icon state (we revert to it if the load gets cancelled)
2887         mTabControl.getCurrentTab().resetLockIcon(url);
2888         updateLockIconImage(LOCK_ICON_UNSECURE);
2889     }
2890
2891     /**
2892      * Update the lock icon to correspond to our latest state.
2893      */
2894     private void updateLockIconToLatest() {
2895         updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2896     }
2897
2898     /**
2899      * Updates the lock-icon image in the title-bar.
2900      */
2901     private void updateLockIconImage(int lockIconType) {
2902         Drawable d = null;
2903         if (lockIconType == LOCK_ICON_SECURE) {
2904             d = mSecLockIcon;
2905         } else if (lockIconType == LOCK_ICON_MIXED) {
2906             d = mMixLockIcon;
2907         }
2908         mTitleBar.setLock(d);
2909         mFakeTitleBar.setLock(d);
2910     }
2911
2912     /**
2913      * Displays a page-info dialog.
2914      * @param tab The tab to show info about
2915      * @param fromShowSSLCertificateOnError The flag that indicates whether
2916      * this dialog was opened from the SSL-certificate-on-error dialog or
2917      * not. This is important, since we need to know whether to return to
2918      * the parent dialog or simply dismiss.
2919      */
2920     private void showPageInfo(final Tab tab,
2921                               final boolean fromShowSSLCertificateOnError) {
2922         final LayoutInflater factory = LayoutInflater
2923                 .from(this);
2924
2925         final View pageInfoView = factory.inflate(R.layout.page_info, null);
2926
2927         final WebView view = tab.getWebView();
2928
2929         String url = null;
2930         String title = null;
2931
2932         if (view == null) {
2933             url = tab.getUrl();
2934             title = tab.getTitle();
2935         } else if (view == mTabControl.getCurrentWebView()) {
2936              // Use the cached title and url if this is the current WebView
2937             url = mUrl;
2938             title = mTitle;
2939         } else {
2940             url = view.getUrl();
2941             title = view.getTitle();
2942         }
2943
2944         if (url == null) {
2945             url = "";
2946         }
2947         if (title == null) {
2948             title = "";
2949         }
2950
2951         ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2952         ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2953
2954         mPageInfoView = tab;
2955         mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
2956
2957         AlertDialog.Builder alertDialogBuilder =
2958             new AlertDialog.Builder(this)
2959             .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2960             .setView(pageInfoView)
2961             .setPositiveButton(
2962                 R.string.ok,
2963                 new DialogInterface.OnClickListener() {
2964                     public void onClick(DialogInterface dialog,
2965                                         int whichButton) {
2966                         mPageInfoDialog = null;
2967                         mPageInfoView = null;
2968
2969                         // if we came here from the SSL error dialog
2970                         if (fromShowSSLCertificateOnError) {
2971                             // go back to the SSL error dialog
2972                             showSSLCertificateOnError(
2973                                 mSSLCertificateOnErrorView,
2974                                 mSSLCertificateOnErrorHandler,
2975                                 mSSLCertificateOnErrorError);
2976                         }
2977                     }
2978                 })
2979             .setOnCancelListener(
2980                 new DialogInterface.OnCancelListener() {
2981                     public void onCancel(DialogInterface dialog) {
2982                         mPageInfoDialog = null;
2983                         mPageInfoView = null;
2984
2985                         // if we came here from the SSL error dialog
2986                         if (fromShowSSLCertificateOnError) {
2987                             // go back to the SSL error dialog
2988                             showSSLCertificateOnError(
2989                                 mSSLCertificateOnErrorView,
2990                                 mSSLCertificateOnErrorHandler,
2991                                 mSSLCertificateOnErrorError);
2992                         }
2993                     }
2994                 });
2995
2996         // if we have a main top-level page SSL certificate set or a certificate
2997         // error
2998         if (fromShowSSLCertificateOnError ||
2999                 (view != null && view.getCertificate() != null)) {
3000             // add a 'View Certificate' button
3001             alertDialogBuilder.setNeutralButton(
3002                 R.string.view_certificate,
3003                 new DialogInterface.OnClickListener() {
3004                     public void onClick(DialogInterface dialog,
3005                                         int whichButton) {
3006                         mPageInfoDialog = null;
3007                         mPageInfoView = null;
3008
3009                         // if we came here from the SSL error dialog
3010                         if (fromShowSSLCertificateOnError) {
3011                             // go back to the SSL error dialog
3012                             showSSLCertificateOnError(
3013                                 mSSLCertificateOnErrorView,
3014                                 mSSLCertificateOnErrorHandler,
3015                                 mSSLCertificateOnErrorError);
3016                         } else {
3017                             // otherwise, display the top-most certificate from
3018                             // the chain
3019                             if (view.getCertificate() != null) {
3020                                 showSSLCertificate(tab);
3021                             }
3022                         }
3023                     }
3024                 });
3025         }
3026
3027         mPageInfoDialog = alertDialogBuilder.show();
3028     }
3029
3030        /**
3031      * Displays the main top-level page SSL certificate dialog
3032      * (accessible from the Page-Info dialog).
3033      * @param tab The tab to show certificate for.
3034      */
3035     private void showSSLCertificate(final Tab tab) {
3036         final View certificateView =
3037                 inflateCertificateView(tab.getWebView().getCertificate());
3038         if (certificateView == null) {
3039             return;
3040         }
3041
3042         LayoutInflater factory = LayoutInflater.from(this);
3043
3044         final LinearLayout placeholder =
3045                 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3046
3047         LinearLayout ll = (LinearLayout) factory.inflate(
3048             R.layout.ssl_success, placeholder);
3049         ((TextView)ll.findViewById(R.id.success))
3050             .setText(R.string.ssl_certificate_is_valid);
3051
3052         mSSLCertificateView = tab;
3053         mSSLCertificateDialog =
3054             new AlertDialog.Builder(this)
3055                 .setTitle(R.string.ssl_certificate).setIcon(
3056                     R.drawable.ic_dialog_browser_certificate_secure)
3057                 .setView(certificateView)
3058                 .setPositiveButton(R.string.ok,
3059                         new DialogInterface.OnClickListener() {
3060                             public void onClick(DialogInterface dialog,
3061                                     int whichButton) {
3062                                 mSSLCertificateDialog = null;
3063                                 mSSLCertificateView = null;
3064
3065                                 showPageInfo(tab, false);
3066                             }
3067                         })
3068                 .setOnCancelListener(
3069                         new DialogInterface.OnCancelListener() {
3070                             public void onCancel(DialogInterface dialog) {
3071                                 mSSLCertificateDialog = null;
3072                                 mSSLCertificateView = null;
3073
3074                                 showPageInfo(tab, false);
3075                             }
3076                         })
3077                 .show();
3078     }
3079
3080     /**
3081      * Displays the SSL error certificate dialog.
3082      * @param view The target web-view.
3083      * @param handler The SSL error handler responsible for cancelling the
3084      * connection that resulted in an SSL error or proceeding per user request.
3085      * @param error The SSL error object.
3086      */
3087     void showSSLCertificateOnError(
3088         final WebView view, final SslErrorHandler handler, final SslError error) {
3089
3090         final View certificateView =
3091             inflateCertificateView(error.getCertificate());
3092         if (certificateView == null) {
3093             return;
3094         }
3095
3096         LayoutInflater factory = LayoutInflater.from(this);
3097
3098         final LinearLayout placeholder =
3099                 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3100
3101         if (error.hasError(SslError.SSL_UNTRUSTED)) {
3102             LinearLayout ll = (LinearLayout)factory
3103                 .inflate(R.layout.ssl_warning, placeholder);
3104             ((TextView)ll.findViewById(R.id.warning))
3105                 .setText(R.string.ssl_untrusted);
3106         }
3107
3108         if (error.hasError(SslError.SSL_IDMISMATCH)) {
3109             LinearLayout ll = (LinearLayout)factory
3110                 .inflate(R.layout.ssl_warning, placeholder);
3111             ((TextView)ll.findViewById(R.id.warning))
3112                 .setText(R.string.ssl_mismatch);
3113         }
3114
3115         if (error.hasError(SslError.SSL_EXPIRED)) {
3116             LinearLayout ll = (LinearLayout)factory
3117                 .inflate(R.layout.ssl_warning, placeholder);
3118             ((TextView)ll.findViewById(R.id.warning))
3119                 .setText(R.string.ssl_expired);
3120         }
3121
3122         if (error.hasError(SslError.SSL_NOTYETVALID)) {
3123             LinearLayout ll = (LinearLayout)factory
3124                 .inflate(R.layout.ssl_warning, placeholder);
3125             ((TextView)ll.findViewById(R.id.warning))
3126                 .setText(R.string.ssl_not_yet_valid);
3127         }
3128
3129         mSSLCertificateOnErrorHandler = handler;
3130         mSSLCertificateOnErrorView = view;
3131         mSSLCertificateOnErrorError = error;
3132         mSSLCertificateOnErrorDialog =
3133             new AlertDialog.Builder(this)
3134                 .setTitle(R.string.ssl_certificate).setIcon(
3135                     R.drawable.ic_dialog_browser_certificate_partially_secure)
3136                 .setView(certificateView)
3137                 .setPositiveButton(R.string.ok,
3138                         new DialogInterface.OnClickListener() {
3139                             public void onClick(DialogInterface dialog,
3140                                     int whichButton) {
3141                                 mSSLCertificateOnErrorDialog = null;
3142                                 mSSLCertificateOnErrorView = null;
3143                                 mSSLCertificateOnErrorHandler = null;
3144                                 mSSLCertificateOnErrorError = null;
3145
3146                                 view.getWebViewClient().onReceivedSslError(
3147                                                 view, handler, error);
3148                             }
3149                         })
3150                  .setNeutralButton(R.string.page_info_view,
3151                         new DialogInterface.OnClickListener() {
3152                             public void onClick(DialogInterface dialog,
3153                                     int whichButton) {
3154                                 mSSLCertificateOnErrorDialog = null;
3155
3156                                 // do not clear the dialog state: we will
3157                                 // need to show the dialog again once the
3158                                 // user is done exploring the page-info details
3159
3160                                 showPageInfo(mTabControl.getTabFromView(view),
3161                                         true);
3162                             }
3163                         })
3164                 .setOnCancelListener(
3165                         new DialogInterface.OnCancelListener() {
3166                             public void onCancel(DialogInterface dialog) {
3167                                 mSSLCertificateOnErrorDialog = null;
3168                                 mSSLCertificateOnErrorView = null;
3169                                 mSSLCertificateOnErrorHandler = null;
3170                                 mSSLCertificateOnErrorError = null;
3171
3172                                 view.getWebViewClient().onReceivedSslError(
3173                                                 view, handler, error);
3174                             }
3175                         })
3176                 .show();
3177     }
3178
3179     /**
3180      * Inflates the SSL certificate view (helper method).
3181      * @param certificate The SSL certificate.
3182      * @return The resultant certificate view with issued-to, issued-by,
3183      * issued-on, expires-on, and possibly other fields set.
3184      * If the input certificate is null, returns null.
3185      */
3186     private View inflateCertificateView(SslCertificate certificate) {
3187         if (certificate == null) {
3188             return null;
3189         }
3190
3191         LayoutInflater factory = LayoutInflater.from(this);
3192
3193         View certificateView = factory.inflate(
3194             R.layout.ssl_certificate, null);
3195
3196         // issued to:
3197         SslCertificate.DName issuedTo = certificate.getIssuedTo();
3198         if (issuedTo != null) {
3199             ((TextView) certificateView.findViewById(R.id.to_common))
3200                 .setText(issuedTo.getCName());
3201             ((TextView) certificateView.findViewById(R.id.to_org))
3202                 .setText(issuedTo.getOName());
3203             ((TextView) certificateView.findViewById(R.id.to_org_unit))
3204                 .setText(issuedTo.getUName());
3205         }
3206
3207         // issued by:
3208         SslCertificate.DName issuedBy = certificate.getIssuedBy();
3209         if (issuedBy != null) {
3210             ((TextView) certificateView.findViewById(R.id.by_common))
3211                 .setText(issuedBy.getCName());
3212             ((TextView) certificateView.findViewById(R.id.by_org))
3213                 .setText(issuedBy.getOName());
3214             ((TextView) certificateView.findViewById(R.id.by_org_unit))
3215                 .setText(issuedBy.getUName());
3216         }
3217
3218         // issued on:
3219         String issuedOn = reformatCertificateDate(
3220             certificate.getValidNotBefore());
3221         ((TextView) certificateView.findViewById(R.id.issued_on))
3222             .setText(issuedOn);
3223
3224         // expires on:
3225         String expiresOn = reformatCertificateDate(
3226             certificate.getValidNotAfter());
3227         ((TextView) certificateView.findViewById(R.id.expires_on))
3228             .setText(expiresOn);
3229
3230         return certificateView;
3231     }
3232
3233     /**
3234      * Re-formats the certificate date (Date.toString()) string to
3235      * a properly localized date string.
3236      * @return Properly localized version of the certificate date string and
3237      * the original certificate date string if fails to localize.
3238      * If the original string is null, returns an empty string "".
3239      */
3240     private String reformatCertificateDate(String certificateDate) {
3241       String reformattedDate = null;
3242
3243       if (certificateDate != null) {
3244           Date date = null;
3245           try {
3246               date = java.text.DateFormat.getInstance().parse(certificateDate);
3247           } catch (ParseException e) {
3248               date = null;
3249           }
3250
3251           if (date != null) {
3252               reformattedDate =
3253                   DateFormat.getDateFormat(this).format(date);
3254           }
3255       }
3256
3257       return reformattedDate != null ? reformattedDate :
3258           (certificateDate != null ? certificateDate : "");
3259     }
3260
3261     /**
3262      * Displays an http-authentication dialog.
3263      */
3264     void showHttpAuthentication(final HttpAuthHandler handler,
3265             final String host, final String realm, final String title,
3266             final String name, final String password, int focusId) {
3267         LayoutInflater factory = LayoutInflater.from(this);
3268         final View v = factory
3269                 .inflate(R.layout.http_authentication, null);
3270         if (name != null) {
3271             ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3272         }
3273         if (password != null) {
3274             ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3275         }
3276
3277         String titleText = title;
3278         if (titleText == null) {
3279             titleText = getText(R.string.sign_in_to).toString().replace(
3280                     "%s1", host).replace("%s2", realm);
3281         }
3282
3283         mHttpAuthHandler = handler;
3284         AlertDialog dialog = new AlertDialog.Builder(this)
3285                 .setTitle(titleText)
3286                 .setIcon(android.R.drawable.ic_dialog_alert)
3287                 .setView(v)
3288                 .setPositiveButton(R.string.action,
3289                         new DialogInterface.OnClickListener() {
3290                              public void onClick(DialogInterface dialog,
3291                                      int whichButton) {
3292                                 String nm = ((EditText) v
3293                                         .findViewById(R.id.username_edit))
3294                                         .getText().toString();
3295                                 String pw = ((EditText) v
3296                                         .findViewById(R.id.password_edit))
3297                                         .getText().toString();
3298                                 BrowserActivity.this.setHttpAuthUsernamePassword
3299                                         (host, realm, nm, pw);
3300                                 handler.proceed(nm, pw);
3301                                 mHttpAuthenticationDialog = null;
3302                                 mHttpAuthHandler = null;
3303                             }})
3304                 .setNegativeButton(R.string.cancel,
3305                         new DialogInterface.OnClickListener() {
3306                             public void onClick(DialogInterface dialog,
3307                                     int whichButton) {
3308                                 handler.cancel();
3309                                 BrowserActivity.this.resetTitleAndRevertLockIcon();
3310                                 mHttpAuthenticationDialog = null;
3311                                 mHttpAuthHandler = null;
3312                             }})
3313                 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3314                         public void onCancel(DialogInterface dialog) {
3315                             handler.cancel();
3316                             BrowserActivity.this.resetTitleAndRevertLockIcon();
3317                             mHttpAuthenticationDialog = null;
3318                             mHttpAuthHandler = null;
3319                         }})
3320                 .create();
3321         // Make the IME appear when the dialog is displayed if applicable.
3322         dialog.getWindow().setSoftInputMode(
3323                 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3324         dialog.show();
3325         if (focusId != 0) {
3326             dialog.findViewById(focusId).requestFocus();
3327         } else {
3328             v.findViewById(R.id.username_edit).requestFocus();
3329         }
3330         mHttpAuthenticationDialog = dialog;
3331     }
3332
3333     public int getProgress() {
3334         WebView w = mTabControl.getCurrentWebView();
3335         if (w != null) {
3336             return w.getProgress();
3337         } else {
3338             return 100;
3339         }
3340     }
3341
3342     /**
3343      * Set HTTP authentication password.
3344      *
3345      * @param host The host for the password
3346      * @param realm The realm for the password
3347      * @param username The username for the password. If it is null, it means
3348      *            password can't be saved.
3349      * @param password The password
3350      */
3351     public void setHttpAuthUsernamePassword(String host, String realm,
3352                                             String username,
3353                                             String password) {
3354         WebView w = mTabControl.getCurrentWebView();
3355         if (w != null) {
3356             w.setHttpAuthUsernamePassword(host, realm, username, password);
3357         }
3358     }
3359
3360     /**
3361      * connectivity manager says net has come or gone... inform the user
3362      * @param up true if net has come up, false if net has gone down
3363      */
3364     public void onNetworkToggle(boolean up) {
3365         if (up == mIsNetworkUp) {
3366             return;
3367         } else if (up) {
3368             mIsNetworkUp = true;
3369             if (mAlertDialog != null) {
3370                 mAlertDialog.cancel();
3371                 mAlertDialog = null;
3372             }
3373         } else {
3374             mIsNetworkUp = false;
3375             if (mInLoad) {
3376                 createAndShowNetworkDialog();
3377            }
3378         }
3379         WebView w = mTabControl.getCurrentWebView();
3380         if (w != null) {
3381             w.setNetworkAvailable(up);
3382         }
3383     }
3384
3385     boolean isNetworkUp() {
3386         return mIsNetworkUp;
3387     }
3388
3389     // This method shows the network dialog alerting the user that the net is
3390     // down. It will only show the dialog if mAlertDialog is null.
3391     private void createAndShowNetworkDialog() {
3392         if (mAlertDialog == null) {
3393             mAlertDialog = new AlertDialog.Builder(this)
3394                     .setTitle(R.string.loadSuspendedTitle)
3395                     .setMessage(R.string.loadSuspended)
3396                     .setPositiveButton(R.string.ok, null)
3397                     .show();
3398         }
3399     }
3400
3401     @Override
3402     protected void onActivityResult(int requestCode, int resultCode,
3403                                     Intent intent) {
3404         if (getTopWindow() == null) return;
3405
3406         switch (requestCode) {
3407             case COMBO_PAGE:
3408                 if (resultCode == RESULT_OK && intent != null) {
3409                     String data = intent.getAction();
3410                     Bundle extras = intent.getExtras();
3411                     if (extras != null && extras.getBoolean("new_window", false)) {
3412                         openTab(data);
3413                     } else {
3414                         final Tab currentTab =
3415                                 mTabControl.getCurrentTab();
3416                         dismissSubWindow(currentTab);
3417                         if (data != null && data.length() != 0) {
3418                             getTopWindow().loadUrl(data);
3419                         }
3420                     }
3421                 }
3422                 // Deliberately fall through to PREFERENCES_PAGE, since the
3423                 // same extra may be attached to the COMBO_PAGE
3424             case PREFERENCES_PAGE:
3425                 if (resultCode == RESULT_OK && intent != null) {
3426                     String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3427                     if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3428                         mTabControl.removeParentChildRelationShips();
3429                     }
3430                 }
3431                 break;
3432             // Choose a file from the file picker.
3433             case FILE_SELECTED:
3434                 if (null == mUploadMessage) break;
3435                 Uri result = intent == null || resultCode != RESULT_OK ? null
3436                         : intent.getData();
3437                 mUploadMessage.onReceiveValue(result);
3438                 mUploadMessage = null;
3439                 break;
3440             default:
3441                 break;
3442         }
3443         getTopWindow().requestFocus();
3444     }
3445
3446     /*
3447      * This method is called as a result of the user selecting the options
3448      * menu to see the download window, or when a download changes state. It
3449      * shows the download window ontop of the current window.
3450      */
3451     /* package */ void viewDownloads(Uri downloadRecord) {
3452         Intent intent = new Intent(this,
3453                 BrowserDownloadPage.class);
3454         intent.setData(downloadRecord);
3455         startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3456
3457     }
3458
3459     /**
3460      * Open the Go page.
3461      * @param startWithHistory If true, open starting on the history tab.
3462      *                         Otherwise, start with the bookmarks tab.
3463      */
3464     /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3465         WebView current = mTabControl.getCurrentWebView();
3466         if (current == null) {
3467             return;
3468         }
3469         Intent intent = new Intent(this,
3470                 CombinedBookmarkHistoryActivity.class);
3471         String title = current.getTitle();
3472         String url = current.getUrl();
3473         Bitmap thumbnail = createScreenshot(current);
3474
3475         // Just in case the user opens bookmarks before a page finishes loading
3476         // so the current history item, and therefore the page, is null.
3477         if (null == url) {
3478             url = mLastEnteredUrl;
3479             // This can happen.
3480             if (null == url) {
3481                 url = mSettings.getHomePage();
3482             }
3483         }
3484         // In case the web page has not yet received its associated title.
3485         if (title == null) {
3486             title = url;
3487         }
3488         intent.putExtra("title", title);
3489         intent.putExtra("url", url);
3490         intent.putExtra("thumbnail", thumbnail);
3491         // Disable opening in a new window if we have maxed out the windows
3492         intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3493         intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3494         if (startWithHistory) {
3495             intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3496                     CombinedBookmarkHistoryActivity.HISTORY_TAB);
3497         }
3498         startActivityForResult(intent, COMBO_PAGE);
3499     }
3500
3501     // Called when loading from context menu or LOAD_URL message
3502     private void loadURL(WebView view, String url) {
3503         // In case the user enters nothing.
3504         if (url != null && url.length() != 0 && view != null) {
3505             url = smartUrlFilter(url);
3506             if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3507                 view.loadUrl(url);
3508             }
3509         }
3510     }
3511
3512     private String smartUrlFilter(Uri inUri) {
3513         if (inUri != null) {
3514             return smartUrlFilter(inUri.toString());
3515         }
3516         return null;
3517     }
3518
3519     protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3520             "(?i)" + // switch on case insensitive matching
3521             "(" +    // begin group for schema
3522             "(?:http|https|file):\\/\\/" +
3523             "|(?:inline|data|about|content|javascript):" +
3524             ")" +
3525             "(.*)" );
3526
3527     /**
3528      * Attempts to determine whether user input is a URL or search
3529      * terms.  Anything with a space is passed to search.
3530      *
3531      * Converts to lowercase any mistakenly uppercased schema (i.e.,
3532      * "Http://" converts to "http://"
3533      *
3534      * @return Original or modified URL
3535      *
3536      */
3537     String smartUrlFilter(String url) {
3538
3539         String inUrl = url.trim();
3540         boolean hasSpace = inUrl.indexOf(' ') != -1;
3541
3542         Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3543         if (matcher.matches()) {
3544             // force scheme to lowercase
3545             String scheme = matcher.group(1);
3546             String lcScheme = scheme.toLowerCase();
3547             if (!lcScheme.equals(scheme)) {
3548                 inUrl = lcScheme + matcher.group(2);
3549             }
3550             if (hasSpace) {
3551                 inUrl = inUrl.replace(" ", "%20");
3552             }
3553             return inUrl;
3554         }
3555         if (hasSpace) {
3556             // FIXME: Is this the correct place to add to searches?
3557             // what if someone else calls this function?
3558             int shortcut = parseUrlShortcut(inUrl);
3559             if (shortcut != SHORTCUT_INVALID) {
3560                 Browser.addSearchUrl(mResolver, inUrl);
3561                 String query = inUrl.substring(2);
3562                 switch (shortcut) {
3563                 case SHORTCUT_GOOGLE_SEARCH:
3564                     return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3565                 case SHORTCUT_WIKIPEDIA_SEARCH:
3566                     return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3567                 case SHORTCUT_DICTIONARY_SEARCH:
3568                     return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3569                 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3570                     // FIXME: we need location in this case
3571                     return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3572                 }
3573             }
3574         } else {
3575             if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3576                 return URLUtil.guessUrl(inUrl);
3577             }
3578         }
3579
3580         Browser.addSearchUrl(mResolver, inUrl);
3581         return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3582     }
3583
3584     /* package */ void setShouldShowErrorConsole(boolean flag) {
3585         if (flag == mShouldShowErrorConsole) {
3586             // Nothing to do.
3587             return;
3588         }
3589
3590         mShouldShowErrorConsole = flag;
3591
3592         ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3593                 .getErrorConsole(true);
3594
3595         if (flag) {
3596             // Setting the show state of the console will cause it's the layout to be inflated.
3597             if (errorConsole.numberOfErrors() > 0) {
3598                 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3599             } else {
3600                 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3601             }
3602
3603             // Now we can add it to the main view.
3604             mErrorConsoleContainer.addView(errorConsole,
3605                     new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3606                                                   ViewGroup.LayoutParams.WRAP_CONTENT));
3607         } else {
3608             mErrorConsoleContainer.removeView(errorConsole);
3609         }
3610
3611     }
3612
3613     boolean shouldShowErrorConsole() {
3614         return mShouldShowErrorConsole;
3615     }
3616
3617     private void setStatusBarVisibility(boolean visible) {
3618         int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3619         getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3620     }
3621
3622     final static int LOCK_ICON_UNSECURE = 0;
3623     final static int LOCK_ICON_SECURE   = 1;
3624     final static int LOCK_ICON_MIXED    = 2;
3625
3626     private BrowserSettings mSettings;
3627     private TabControl      mTabControl;
3628     private ContentResolver mResolver;
3629     private FrameLayout     mContentView;
3630     private View            mCustomView;
3631     private FrameLayout     mCustomViewContainer;
3632     private WebChromeClient.CustomViewCallback mCustomViewCallback;
3633
3634     // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3635     // view, we should rewrite this.
3636     private int mCurrentMenuState = 0;
3637     private int mMenuState = R.id.MAIN_MENU;
3638     private int mOldMenuState = EMPTY_MENU;
3639     private static final int EMPTY_MENU = -1;
3640     private Menu mMenu;
3641
3642     private FindDialog mFindDialog;
3643     // Used to prevent chording to result in firing two shortcuts immediately
3644     // one after another.  Fixes bug 1211714.
3645     boolean mCanChord;
3646
3647     private boolean mInLoad;
3648     private boolean mIsNetworkUp;
3649     private boolean mDidStopLoad;
3650
3651     private boolean mActivityInPause = true;
3652
3653     private boolean mMenuIsDown;
3654
3655     private static boolean mInTrace;
3656
3657     // Performance probe
3658     private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3659             Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3660             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3661             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3662             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3663             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3664             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3665             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3666             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG  // 7: softirq time
3667     };
3668
3669     private long mStart;
3670     private long mProcessStart;
3671     private long mUserStart;
3672     private long mSystemStart;
3673     private long mIdleStart;
3674     private long mIrqStart;
3675
3676     private long mUiStart;
3677
3678     private Drawable    mMixLockIcon;
3679     private Drawable    mSecLockIcon;
3680
3681     /* hold a ref so we can auto-cancel if necessary */
3682     private AlertDialog mAlertDialog;
3683
3684     // Wait for credentials before loading google.com
3685     private ProgressDialog mCredsDlg;
3686
3687     // The up-to-date URL and title (these can be different from those stored
3688     // in WebView, since it takes some time for the information in WebView to
3689     // get updated)
3690     private String mUrl;
3691     private String mTitle;
3692
3693     // As PageInfo has different style for landscape / portrait, we have
3694     // to re-open it when configuration changed
3695     private AlertDialog mPageInfoDialog;
3696     private Tab mPageInfoView;
3697     // If the Page-Info dialog is launched from the SSL-certificate-on-error
3698     // dialog, we should not just dismiss it, but should get back to the
3699     // SSL-certificate-on-error dialog. This flag is used to store this state
3700     private boolean mPageInfoFromShowSSLCertificateOnError;
3701
3702     // as SSLCertificateOnError has different style for landscape / portrait,
3703     // we have to re-open it when configuration changed
3704     private AlertDialog mSSLCertificateOnErrorDialog;
3705     private WebView mSSLCertificateOnErrorView;
3706     private SslErrorHandler mSSLCertificateOnErrorHandler;
3707     private SslError mSSLCertificateOnErrorError;
3708
3709     // as SSLCertificate has different style for landscape / portrait, we
3710     // have to re-open it when configuration changed
3711     private AlertDialog mSSLCertificateDialog;
3712     private Tab mSSLCertificateView;
3713
3714     // as HttpAuthentication has different style for landscape / portrait, we
3715     // have to re-open it when configuration changed
3716     private AlertDialog mHttpAuthenticationDialog;
3717     private HttpAuthHandler mHttpAuthHandler;
3718
3719     /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3720                                             new FrameLayout.LayoutParams(
3721                                             ViewGroup.LayoutParams.MATCH_PARENT,
3722                                             ViewGroup.LayoutParams.MATCH_PARENT);
3723     /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3724                                             new FrameLayout.LayoutParams(
3725                                             ViewGroup.LayoutParams.MATCH_PARENT,
3726                                             ViewGroup.LayoutParams.MATCH_PARENT,
3727                                             Gravity.CENTER);
3728     // Google search
3729     final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3730     // Wikipedia search
3731     final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3732     // Dictionary search
3733     final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3734     // Google Mobile Local search
3735     final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3736
3737     final static String QUERY_PLACE_HOLDER = "%s";
3738
3739     // "source" parameter for Google search through search key
3740     final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3741     // "source" parameter for Google search through goto menu
3742     final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3743     // "source" parameter for Google search through simplily type
3744     final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3745     // "source" parameter for Google search suggested by the browser
3746     final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3747     // "source" parameter for Google search from unknown source
3748     final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3749
3750     private final static String LOGTAG = "browser";
3751
3752     private String mLastEnteredUrl;
3753
3754     private PowerManager.WakeLock mWakeLock;
3755     private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3756
3757     private Toast mStopToast;
3758
3759     private TitleBar mTitleBar;
3760
3761     private LinearLayout mErrorConsoleContainer = null;
3762     private boolean mShouldShowErrorConsole = false;
3763
3764     // As the ids are dynamically created, we can't guarantee that they will
3765     // be in sequence, so this static array maps ids to a window number.
3766     final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3767     { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3768       R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3769       R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3770
3771     // monitor platform changes
3772     private IntentFilter mNetworkStateChangedFilter;
3773     private BroadcastReceiver mNetworkStateIntentReceiver;
3774
3775     private BroadcastReceiver mPackageInstallationReceiver;
3776
3777     // activity requestCode
3778     final static int COMBO_PAGE                 = 1;
3779     final static int DOWNLOAD_PAGE              = 2;
3780     final static int PREFERENCES_PAGE           = 3;
3781     final static int FILE_SELECTED              = 4;
3782
3783     // the default <video> poster
3784     private Bitmap mDefaultVideoPoster;
3785     // the video progress view
3786     private View mVideoProgressView;
3787
3788     /**
3789      * A UrlData class to abstract how the content will be set to WebView.
3790      * This base class uses loadUrl to show the content.
3791      */
3792     private static class UrlData {
3793         String mUrl;
3794         byte[] mPostData;
3795
3796         UrlData(String url) {
3797             this.mUrl = url;
3798         }
3799
3800         void setPostData(byte[] postData) {
3801             mPostData = postData;
3802         }
3803
3804         boolean isEmpty() {
3805             return mUrl == null || mUrl.length() == 0;
3806         }
3807
3808         public void loadIn(WebView webView) {
3809             if (mPostData != null) {
3810                 webView.postUrl(mUrl, mPostData);
3811             } else {
3812                 webView.loadUrl(mUrl);
3813             }
3814         }
3815     };
3816
3817     /**
3818      * A subclass of UrlData class that can display inlined content using
3819      * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3820      */
3821     private static class InlinedUrlData extends UrlData {
3822         InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3823             super(failUrl);
3824             mInlined = inlined;
3825             mMimeType = mimeType;
3826             mEncoding = encoding;
3827         }
3828         String mMimeType;
3829         String mInlined;
3830         String mEncoding;
3831         @Override
3832         boolean isEmpty() {
3833             return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3834         }
3835
3836         @Override
3837         public void loadIn(WebView webView) {
3838             webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3839         }
3840     }
3841
3842     /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
3843 }