OSDN Git Service

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