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