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