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