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