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