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