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