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