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