OSDN Git Service

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