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