OSDN Git Service

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