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