OSDN Git Service

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