blob: 1689300d1789f1815b7cba19cb1dd2e7b6ea79cf [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
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
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
Steve Howard5a862fc2010-09-28 12:52:06 -070021import android.app.DownloadManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080022import android.app.ProgressDialog;
23import android.app.SearchManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050027import android.content.ContentProvider;
28import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080029import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040030import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080031import android.content.ContentValues;
32import android.content.Context;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070036import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080037import android.content.pm.PackageManager;
38import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.content.res.Configuration;
40import android.content.res.Resources;
41import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050042import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010044import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040047import android.graphics.PixelFormat;
48import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080050import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000051import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080052import android.net.Uri;
53import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080054import android.net.http.SslCertificate;
55import android.net.http.SslError;
56import android.os.AsyncTask;
57import android.os.Bundle;
58import android.os.Debug;
59import android.os.Environment;
60import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.os.Message;
62import android.os.PowerManager;
63import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.os.ServiceManager;
65import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040067import android.provider.ContactsContract;
68import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080069import android.provider.Downloads;
70import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050071import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.text.IClipboard;
73import android.text.TextUtils;
74import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040075import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080076import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080077import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080078import android.view.ContextMenu;
79import android.view.Gravity;
80import android.view.KeyEvent;
81import android.view.LayoutInflater;
82import android.view.Menu;
83import android.view.MenuInflater;
84import android.view.MenuItem;
85import android.view.View;
86import android.view.ViewGroup;
87import android.view.Window;
88import android.view.WindowManager;
89import android.view.ContextMenu.ContextMenuInfo;
90import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.webkit.CookieManager;
92import android.webkit.CookieSyncManager;
93import android.webkit.DownloadListener;
94import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070095import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.SslErrorHandler;
97import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010098import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080099import android.webkit.WebChromeClient;
100import android.webkit.WebHistoryItem;
101import android.webkit.WebIconDatabase;
102import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800103import android.widget.EditText;
104import android.widget.FrameLayout;
105import android.widget.LinearLayout;
106import android.widget.TextView;
107import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800108import android.accounts.Account;
109import android.accounts.AccountManager;
110import android.accounts.AccountManagerFuture;
111import android.accounts.AuthenticatorException;
112import android.accounts.OperationCanceledException;
113import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800114
Bjorn Bringertd2670652010-09-13 14:06:41 +0100115import com.android.browser.search.SearchEngine;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000116import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500117import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800118
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400119import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000121import java.io.IOException;
122import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.net.MalformedURLException;
124import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700125import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.net.URL;
127import java.net.URLEncoder;
128import java.text.ParseException;
129import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800132import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800134import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000135import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136import java.util.regex.Matcher;
137import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800138
139public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700140 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800141
Dave Bort31a6d1c2009-04-13 15:56:49 -0700142 /* Define some aliases to make these debugging flags easier to refer to.
143 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
144 */
145 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
146 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
147 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
148
Cary Clarka9771242009-08-11 16:42:26 -0400149 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800150 @Override
151 public Void doInBackground(File... files) {
152 if (files != null) {
153 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400154 if (!f.delete()) {
155 Log.e(LOGTAG, f.getPath() + " was not deleted");
156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800157 }
158 }
159 return null;
160 }
161 }
162
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400163 /**
164 * This layout holds everything you see below the status bar, including the
165 * error console, the custom view container, and the webviews.
166 */
167 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400168
Grace Kloba22ac16e2009-10-07 18:00:23 -0700169 @Override
170 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700171 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800172 Log.v(LOGTAG, this + " onStart");
173 }
174 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800175 // test the browser in OpenGL
176 // requestWindowFeature(Window.FEATURE_OPENGL);
177
Mike Reedd334bf52010-01-26 15:21:44 -0500178 // enable this to test the browser in 32bit
179 if (false) {
180 getWindow().setFormat(PixelFormat.RGBX_8888);
181 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
182 }
183
The Android Open Source Project0c908882009-03-03 19:32:16 -0800184 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
185
186 mResolver = getContentResolver();
187
Leon Scroggins IIIcc14c8c2010-09-27 12:45:34 -0400188 // Keep a settings instance handy.
189 mSettings = BrowserSettings.getInstance();
190
Ed Tam8ba13bc2011-05-05 16:19:48 -0700191 mSettings.updateRlzValues(this);
192
Grace Kloba0923d692009-09-23 21:37:25 -0700193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
196 finish();
197 return;
198 }
199
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800204
Leon Scroggins81db3662009-06-04 17:45:11 -0400205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
210 R.id.main_content);
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400216 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400219 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800220
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
223
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
226
The Android Open Source Project0c908882009-03-03 19:32:16 -0800227 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228
229 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
230 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
231
Patrick Scott6adacc92010-03-05 08:24:51 -0500232 // Find out if the network is currently up.
233 ConnectivityManager cm = (ConnectivityManager) getSystemService(
234 Context.CONNECTIVITY_SERVICE);
235 NetworkInfo info = cm.getActiveNetworkInfo();
236 if (info != null) {
237 mIsNetworkUp = info.isAvailable();
238 }
239
Grace Klobaa34f6862009-07-31 16:28:17 -0700240 /* enables registration for changes in network status from
241 http stack */
242 mNetworkStateChangedFilter = new IntentFilter();
243 mNetworkStateChangedFilter.addAction(
244 ConnectivityManager.CONNECTIVITY_ACTION);
245 mNetworkStateIntentReceiver = new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context, Intent intent) {
248 if (intent.getAction().equals(
249 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000250
251 NetworkInfo info = intent.getParcelableExtra(
252 ConnectivityManager.EXTRA_NETWORK_INFO);
253 String typeName = info.getTypeName();
254 String subtypeName = info.getSubtypeName();
255 sendNetworkType(typeName.toLowerCase(),
256 (subtypeName != null ? subtypeName.toLowerCase() : ""));
257
258 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700259 }
260 }
261 };
262
Grace Kloba615c6c92009-08-03 10:22:44 -0700263 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
264 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
265 filter.addDataScheme("package");
266 mPackageInstallationReceiver = new BroadcastReceiver() {
267 @Override
268 public void onReceive(Context context, Intent intent) {
269 final String action = intent.getAction();
270 final String packageName = intent.getData()
271 .getSchemeSpecificPart();
272 final boolean replacing = intent.getBooleanExtra(
273 Intent.EXTRA_REPLACING, false);
274 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
275 // if it is replacing, refreshPlugins() when adding
276 return;
277 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000278
279 if (sGoogleApps.contains(packageName)) {
280 BrowserActivity.this.packageChanged(packageName,
281 Intent.ACTION_PACKAGE_ADDED.equals(action));
282 }
283
Grace Kloba615c6c92009-08-03 10:22:44 -0700284 PackageManager pm = BrowserActivity.this.getPackageManager();
285 PackageInfo pkgInfo = null;
286 try {
287 pkgInfo = pm.getPackageInfo(packageName,
288 PackageManager.GET_PERMISSIONS);
289 } catch (PackageManager.NameNotFoundException e) {
290 return;
291 }
292 if (pkgInfo != null) {
293 String permissions[] = pkgInfo.requestedPermissions;
294 if (permissions == null) {
295 return;
296 }
297 boolean permissionOk = false;
298 for (String permit : permissions) {
299 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
300 permissionOk = true;
301 break;
302 }
303 }
304 if (permissionOk) {
305 PluginManager.getInstance(BrowserActivity.this)
306 .refreshPlugins(
307 Intent.ACTION_PACKAGE_ADDED
308 .equals(action));
309 }
310 }
311 }
312 };
313 registerReceiver(mPackageInstallationReceiver, filter);
314
The Android Open Source Project0c908882009-03-03 19:32:16 -0800315 if (!mTabControl.restoreState(icicle)) {
316 // clear up the thumbnail directory if we can't restore the state as
317 // none of the files in the directory are referenced any more.
318 new ClearThumbnails().execute(
319 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700320 // there is no quit on Android. But if we can't restore the state,
321 // we can treat it as a new Browser, remove the old session cookies.
322 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800323 final Intent intent = getIntent();
324 final Bundle extra = intent.getExtras();
325 // Create an initial tab.
326 // If the intent is ACTION_VIEW and data is not null, the Browser is
327 // invoked to view the content by another application. In this case,
328 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700329 UrlData urlData = getUrlDataFromIntent(intent);
330
Leon Scroggins58d56c62010-01-28 15:12:40 -0500331 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700332 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500333 (Intent.ACTION_VIEW.equals(action) &&
334 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500335 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
336 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700337 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800338 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800339 attachTabToContentView(t);
340 WebView webView = t.getWebView();
341 if (extra != null) {
342 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
343 if (scale > 0 && scale <= 1000) {
344 webView.setInitialScale(scale);
345 }
346 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800347
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700348 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700349 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500351 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800352 }
353 } else {
354 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400355 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800356 attachTabToContentView(mTabControl.getCurrentTab());
357 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700358
Cary Clark23cbeb72010-07-01 12:36:56 -0400359 // Delete old thumbnails to save space
360 File dir = mTabControl.getThumbnailDir();
361 if (dir.exists()) {
362 for (String child : dir.list()) {
363 File f = new File(dir, child);
364 f.delete();
365 }
366 }
367
Feng Qianb3c02da2009-06-29 15:58:08 -0700368 // Read JavaScript flags if it exists.
369 String jsFlags = mSettings.getJsFlags();
370 if (jsFlags.trim().length() != 0) {
371 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
372 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000373 // Work out which packages are installed on the system.
374 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000375
376 // Start watching the default geolocation permissions
377 mSystemAllowGeolocationOrigins
378 = new SystemAllowGeolocationOrigins(getApplicationContext());
379 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800380 }
381
Leon Scroggins58d56c62010-01-28 15:12:40 -0500382 /**
383 * Feed the previously stored results strings to the BrowserProvider so that
384 * the SearchDialog will show them instead of the standard searches.
385 * @param result String to show on the editable line of the SearchDialog.
386 */
387 /* package */ void showVoiceSearchResults(String result) {
388 ContentProviderClient client = mResolver.acquireContentProviderClient(
389 Browser.BOOKMARKS_URI);
390 ContentProvider prov = client.getLocalContentProvider();
391 BrowserProvider bp = (BrowserProvider) prov;
392 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
393 client.release();
394
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500395 Bundle bundle = createGoogleSearchSourceBundle(
396 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
397 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
398 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500399 }
400
The Android Open Source Project0c908882009-03-03 19:32:16 -0800401 @Override
402 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700403 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404 // When a tab is closed on exit, the current tab index is set to -1.
405 // Reset before proceed as Browser requires the current tab to be set.
406 if (current == null) {
407 // Try to reset the tab in case the index was incorrect.
408 current = mTabControl.getTab(0);
409 if (current == null) {
410 // No tabs at all so just ignore this intent.
411 return;
412 }
413 mTabControl.setCurrentTab(current);
414 attachTabToContentView(current);
415 resetTitleAndIcon(current.getWebView());
416 }
417 final String action = intent.getAction();
418 final int flags = intent.getFlags();
419 if (Intent.ACTION_MAIN.equals(action) ||
420 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
421 // just resume the browser
422 return;
423 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400424 // In case the SearchDialog is open.
425 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
426 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500427 boolean activateVoiceSearch = RecognizerResultsIntent
428 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800429 if (Intent.ACTION_VIEW.equals(action)
430 || Intent.ACTION_SEARCH.equals(action)
431 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500432 || Intent.ACTION_WEB_SEARCH.equals(action)
433 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500434 if (current.isInVoiceSearchMode()) {
435 String title = current.getVoiceDisplayTitle();
436 if (title != null && title.equals(intent.getStringExtra(
437 SearchManager.QUERY))) {
438 // The user submitted the same search as the last voice
439 // search, so do nothing.
440 return;
441 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500442 if (Intent.ACTION_SEARCH.equals(action)
443 && current.voiceSearchSourceIsGoogle()) {
444 Intent logIntent = new Intent(
445 LoggingEvents.ACTION_LOG_EVENT);
446 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
447 LoggingEvents.VoiceSearch.QUERY_UPDATED);
448 logIntent.putExtra(
449 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
450 intent.getDataString());
451 sendBroadcast(logIntent);
452 // Note, onPageStarted will revert the voice title bar
453 // When http://b/issue?id=2379215 is fixed, we should update
454 // the title bar here.
455 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500456 }
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700467
Grace Klobacc634032009-07-28 15:58:19 -0700468 final String appId = intent
469 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
John Reck096bae22011-06-21 14:15:19 -0700470 if (!TextUtils.isEmpty(urlData.mUrl) &&
471 urlData.mUrl.startsWith("javascript:")) {
472 // Always open javascript: URIs in new tabs
473 openTabAndShow(urlData, true, appId);
474 return;
475 }
Leon Scroggins47208682010-04-07 17:59:48 -0400476 if ((Intent.ACTION_VIEW.equals(action)
477 // If a voice search has no appId, it means that it came
478 // from the browser. In that case, reuse the current tab.
479 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700480 && !getPackageName().equals(appId)
481 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700482 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 if (appTab != null) {
484 Log.i(LOGTAG, "Reusing tab for " + appId);
485 // Dismiss the subwindow if applicable.
486 dismissSubWindow(appTab);
487 // Since we might kill the WebView, remove it from the
488 // content view first.
489 removeTabFromContentView(appTab);
490 // Recreate the main WebView after destroying the old one.
491 // If the WebView has the same original url and is on that
492 // page, it can be reused.
493 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400494 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100495
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700496 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400497 switchToTab(mTabControl.getTabIndex(appTab));
498 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500499 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400500 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700501 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400502 // If the tab was the current tab, we have to attach
503 // it to the view system again.
504 attachTabToContentView(appTab);
505 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500506 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700507 }
508 }
509 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400510 } else {
511 // No matching application tab, try to find a regular tab
512 // with a matching url.
513 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400514 if (appTab != null) {
515 if (current != appTab) {
516 switchToTab(mTabControl.getTabIndex(appTab));
517 }
518 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400519 } else {
520 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
521 // will be opened in a new tab unless we have reached
522 // MAX_TABS. Then the url will be opened in the current
523 // tab. If a new tab is created, it will have "true" for
524 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400525 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400526 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700527 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800528 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800529 if (!urlData.isEmpty()
530 && urlData.mUrl.startsWith("about:debug")) {
531 if ("about:debug.dom".equals(urlData.mUrl)) {
532 current.getWebView().dumpDomTree(false);
533 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
534 current.getWebView().dumpDomTree(true);
535 } else if ("about:debug.render".equals(urlData.mUrl)) {
536 current.getWebView().dumpRenderTree(false);
537 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
538 current.getWebView().dumpRenderTree(true);
539 } else if ("about:debug.display".equals(urlData.mUrl)) {
540 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800541 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
542 int index = urlData.mUrl.codePointAt(16) - '0';
543 if (index <= 0 || index > 9) {
544 current.getWebView().setDragTracker(null);
545 } else {
546 current.getWebView().setDragTracker(new MeshTracker(index));
547 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800548 } else {
549 mSettings.toggleDebugSettings();
550 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800551 return;
552 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400553 // Get rid of the subwindow if it exists
554 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400555 // If the current Tab is being used as an application tab,
556 // remove the association, since the new Intent means that it is
557 // no longer associated with that application.
558 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500559 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800560 }
561 }
562 }
563
Satish Sampath565505b2009-05-29 15:37:27 +0100564 /**
565 * Launches the default web search activity with the query parameters if the given intent's data
566 * are identified as plain search terms and not URLs/shortcuts.
567 * @return true if the intent was handled and web search activity was launched, false if not.
568 */
569 private boolean handleWebSearchIntent(Intent intent) {
570 if (intent == null) return false;
571
572 String url = null;
573 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500574 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
575 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500576 return false;
577 }
Satish Sampath565505b2009-05-29 15:37:27 +0100578 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700579 Uri data = intent.getData();
580 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100581 } else if (Intent.ACTION_SEARCH.equals(action)
582 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
583 || Intent.ACTION_WEB_SEARCH.equals(action)) {
584 url = intent.getStringExtra(SearchManager.QUERY);
585 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100586 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
587 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100588 }
589
590 /**
591 * Launches the default web search activity with the query parameters if the given url string
592 * was identified as plain search terms and not URL/shortcut.
593 * @return true if the request was handled and web search activity was launched, false if not.
594 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100595 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100596 if (inUrl == null) return false;
597
598 // In general, we shouldn't modify URL from Intent.
599 // But currently, we get the user-typed URL from search box as well.
600 String url = fixUrl(inUrl).trim();
601
Leon Scroggins956cf012010-10-07 13:51:57 -0400602 // URLs are handled by the regular flow of control, so
Satish Sampath565505b2009-05-29 15:37:27 +0100603 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800604 if (Patterns.WEB_URL.matcher(url).matches()
Leon Scroggins956cf012010-10-07 13:51:57 -0400605 || ACCEPTED_URI_SCHEMA.matcher(url).matches()) {
Satish Sampath565505b2009-05-29 15:37:27 +0100606 return false;
607 }
608
Leon Scroggins8d06e362010-03-24 14:45:57 -0400609 final ContentResolver cr = mResolver;
610 final String newUrl = url;
611 new AsyncTask<Void, Void, Void>() {
612 protected Void doInBackground(Void... unused) {
613 Browser.updateVisitedHistory(cr, newUrl, false);
614 Browser.addSearchUrl(cr, newUrl);
615 return null;
616 }
617 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100618
Bjorn Bringertd2670652010-09-13 14:06:41 +0100619 SearchEngine searchEngine = mSettings.getSearchEngine();
620 if (searchEngine == null) return false;
621 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100622
623 return true;
624 }
625
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700626 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500627 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800628 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800629 if (intent != null) {
630 final String action = intent.getAction();
631 if (Intent.ACTION_VIEW.equals(action)) {
632 url = smartUrlFilter(intent.getData());
Grace Kloba068e48b2010-01-26 18:11:27 -0800633 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800634 final Bundle pairs = intent
635 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800636 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800637 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800638 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800639 while (iter.hasNext()) {
640 String key = iter.next();
641 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800642 }
643 }
Ed Tam8ba13bc2011-05-05 16:19:48 -0700644
645 // AppId will be set to the Browser for Search Bar initiated searches
646 final String appId = intent.getStringExtra(Browser.EXTRA_APPLICATION_ID);
647 if (getPackageName().equals(appId)) {
648 String rlz = mSettings.getRlzValue();
649 Uri uri = Uri.parse(url);
650 if (!rlz.isEmpty() && needsRlz(uri)) {
651 Uri rlzUri = addRlzParameter(uri, rlz);
652 url = rlzUri.toString();
653 }
654 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700655 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800656 } else if (Intent.ACTION_SEARCH.equals(action)
657 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
658 || Intent.ACTION_WEB_SEARCH.equals(action)) {
659 url = intent.getStringExtra(SearchManager.QUERY);
660 if (url != null) {
661 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800662 // In general, we shouldn't modify URL from Intent.
663 // But currently, we get the user-typed URL from search box as well.
664 url = fixUrl(url);
665 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400666 final ContentResolver cr = mResolver;
667 final String newUrl = url;
668 new AsyncTask<Void, Void, Void>() {
669 protected Void doInBackground(Void... unused) {
670 Browser.updateVisitedHistory(cr, newUrl, false);
671 return null;
672 }
673 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
675 if (url.contains(searchSource)) {
676 String source = null;
677 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
678 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000679 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 }
681 if (TextUtils.isEmpty(source)) {
682 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
683 }
684 url = url.replace(searchSource, "&source=android-"+source+"&");
685 }
686 }
687 }
688 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500689 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500691 /* package */ void showVoiceTitleBar(String title) {
692 mTitleBar.setInVoiceMode(true);
693 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694
Leon Scroggins58d56c62010-01-28 15:12:40 -0500695 mTitleBar.setDisplayTitle(title);
696 mFakeTitleBar.setDisplayTitle(title);
697 }
698 /* package */ void revertVoiceTitleBar() {
699 mTitleBar.setInVoiceMode(false);
700 mFakeTitleBar.setInVoiceMode(false);
701
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500702 mTitleBar.setDisplayTitle(mUrl);
703 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400706 // FIXME: Converting the url to lower case
707 // duplicates functionality in smartUrlFilter().
708 // However, changing all current callers of fixUrl to
709 // call smartUrlFilter in addition may have unwanted
710 // consequences, and is deferred for now.
711 int colon = inUrl.indexOf(':');
712 boolean allLower = true;
713 for (int index = 0; index < colon; index++) {
714 char ch = inUrl.charAt(index);
715 if (!Character.isLetter(ch)) {
716 break;
717 }
718 allLower &= Character.isLowerCase(ch);
719 if (index == colon - 1 && !allLower) {
720 inUrl = inUrl.substring(0, colon).toLowerCase()
721 + inUrl.substring(colon);
722 }
723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
725 return inUrl;
726 if (inUrl.startsWith("http:") ||
727 inUrl.startsWith("https:")) {
728 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
729 inUrl = inUrl.replaceFirst("/", "//");
730 } else inUrl = inUrl.replaceFirst(":", "://");
731 }
732 return inUrl;
733 }
734
Grace Kloba22ac16e2009-10-07 18:00:23 -0700735 @Override
736 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700738 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
740 }
741
742 if (!mActivityInPause) {
743 Log.e(LOGTAG, "BrowserActivity is already resumed.");
744 return;
745 }
746
Mike Reed7bfa63b2009-05-28 11:08:32 -0400747 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800748 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400749 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750
751 if (mWakeLock.isHeld()) {
752 mHandler.removeMessages(RELEASE_WAKELOCK);
753 mWakeLock.release();
754 }
755
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756 registerReceiver(mNetworkStateIntentReceiver,
757 mNetworkStateChangedFilter);
758 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 }
760
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400761 /**
762 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400763 * would change its appearance, use a different TitleBar to show overlayed
764 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400765 */
766 private TitleBar mFakeTitleBar;
767
768 /**
769 * Keeps track of whether the options menu is open. This is important in
770 * determining whether to show or hide the title bar overlay.
771 */
772 private boolean mOptionsMenuOpen;
773
774 /**
775 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
776 * of whether the configuration has changed. The first onMenuOpened call
777 * after a configuration change is simply a reopening of the same menu
778 * (i.e. mIconView did not change).
779 */
780 private boolean mConfigChanged;
781
782 /**
783 * Whether or not the options menu is in its smaller, icon menu form. When
784 * true, we want the title bar overlay to be up. When false, we do not.
785 * Only meaningful if mOptionsMenuOpen is true.
786 */
787 private boolean mIconView;
788
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400789 @Override
790 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400791 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
792 if (mOptionsMenuOpen) {
793 if (mConfigChanged) {
794 // We do not need to make any changes to the state of the
795 // title bar, since the only thing that happened was a
796 // change in orientation
797 mConfigChanged = false;
798 } else {
799 if (mIconView) {
800 // Switching the menu to expanded view, so hide the
801 // title bar.
802 hideFakeTitleBar();
803 mIconView = false;
804 } else {
805 // Switching the menu back to icon view, so show the
806 // title bar once again.
807 showFakeTitleBar();
808 mIconView = true;
809 }
810 }
811 } else {
812 // The options menu is closed, so open it, and show the title
813 showFakeTitleBar();
814 mOptionsMenuOpen = true;
815 mConfigChanged = false;
816 mIconView = true;
817 }
818 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400819 return true;
820 }
821
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400822 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400823 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700824 && !mActivityInPause) {
825 WebView mainView = mTabControl.getCurrentWebView();
826 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700827 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400828 return;
829 }
Cary Clark2c326e62010-08-19 18:40:57 -0400830 // Do not need to check for null, since the current tab will have
831 // at least a main WebView, or we would have returned above.
832 if (dialogIsUp()) {
833 // Do not show the fake title bar, which would cover up the
834 // find or select dialog.
835 return;
836 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400837
838 WindowManager manager
839 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
840
841 // Add the title bar to the window manager so it can receive touches
842 // while the menu is up
843 WindowManager.LayoutParams params
844 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800845 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400846 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700847 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400848 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400849 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400850 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700851 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400852 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700853 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 }
855 }
856
857 @Override
858 public void onOptionsMenuClosed(Menu menu) {
859 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400860 if (!mInLoad) {
861 hideFakeTitleBar();
862 } else if (!mIconView) {
863 // The page is currently loading, and we are in expanded mode, so
864 // we were not showing the menu. Show it once again. It will be
865 // removed when the page finishes.
866 showFakeTitleBar();
867 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400868 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700869
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400870 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400871 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400872 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700873 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400874 WebView mainView = mTabControl.getCurrentWebView();
875 // Although we decided whether or not to animate based on the current
876 // scroll position, the scroll position may have changed since the
877 // fake title bar was displayed. Make sure it has the appropriate
878 // animation/lack thereof before removing.
879 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400880 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 WindowManager manager
882 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700883 manager.updateViewLayout(mFakeTitleBar, params);
884 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400885 }
886
The Android Open Source Project0c908882009-03-03 19:32:16 -0800887 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400888 * Special method for the fake title bar to call when displaying its context
889 * menu, since it is in its own Window, and its parent does not show a
890 * context menu.
891 */
892 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400893 if (null == mTitleBar.getParent()) {
894 return;
895 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400896 openContextMenu(mTitleBar);
897 }
898
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400899 @Override
900 public void onContextMenuClosed(Menu menu) {
901 super.onContextMenuClosed(menu);
902 if (mInLoad) {
903 showFakeTitleBar();
904 }
905 }
906
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400907 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800908 * onSaveInstanceState(Bundle map)
909 * onSaveInstanceState is called right before onStop(). The map contains
910 * the saved state.
911 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700912 @Override
913 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700914 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800915 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
916 }
917 // the default implementation requires each view to have an id. As the
918 // browser handles the state itself and it doesn't use id for the views,
919 // don't call the default implementation. Otherwise it will trigger the
920 // warning like this, "couldn't save which view has focus because the
921 // focused view XXX has no id".
922
923 // Save all the tabs
924 mTabControl.saveState(outState);
925 }
926
Grace Kloba22ac16e2009-10-07 18:00:23 -0700927 @Override
928 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800929 super.onPause();
930
931 if (mActivityInPause) {
932 Log.e(LOGTAG, "BrowserActivity is already paused.");
933 return;
934 }
935
Mike Reed7bfa63b2009-05-28 11:08:32 -0400936 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400938 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800939 mWakeLock.acquire();
940 mHandler.sendMessageDelayed(mHandler
941 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
942 }
943
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400944 // FIXME: This removes the active tabs page and resets the menu to
945 // MAIN_MENU. A better solution might be to do this work in onNewIntent
946 // but then we would need to save it in onSaveInstanceState and restore
947 // it in onCreate/onRestoreInstanceState
948 if (mActiveTabsPage != null) {
949 removeActiveTabPage(true);
950 }
951
The Android Open Source Project0c908882009-03-03 19:32:16 -0800952 cancelStopToast();
953
954 // unregister network state listener
955 unregisterReceiver(mNetworkStateIntentReceiver);
956 WebView.disablePlatformNotifications();
Ben Murdocha4909cb2010-11-30 20:48:15 +0000957
958 if (mCustomView != null) {
959 mTabControl.getCurrentWebView().getWebChromeClient().onHideCustomView();
960 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800961 }
962
Grace Kloba22ac16e2009-10-07 18:00:23 -0700963 @Override
964 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700965 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
967 }
968 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700969
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400970 if (mUploadMessage != null) {
971 mUploadMessage.onReceiveValue(null);
972 mUploadMessage = null;
973 }
974
Grace Kloba0923d692009-09-23 21:37:25 -0700975 if (mTabControl == null) return;
976
Grace Kloba1fc98a32009-10-21 13:23:08 -0700977 // Remove the fake title bar if it is there
978 hideFakeTitleBar();
979
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700981 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700982 if (t != null) {
983 dismissSubWindow(t);
984 removeTabFromContentView(t);
985 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 // Destroy all the tabs
987 mTabControl.destroy();
988 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989
Grace Klobab4da0ad2009-05-14 14:45:40 -0700990 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000991
992 // Stop watching the default geolocation permissions
993 mSystemAllowGeolocationOrigins.stop();
994 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800995 }
996
997 @Override
998 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 super.onConfigurationChanged(newConfig);
1001
1002 if (mPageInfoDialog != null) {
1003 mPageInfoDialog.dismiss();
1004 showPageInfo(
1005 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001006 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 }
1008 if (mSSLCertificateDialog != null) {
1009 mSSLCertificateDialog.dismiss();
1010 showSSLCertificate(
1011 mSSLCertificateView);
1012 }
1013 if (mSSLCertificateOnErrorDialog != null) {
1014 mSSLCertificateOnErrorDialog.dismiss();
1015 showSSLCertificateOnError(
1016 mSSLCertificateOnErrorView,
1017 mSSLCertificateOnErrorHandler,
1018 mSSLCertificateOnErrorError);
1019 }
1020 if (mHttpAuthenticationDialog != null) {
1021 String title = ((TextView) mHttpAuthenticationDialog
1022 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1023 .toString();
1024 String name = ((TextView) mHttpAuthenticationDialog
1025 .findViewById(R.id.username_edit)).getText().toString();
1026 String password = ((TextView) mHttpAuthenticationDialog
1027 .findViewById(R.id.password_edit)).getText().toString();
1028 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1029 .getId();
1030 mHttpAuthenticationDialog.dismiss();
1031 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1032 name, password, focusId);
1033 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 }
1035
Grace Kloba22ac16e2009-10-07 18:00:23 -07001036 @Override
1037 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001038 super.onLowMemory();
1039 mTabControl.freeMemory();
1040 }
1041
Cary Clarkff4d92c2010-03-25 11:17:03 -04001042 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001044 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 boolean inLoad = tab.inLoad();
1046 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001047 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001048 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 if (w != null) {
1050 w.resumeTimers();
1051 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001052 }
1053 }
1054
Mike Reed7bfa63b2009-05-28 11:08:32 -04001055 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001056 Tab tab = mTabControl.getCurrentTab();
1057 boolean inLoad = tab.inLoad();
1058 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 CookieSyncManager.getInstance().stopSync();
1060 WebView w = mTabControl.getCurrentWebView();
1061 if (w != null) {
1062 w.pauseTimers();
1063 }
1064 return true;
1065 } else {
1066 return false;
1067 }
1068 }
1069
The Android Open Source Project0c908882009-03-03 19:32:16 -08001070 // Open the icon database and retain all the icons for visited sites.
1071 private void retainIconsOnStartup() {
1072 final WebIconDatabase db = WebIconDatabase.getInstance();
1073 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001074 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001076 c = Browser.getAllBookmarks(mResolver);
1077 if (c.moveToFirst()) {
1078 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1079 do {
1080 String url = c.getString(urlIndex);
1081 db.retainIconForPageUrl(url);
1082 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001084 } catch (IllegalStateException e) {
1085 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001086 } finally {
1087 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 }
1089 }
1090
1091 // Helper method for getting the top window.
1092 WebView getTopWindow() {
1093 return mTabControl.getCurrentTopWebView();
1094 }
1095
Grace Kloba22ac16e2009-10-07 18:00:23 -07001096 TabControl getTabControl() {
1097 return mTabControl;
1098 }
1099
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 @Override
1101 public boolean onCreateOptionsMenu(Menu menu) {
1102 super.onCreateOptionsMenu(menu);
1103
1104 MenuInflater inflater = getMenuInflater();
1105 inflater.inflate(R.menu.browser, menu);
1106 mMenu = menu;
1107 updateInLoadMenuItems();
1108 return true;
1109 }
1110
1111 /**
1112 * As the menu can be open when loading state changes
1113 * we must manually update the state of the stop/reload menu
1114 * item
1115 */
1116 private void updateInLoadMenuItems() {
1117 if (mMenu == null) {
1118 return;
1119 }
1120 MenuItem src = mInLoad ?
1121 mMenu.findItem(R.id.stop_menu_id):
1122 mMenu.findItem(R.id.reload_menu_id);
1123 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1124 dest.setIcon(src.getIcon());
1125 dest.setTitle(src.getTitle());
1126 }
1127
1128 @Override
1129 public boolean onContextItemSelected(MenuItem item) {
1130 // chording is not an issue with context menus, but we use the same
1131 // options selector, so set mCanChord to true so we can access them.
1132 mCanChord = true;
1133 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001134 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001135 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001136 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001137 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001138 Tab currentTab = mTabControl.getCurrentTab();
1139 if (null == currentTab) {
1140 result = false;
1141 break;
1142 }
1143 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001144 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001145 result = false;
1146 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001147 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001148 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001149 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001150 // -- Browser context menu
1151 case R.id.open_context_menu_id:
1152 case R.id.open_newtab_context_menu_id:
1153 case R.id.bookmark_context_menu_id:
1154 case R.id.save_link_context_menu_id:
1155 case R.id.share_link_context_menu_id:
1156 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001157 final WebView webView = getTopWindow();
1158 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001159 result = false;
1160 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001161 }
1162 final HashMap hrefMap = new HashMap();
1163 hrefMap.put("webview", webView);
1164 final Message msg = mHandler.obtainMessage(
1165 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001166 webView.requestFocusNodeHref(msg);
1167 break;
1168
1169 default:
1170 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001171 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 }
1173 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001174 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001175 }
1176
1177 private Bundle createGoogleSearchSourceBundle(String source) {
1178 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001179 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 return bundle;
1181 }
1182
Leon Scroggins8ad29922010-02-16 12:33:55 -05001183 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001184 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001185 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001186 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001187 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001188 }
1189
Leon Scroggins8ad29922010-02-16 12:33:55 -05001190 /**
1191 * Overriding this to insert a local information bundle
1192 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001193 @Override
1194 public void startSearch(String initialQuery, boolean selectInitialQuery,
1195 Bundle appSearchData, boolean globalSearch) {
1196 if (appSearchData == null) {
1197 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1198 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001199
1200 SearchEngine searchEngine = mSettings.getSearchEngine();
1201 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1202 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1203 }
1204
The Android Open Source Project0c908882009-03-03 19:32:16 -08001205 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1206 }
1207
Leon Scroggins1f005d32009-08-10 17:36:42 -04001208 /**
1209 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1210 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001211 * @param index Index of the tab to change to, as defined by
1212 * mTabControl.getTabIndex(Tab t).
1213 * @return boolean True if we successfully switched to a different tab. If
1214 * the indexth tab is null, or if that tab is the same as
1215 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001216 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001217 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001218 Tab tab = mTabControl.getTab(index);
1219 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001220 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001221 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 }
1223 if (currentTab != null) {
1224 // currentTab may be null if it was just removed. In that case,
1225 // we do not need to remove it
1226 removeTabFromContentView(currentTab);
1227 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 mTabControl.setCurrentTab(tab);
1229 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001230 resetTitleIconAndProgress();
1231 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001232 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001233 }
1234
Grace Kloba22ac16e2009-10-07 18:00:23 -07001235 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001236 return openTabAndShow(mSettings.getHomePage(), false, null);
1237 }
1238
Leon Scroggins1f005d32009-08-10 17:36:42 -04001239 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001240 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001241 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001242 // This is the last tab. Open a new one, with the home
1243 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001244 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001245 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001246 return;
1247 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001248 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001249 int indexToShow = -1;
1250 if (parent != null) {
1251 indexToShow = mTabControl.getTabIndex(parent);
1252 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001253 final int currentIndex = mTabControl.getCurrentIndex();
1254 // Try to move to the tab to the right
1255 indexToShow = currentIndex + 1;
1256 if (indexToShow > mTabControl.getTabCount() - 1) {
1257 // Try to move to the tab to the left
1258 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001259 }
1260 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001261 if (switchToTab(indexToShow)) {
1262 // Close window
1263 closeTab(current);
1264 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001265 }
1266
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001267 private ActiveTabsPage mActiveTabsPage;
1268
1269 /**
1270 * Remove the active tabs page.
1271 * @param needToAttach If true, the active tabs page did not attach a tab
1272 * to the content view, so we need to do that here.
1273 */
1274 /* package */ void removeActiveTabPage(boolean needToAttach) {
1275 mContentView.removeView(mActiveTabsPage);
1276 mActiveTabsPage = null;
1277 mMenuState = R.id.MAIN_MENU;
1278 if (needToAttach) {
1279 attachTabToContentView(mTabControl.getCurrentTab());
1280 }
1281 getTopWindow().requestFocus();
1282 }
1283
Cary Clark2c326e62010-08-19 18:40:57 -04001284 private WebView showDialog(WebDialog dialog) {
Cary Clark2c326e62010-08-19 18:40:57 -04001285 Tab tab = mTabControl.getCurrentTab();
1286 if (tab.getSubWebView() == null) {
1287 // If the find or select is being performed on the main webview,
1288 // remove the embedded title bar.
1289 WebView mainView = tab.getWebView();
1290 if (mainView != null) {
1291 mainView.setEmbeddedTitleBar(null);
1292 }
1293 }
1294 hideFakeTitleBar();
1295 mMenuState = EMPTY_MENU;
1296 return tab.showDialog(dialog);
1297 }
1298
The Android Open Source Project0c908882009-03-03 19:32:16 -08001299 @Override
1300 public boolean onOptionsItemSelected(MenuItem item) {
1301 if (!mCanChord) {
1302 // The user has already fired a shortcut with this hold down of the
1303 // menu key.
1304 return false;
1305 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001306 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001307 return false;
1308 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001309 if (mMenuIsDown) {
1310 // The shortcut action consumes the MENU. Even if it is still down,
1311 // it won't trigger the next shortcut action. In the case of the
1312 // shortcut action triggering a new activity, like Bookmarks, we
1313 // won't get onKeyUp for MENU. So it is important to reset it here.
1314 mMenuIsDown = false;
1315 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 switch (item.getItemId()) {
1317 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001318 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001319 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001320 break;
1321
Leon Scroggins64b80f32009-08-07 12:03:34 -04001322 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001323 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001324 break;
1325
1326 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001327 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 break;
1329
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001330 case R.id.active_tabs_menu_id:
1331 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1332 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001333 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001334 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1335 mActiveTabsPage.requestFocus();
1336 mMenuState = EMPTY_MENU;
1337 break;
1338
Leon Scroggins1f005d32009-08-10 17:36:42 -04001339 case R.id.add_bookmark_menu_id:
1340 Intent i = new Intent(BrowserActivity.this,
1341 AddBookmarkPage.class);
1342 WebView w = getTopWindow();
1343 i.putExtra("url", w.getUrl());
1344 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001345 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001346 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001347 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001348 break;
1349
1350 case R.id.stop_reload_menu_id:
1351 if (mInLoad) {
1352 stopLoading();
1353 } else {
1354 getTopWindow().reload();
1355 }
1356 break;
1357
1358 case R.id.back_menu_id:
1359 getTopWindow().goBack();
1360 break;
1361
1362 case R.id.forward_menu_id:
1363 getTopWindow().goForward();
1364 break;
1365
1366 case R.id.close_menu_id:
1367 // Close the subwindow if it exists.
1368 if (mTabControl.getCurrentSubWindow() != null) {
1369 dismissSubWindow(mTabControl.getCurrentTab());
1370 break;
1371 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 break;
1374
1375 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001376 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 if (current != null) {
1378 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001379 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001380 }
1381 break;
1382
1383 case R.id.preferences_menu_id:
1384 Intent intent = new Intent(this,
1385 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001386 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1387 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001388 startActivityForResult(intent, PREFERENCES_PAGE);
1389 break;
1390
1391 case R.id.find_menu_id:
Cary Clark2c326e62010-08-19 18:40:57 -04001392 showFindDialog();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 break;
1394
1395 case R.id.select_text_id:
Cary Clark5feb8ad2010-09-21 14:28:49 -04001396 if (true) {
1397 Tab currentTab = mTabControl.getCurrentTab();
1398 if (currentTab != null) {
1399 currentTab.getWebView().setUpSelect();
1400 }
1401 } else {
1402 showSelectDialog();
1403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001404 break;
Cary Clark2c326e62010-08-19 18:40:57 -04001405
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 case R.id.page_info_menu_id:
1407 showPageInfo(mTabControl.getCurrentTab(), false);
1408 break;
1409
1410 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001411 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 break;
1413
Leon Scroggins96afcb12009-12-10 12:35:56 -05001414 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001416 Tab currentTab = mTabControl.getCurrentTab();
1417 if (null == currentTab) {
1418 mCanChord = false;
1419 return false;
1420 }
1421 currentTab.populatePickerData();
1422 sharePage(this, currentTab.getTitle(),
1423 currentTab.getUrl(), currentTab.getFavicon(),
1424 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 break;
1426
1427 case R.id.dump_nav_menu_id:
1428 getTopWindow().debugDump();
1429 break;
1430
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001431 case R.id.dump_counters_menu_id:
1432 getTopWindow().dumpV8Counters();
1433 break;
1434
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 case R.id.zoom_in_menu_id:
1436 getTopWindow().zoomIn();
1437 break;
1438
1439 case R.id.zoom_out_menu_id:
1440 getTopWindow().zoomOut();
1441 break;
1442
1443 case R.id.view_downloads_menu_id:
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04001444 viewDownloads();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001445 break;
1446
The Android Open Source Project0c908882009-03-03 19:32:16 -08001447 case R.id.window_one_menu_id:
1448 case R.id.window_two_menu_id:
1449 case R.id.window_three_menu_id:
1450 case R.id.window_four_menu_id:
1451 case R.id.window_five_menu_id:
1452 case R.id.window_six_menu_id:
1453 case R.id.window_seven_menu_id:
1454 case R.id.window_eight_menu_id:
1455 {
1456 int menuid = item.getItemId();
1457 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1458 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001459 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001460 if (desiredTab != null &&
1461 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001462 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001463 }
1464 break;
1465 }
1466 }
1467 }
1468 break;
1469
1470 default:
1471 if (!super.onOptionsItemSelected(item)) {
1472 return false;
1473 }
1474 // Otherwise fall through.
1475 }
1476 mCanChord = false;
1477 return true;
1478 }
1479
Cary Clark2c326e62010-08-19 18:40:57 -04001480 private boolean dialogIsUp() {
1481 return null != mFindDialog && mFindDialog.isVisible() ||
1482 null != mSelectDialog && mSelectDialog.isVisible();
1483 }
1484
1485 private boolean closeDialog(WebDialog dialog) {
1486 if (null == dialog || !dialog.isVisible()) return false;
1487 Tab currentTab = mTabControl.getCurrentTab();
1488 currentTab.closeDialog(dialog);
1489 dialog.dismiss();
1490 return true;
1491 }
1492
1493 /*
1494 * Remove the find dialog or select dialog.
1495 */
1496 public void closeDialogs() {
1497 if (!(closeDialog(mFindDialog) || closeDialog(mSelectDialog))) return;
1498 // If the Find was being performed in the main WebView, replace the
1499 // embedded title bar.
1500 Tab currentTab = mTabControl.getCurrentTab();
1501 if (currentTab.getSubWebView() == null) {
1502 WebView mainView = currentTab.getWebView();
1503 if (mainView != null) {
1504 mainView.setEmbeddedTitleBar(mTitleBar);
1505 }
1506 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 mMenuState = R.id.MAIN_MENU;
Cary Clark2c326e62010-08-19 18:40:57 -04001508 if (mInLoad) {
1509 // The title bar was hidden, because otherwise it would cover up the
1510 // find or select dialog. Now that the dialog has been removed,
1511 // show the fake title bar once again.
1512 showFakeTitleBar();
1513 }
1514 }
1515
1516 public void showFindDialog() {
1517 if (null == mFindDialog) {
1518 mFindDialog = new FindDialog(this);
1519 }
1520 showDialog(mFindDialog).setFindIsUp(true);
1521 }
1522
1523 public void setFindDialogText(String text) {
1524 mFindDialog.setText(text);
1525 }
1526
1527 public void showSelectDialog() {
1528 if (null == mSelectDialog) {
1529 mSelectDialog = new SelectDialog(this);
1530 }
1531 showDialog(mSelectDialog).setUpSelect();
1532 mSelectDialog.hideSoftInput();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 }
1534
Grace Kloba22ac16e2009-10-07 18:00:23 -07001535 @Override
1536 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 // This happens when the user begins to hold down the menu key, so
1538 // allow them to chord to get a shortcut.
1539 mCanChord = true;
1540 // Note: setVisible will decide whether an item is visible; while
1541 // setEnabled() will decide whether an item is enabled, which also means
1542 // whether the matching shortcut key will function.
1543 super.onPrepareOptionsMenu(menu);
1544 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 case EMPTY_MENU:
1546 if (mCurrentMenuState != mMenuState) {
1547 menu.setGroupVisible(R.id.MAIN_MENU, false);
1548 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1549 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 }
1551 break;
1552 default:
1553 if (mCurrentMenuState != mMenuState) {
1554 menu.setGroupVisible(R.id.MAIN_MENU, true);
1555 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1556 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 }
1558 final WebView w = getTopWindow();
1559 boolean canGoBack = false;
1560 boolean canGoForward = false;
1561 boolean isHome = false;
1562 if (w != null) {
1563 canGoBack = w.canGoBack();
1564 canGoForward = w.canGoForward();
1565 isHome = mSettings.getHomePage().equals(w.getUrl());
1566 }
1567 final MenuItem back = menu.findItem(R.id.back_menu_id);
1568 back.setEnabled(canGoBack);
1569
1570 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1571 home.setEnabled(!isHome);
1572
1573 menu.findItem(R.id.forward_menu_id)
1574 .setEnabled(canGoForward);
1575
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001576 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001577 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001578
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 // decide whether to show the share link option
1580 PackageManager pm = getPackageManager();
1581 Intent send = new Intent(Intent.ACTION_SEND);
1582 send.setType("text/plain");
1583 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1584 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1585
The Android Open Source Project0c908882009-03-03 19:32:16 -08001586 boolean isNavDump = mSettings.isNavDump();
1587 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1588 nav.setVisible(isNavDump);
1589 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001590
1591 boolean showDebugSettings = mSettings.showDebugSettings();
1592 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1593 counter.setVisible(showDebugSettings);
1594 counter.setEnabled(showDebugSettings);
1595
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 break;
1597 }
1598 mCurrentMenuState = mMenuState;
1599 return true;
1600 }
1601
1602 @Override
1603 public void onCreateContextMenu(ContextMenu menu, View v,
1604 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001605 if (v instanceof TitleBar) {
1606 return;
1607 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001608 WebView webview = (WebView) v;
1609 WebView.HitTestResult result = webview.getHitTestResult();
1610 if (result == null) {
1611 return;
1612 }
1613
1614 int type = result.getType();
1615 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1616 Log.w(LOGTAG,
1617 "We should not show context menu when nothing is touched");
1618 return;
1619 }
1620 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1621 // let TextView handles context menu
1622 return;
1623 }
1624
1625 // Note, http://b/issue?id=1106666 is requesting that
1626 // an inflated menu can be used again. This is not available
1627 // yet, so inflate each time (yuk!)
1628 MenuInflater inflater = getMenuInflater();
1629 inflater.inflate(R.menu.browsercontext, menu);
1630
1631 // Show the correct menu group
1632 String extra = result.getExtra();
1633 menu.setGroupVisible(R.id.PHONE_MENU,
1634 type == WebView.HitTestResult.PHONE_TYPE);
1635 menu.setGroupVisible(R.id.EMAIL_MENU,
1636 type == WebView.HitTestResult.EMAIL_TYPE);
1637 menu.setGroupVisible(R.id.GEO_MENU,
1638 type == WebView.HitTestResult.GEO_TYPE);
1639 menu.setGroupVisible(R.id.IMAGE_MENU,
1640 type == WebView.HitTestResult.IMAGE_TYPE
1641 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1642 menu.setGroupVisible(R.id.ANCHOR_MENU,
1643 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1644 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1645
1646 // Setup custom handling depending on the type
1647 switch (type) {
1648 case WebView.HitTestResult.PHONE_TYPE:
1649 menu.setHeaderTitle(Uri.decode(extra));
1650 menu.findItem(R.id.dial_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_TEL + extra)));
1653 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1654 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001655 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1657 addIntent);
1658 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1659 new Copy(extra));
1660 break;
1661
1662 case WebView.HitTestResult.EMAIL_TYPE:
1663 menu.setHeaderTitle(extra);
1664 menu.findItem(R.id.email_context_menu_id).setIntent(
1665 new Intent(Intent.ACTION_VIEW, Uri
1666 .parse(WebView.SCHEME_MAILTO + extra)));
1667 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1668 new Copy(extra));
1669 break;
1670
1671 case WebView.HitTestResult.GEO_TYPE:
1672 menu.setHeaderTitle(extra);
1673 menu.findItem(R.id.map_context_menu_id).setIntent(
1674 new Intent(Intent.ACTION_VIEW, Uri
1675 .parse(WebView.SCHEME_GEO
1676 + URLEncoder.encode(extra))));
1677 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1678 new Copy(extra));
1679 break;
1680
1681 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1682 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1683 TextView titleView = (TextView) LayoutInflater.from(this)
1684 .inflate(android.R.layout.browser_link_context_header,
1685 null);
1686 titleView.setText(extra);
1687 menu.setHeaderView(titleView);
1688 // decide whether to show the open link in new tab option
1689 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001690 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001691 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1692 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 PackageManager pm = getPackageManager();
1694 Intent send = new Intent(Intent.ACTION_SEND);
1695 send.setType("text/plain");
1696 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1697 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1698 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1699 break;
1700 }
1701 // otherwise fall through to handle image part
1702 case WebView.HitTestResult.IMAGE_TYPE:
1703 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1704 menu.setHeaderTitle(extra);
1705 }
1706 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1708 menu.findItem(R.id.download_context_menu_id).
1709 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001710 menu.findItem(R.id.set_wallpaper_context_menu_id).
1711 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 break;
1713
1714 default:
1715 Log.w(LOGTAG, "We should not get here.");
1716 break;
1717 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001718 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001719 }
1720
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001722 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001724 // Attach the container that contains the main WebView and any other UI
1725 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727
1728 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730 if (errorConsole.numberOfErrors() == 0) {
1731 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1732 } else {
1733 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1734 }
1735
1736 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001737 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001738 ViewGroup.LayoutParams.WRAP_CONTENT));
1739 }
1740
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001741 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001742 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001743 if (t.isInVoiceSearchMode()) {
1744 showVoiceTitleBar(t.getVoiceDisplayTitle());
1745 } else {
1746 revertVoiceTitleBar();
1747 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 // Request focus on the top window.
1749 t.getTopWindow().requestFocus();
1750 }
1751
1752 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001754 t.attachSubWindow(mContentView);
1755 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001756 }
1757
1758 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001759 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001760 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001761 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001762
Grace Kloba22ac16e2009-10-07 18:00:23 -07001763 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1764 if (errorConsole != null) {
1765 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001766 }
1767
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001768 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001769 if (view != null) {
1770 view.setEmbeddedTitleBar(null);
1771 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001772 }
1773
1774 // Remove the sub window if it exists. Also called by TabControl when the
1775 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001776 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001777 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001778 // dismiss the subwindow. This will destroy the WebView.
1779 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001780 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001781 }
1782
Leon Scroggins1f005d32009-08-10 17:36:42 -04001783 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001784 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 }
1788
1789 // This method does a ton of stuff. It will attempt to create a new tab
1790 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001791 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001792 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1793 String appId) {
John Reckafa4ab12011-06-20 18:30:26 -07001794 Tab currentTab = mTabControl.getCurrentTab();
1795 if (!mTabControl.canCreateNewTab()) {
1796 Tab closeTab = mTabControl.getTab(0);
1797 closeTab(closeTab);
1798 if (closeTab == currentTab) {
1799 currentTab = null;
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001800 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
John Reckafa4ab12011-06-20 18:30:26 -07001802 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1803 urlData.mUrl);
1804 WebView webview = tab.getWebView();
1805 // If the last tab was removed from the active tabs page, currentTab
1806 // will be null.
1807 if (currentTab != null) {
1808 removeTabFromContentView(currentTab);
1809 }
1810 // We must set the new tab as the current tab to reflect the old
1811 // animation behavior.
1812 mTabControl.setCurrentTab(tab);
1813 attachTabToContentView(tab);
1814 if (!urlData.isEmpty()) {
1815 loadUrlDataIn(tab, urlData);
1816 }
1817 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 }
1819
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001824 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001825 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 }
Grace Klobac9181842009-04-14 08:53:22 -07001827 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831 }
1832
1833 private class Copy implements OnMenuItemClickListener {
1834 private CharSequence mText;
1835
1836 public boolean onMenuItemClick(MenuItem item) {
1837 copy(mText);
1838 return true;
1839 }
1840
1841 public Copy(CharSequence toCopy) {
1842 mText = toCopy;
1843 }
1844 }
1845
1846 private class Download implements OnMenuItemClickListener {
1847 private String mText;
1848
1849 public boolean onMenuItemClick(MenuItem item) {
1850 onDownloadStartNoStream(mText, null, null, null, -1);
1851 return true;
1852 }
1853
1854 public Download(String toDownload) {
1855 mText = toDownload;
1856 }
1857 }
1858
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001859 private class SetAsWallpaper extends Thread implements
1860 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1861 private URL mUrl;
1862 private ProgressDialog mWallpaperProgress;
1863 private boolean mCanceled = false;
1864
1865 public SetAsWallpaper(String url) {
1866 try {
1867 mUrl = new URL(url);
1868 } catch (MalformedURLException e) {
1869 mUrl = null;
1870 }
1871 }
1872
1873 public void onCancel(DialogInterface dialog) {
1874 mCanceled = true;
1875 }
1876
1877 public boolean onMenuItemClick(MenuItem item) {
1878 if (mUrl != null) {
1879 // The user may have tried to set a image with a large file size as their
1880 // background so it may take a few moments to perform the operation. Display
1881 // a progress spinner while it is working.
1882 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1883 mWallpaperProgress.setIndeterminate(true);
1884 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1885 mWallpaperProgress.setCancelable(true);
1886 mWallpaperProgress.setOnCancelListener(this);
1887 mWallpaperProgress.show();
1888 start();
1889 }
1890 return true;
1891 }
1892
1893 public void run() {
1894 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1895 try {
1896 // TODO: This will cause the resource to be downloaded again, when we
1897 // should in most cases be able to grab it from the cache. To fix this
1898 // we should query WebCore to see if we can access a cached version and
1899 // instead open an input stream on that. This pattern could also be used
1900 // in the download manager where the same problem exists.
1901 InputStream inputstream = mUrl.openStream();
1902 if (inputstream != null) {
1903 setWallpaper(inputstream);
1904 }
1905 } catch (IOException e) {
1906 Log.e(LOGTAG, "Unable to set new wallpaper");
1907 // Act as though the user canceled the operation so we try to
1908 // restore the old wallpaper.
1909 mCanceled = true;
1910 }
1911
1912 if (mCanceled) {
1913 // Restore the old wallpaper if the user cancelled whilst we were setting
1914 // the new wallpaper.
1915 int width = oldWallpaper.getIntrinsicWidth();
1916 int height = oldWallpaper.getIntrinsicHeight();
1917 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1918 Canvas canvas = new Canvas(bm);
1919 oldWallpaper.setBounds(0, 0, width, height);
1920 oldWallpaper.draw(canvas);
1921 try {
1922 setWallpaper(bm);
1923 } catch (IOException e) {
1924 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1925 }
1926 mCanceled = false;
1927 }
1928
1929 if (mWallpaperProgress.isShowing()) {
1930 mWallpaperProgress.dismiss();
1931 }
1932 }
1933 }
1934
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 private void copy(CharSequence text) {
1936 try {
1937 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1938 if (clip != null) {
1939 clip.setClipboardText(text);
1940 }
1941 } catch (android.os.RemoteException e) {
1942 Log.e(LOGTAG, "Copy failed", e);
1943 }
1944 }
1945
1946 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001947 * Resets the browser title-view to whatever it must be
1948 * (for example, if we had a loading error)
1949 * When we have a new page, we call resetTitle, when we
1950 * have to reset the titlebar to whatever it used to be
1951 * (for example, if the user chose to stop loading), we
1952 * call resetTitleAndRevertLockIcon.
1953 */
1954 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001955 mTabControl.getCurrentTab().revertLockIcon();
1956 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001957 resetTitleIconAndProgress();
1958 }
1959
1960 /**
1961 * Reset the title, favicon, and progress.
1962 */
1963 private void resetTitleIconAndProgress() {
1964 WebView current = mTabControl.getCurrentWebView();
1965 if (current == null) {
1966 return;
1967 }
1968 resetTitleAndIcon(current);
1969 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001970 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 }
1972
1973 // Reset the title and the icon based on the given item.
1974 private void resetTitleAndIcon(WebView view) {
1975 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1976 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001977 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001978 setFavicon(item.getFavicon());
1979 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001980 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 setFavicon(null);
1982 }
1983 }
1984
1985 /**
1986 * Sets a title composed of the URL and the title string.
1987 * @param url The URL of the site being loaded.
1988 * @param title The title of the site being loaded.
1989 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001990 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 mUrl = url;
1992 mTitle = title;
1993
Leon Scroggins58d56c62010-01-28 15:12:40 -05001994 // If we are in voice search mode, the title has already been set.
1995 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1996 mTitleBar.setDisplayTitle(url);
1997 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001998 }
1999
2000 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 * @param url The URL to build a title version of the URL from.
2002 * @return The title version of the URL or null if fails.
2003 * The title version of the URL can be either the URL hostname,
2004 * or the hostname with an "https://" prefix (for secure URLs),
2005 * or an empty string if, for example, the URL in question is a
2006 * file:// URL with no hostname.
2007 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002008 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002009 String titleUrl = null;
2010
2011 if (url != null) {
2012 try {
2013 // parse the url string
2014 URL urlObj = new URL(url);
2015 if (urlObj != null) {
2016 titleUrl = "";
2017
2018 String protocol = urlObj.getProtocol();
2019 String host = urlObj.getHost();
2020
2021 if (host != null && 0 < host.length()) {
2022 titleUrl = host;
2023 if (protocol != null) {
2024 // if a secure site, add an "https://" prefix!
2025 if (protocol.equalsIgnoreCase("https")) {
2026 titleUrl = protocol + "://" + host;
2027 }
2028 }
2029 }
2030 }
2031 } catch (MalformedURLException e) {}
2032 }
2033
2034 return titleUrl;
2035 }
2036
2037 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002039 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002040 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002041 }
2042
2043 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002044 * Close the tab, remove its associated title bar, and adjust mTabControl's
2045 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002046 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002047 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002048 int currentIndex = mTabControl.getCurrentIndex();
2049 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002050 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002051 if (currentIndex >= removeIndex && currentIndex != 0) {
2052 currentIndex--;
2053 }
2054 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002055 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 }
2057
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002058 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002059 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 if (current == null) {
2061 /*
2062 * Instead of finishing the activity, simply push this to the back
2063 * of the stack and let ActivityManager to choose the foreground
2064 * activity. As BrowserActivity is singleTask, it will be always the
2065 * root of the task. So we can use either true or false for
2066 * moveTaskToBack().
2067 */
2068 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002069 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 }
2071 WebView w = current.getWebView();
2072 if (w.canGoBack()) {
2073 w.goBack();
2074 } else {
2075 // Check to see if we are closing a window that was created by
2076 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002077 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002079 switchToTab(mTabControl.getTabIndex(parent));
2080 // Now we close the other tab
2081 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 } else {
2083 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002084 // force the tab's inLoad() to be false as we are going to
2085 // either finish the activity or remove the tab. This will
2086 // ensure pauseWebViewTimers() taking action.
2087 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 if (mTabControl.getTabCount() == 1) {
2089 finish();
2090 return;
2091 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002092 // call pauseWebViewTimers() now, we won't be able to call
2093 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002094 // Temporarily change mActivityInPause to be true as
2095 // pauseWebViewTimers() will do nothing if mActivityInPause
2096 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002097 boolean savedState = mActivityInPause;
2098 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002099 Log.e(LOGTAG, "BrowserActivity is already paused "
2100 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002101 }
2102 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002103 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002104 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 removeTabFromContentView(current);
2106 mTabControl.removeTab(current);
2107 }
2108 /*
2109 * Instead of finishing the activity, simply push this to the back
2110 * of the stack and let ActivityManager to choose the foreground
2111 * activity. As BrowserActivity is singleTask, it will be always the
2112 * root of the task. So we can use either true or false for
2113 * moveTaskToBack().
2114 */
2115 moveTaskToBack(true);
2116 }
2117 }
2118 }
2119
Grace Kloba22ac16e2009-10-07 18:00:23 -07002120 boolean isMenuDown() {
2121 return mMenuIsDown;
2122 }
2123
Grace Kloba5942df02009-09-18 11:48:29 -07002124 @Override
2125 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002126 // Even if MENU is already held down, we need to call to super to open
2127 // the IME on long press.
2128 if (KeyEvent.KEYCODE_MENU == keyCode) {
2129 mMenuIsDown = true;
2130 return super.onKeyDown(keyCode, event);
2131 }
Grace Kloba5942df02009-09-18 11:48:29 -07002132 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2133 // still down, we don't want to trigger the search. Pretend to consume
2134 // the key and do nothing.
2135 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002136
Grace Kloba5942df02009-09-18 11:48:29 -07002137 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002138 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002139 // WebView/WebTextView handle the keys in the KeyDown. As
2140 // the Activity's shortcut keys are only handled when WebView
2141 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2142 if (event.isShiftPressed()) {
2143 getTopWindow().pageUp(false);
2144 } else {
2145 getTopWindow().pageDown(false);
2146 }
Grace Kloba5942df02009-09-18 11:48:29 -07002147 return true;
2148 case KeyEvent.KEYCODE_BACK:
2149 if (event.getRepeatCount() == 0) {
2150 event.startTracking();
2151 return true;
2152 } else if (mCustomView == null && mActiveTabsPage == null
2153 && event.isLongPress()) {
2154 bookmarksOrHistoryPicker(true);
2155 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
Grace Kloba5942df02009-09-18 11:48:29 -07002157 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 }
Grace Kloba5942df02009-09-18 11:48:29 -07002159 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 }
2161
Grace Kloba5942df02009-09-18 11:48:29 -07002162 @Override
2163 public boolean onKeyUp(int keyCode, KeyEvent event) {
2164 switch(keyCode) {
2165 case KeyEvent.KEYCODE_MENU:
2166 mMenuIsDown = false;
2167 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002168 case KeyEvent.KEYCODE_BACK:
2169 if (event.isTracking() && !event.isCanceled()) {
2170 if (mCustomView != null) {
2171 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002172 mTabControl.getCurrentWebView().getWebChromeClient()
2173 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002174 } else if (mActiveTabsPage != null) {
2175 // if tab page is showing, hide it
2176 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002178 WebView subwindow = mTabControl.getCurrentSubWindow();
2179 if (subwindow != null) {
2180 if (subwindow.canGoBack()) {
2181 subwindow.goBack();
2182 } else {
2183 dismissSubWindow(mTabControl.getCurrentTab());
2184 }
2185 } else {
2186 goBackOnePageOrQuit();
2187 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 }
Grace Kloba5942df02009-09-18 11:48:29 -07002189 return true;
2190 }
2191 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002192 }
Grace Kloba5942df02009-09-18 11:48:29 -07002193 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 }
2195
Leon Scroggins68579392009-09-15 15:31:54 -04002196 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002197 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002198 resetTitleAndRevertLockIcon();
2199 WebView w = getTopWindow();
2200 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002201 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2202 // same logic here. But for subwindow case, should we call into the main
2203 // WebView's onPageFinished as we never call its onPageStarted and if
2204 // the page finishes itself, we don't call onPageFinished.
2205 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2206 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207
2208 cancelStopToast();
2209 mStopToast = Toast
2210 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2211 mStopToast.show();
2212 }
2213
Grace Kloba22ac16e2009-10-07 18:00:23 -07002214 boolean didUserStopLoading() {
2215 return mDidStopLoad;
2216 }
2217
The Android Open Source Project0c908882009-03-03 19:32:16 -08002218 private void cancelStopToast() {
2219 if (mStopToast != null) {
2220 mStopToast.cancel();
2221 mStopToast = null;
2222 }
2223 }
2224
Grace Kloba22ac16e2009-10-07 18:00:23 -07002225 // called by a UI or non-UI thread to post the message
2226 public void postMessage(int what, int arg1, int arg2, Object obj,
2227 long delayMillis) {
2228 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2229 obj), delayMillis);
2230 }
2231
2232 // called by a UI or non-UI thread to remove the message
2233 void removeMessages(int what, Object object) {
2234 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235 }
2236
2237 // public message ids
2238 public final static int LOAD_URL = 1001;
2239 public final static int STOP_LOAD = 1002;
2240
2241 // Message Ids
2242 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002243 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244
Grace Kloba22ac16e2009-10-07 18:00:23 -07002245 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002246
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 // Private handler for handling javascript and saving passwords
2248 private Handler mHandler = new Handler() {
2249
2250 public void handleMessage(Message msg) {
2251 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002253 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002255 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 if (url == null || url.length() == 0) {
2257 break;
2258 }
2259 HashMap focusNodeMap = (HashMap) msg.obj;
2260 WebView view = (WebView) focusNodeMap.get("webview");
2261 // Only apply the action if the top window did not change.
2262 if (getTopWindow() != view) {
2263 break;
2264 }
2265 switch (msg.arg1) {
2266 case R.id.open_context_menu_id:
2267 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002268 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002269 break;
2270 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 final Tab parent = mTabControl.getCurrentTab();
2272 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002273 if (newTab != parent) {
2274 parent.addChildTab(newTab);
2275 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 break;
2277 case R.id.bookmark_context_menu_id:
2278 Intent intent = new Intent(BrowserActivity.this,
2279 AddBookmarkPage.class);
2280 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002281 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002282 startActivity(intent);
2283 break;
2284 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002285 // See if this site has been visited before
2286 StringBuilder sb = new StringBuilder(
2287 Browser.BookmarkColumns.URL + " = ");
2288 DatabaseUtils.appendEscapedSQLString(sb, url);
Henrik Baarde2629032010-10-04 12:18:43 +02002289 Cursor c = null;
2290 try {
2291 c = mResolver.query(Browser.BOOKMARKS_URI,
2292 Browser.HISTORY_PROJECTION,
2293 sb.toString(),
2294 null,
2295 null);
2296 if (c.moveToFirst()) {
2297 // The site has been visited before, so grab the
2298 // info from the database.
2299 Bitmap favicon = null;
2300 Bitmap thumbnail = null;
2301 String linkTitle = c.getString(Browser.
2302 HISTORY_PROJECTION_TITLE_INDEX);
2303 byte[] data = c.getBlob(Browser.
2304 HISTORY_PROJECTION_FAVICON_INDEX);
2305 if (data != null) {
2306 favicon = BitmapFactory.decodeByteArray(
2307 data, 0, data.length);
2308 }
2309 data = c.getBlob(Browser.
2310 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2311 if (data != null) {
2312 thumbnail = BitmapFactory.decodeByteArray(
2313 data, 0, data.length);
2314 }
2315 sharePage(BrowserActivity.this,
2316 linkTitle, url, favicon, thumbnail);
2317 } else {
2318 Browser.sendString(BrowserActivity.this, url,
2319 getString(
2320 R.string.choosertitle_sharevia));
Leon Scroggins96afcb12009-12-10 12:35:56 -05002321 }
Henrik Baarde2629032010-10-04 12:18:43 +02002322 } finally {
2323 if (c != null) c.close();
Leon Scroggins96afcb12009-12-10 12:35:56 -05002324 }
Channagoud Kadabi37182262010-09-15 23:48:29 -07002325 // close the cursor after its used
2326 if (c != null) {
2327 c.close();
2328 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 break;
2330 case R.id.copy_link_context_menu_id:
2331 copy(url);
2332 break;
2333 case R.id.save_link_context_menu_id:
2334 case R.id.download_context_menu_id:
2335 onDownloadStartNoStream(url, null, null, null, -1);
2336 break;
2337 }
2338 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002339 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002340
2341 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002342 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 break;
2344
2345 case STOP_LOAD:
2346 stopLoading();
2347 break;
2348
The Android Open Source Project0c908882009-03-03 19:32:16 -08002349 case RELEASE_WAKELOCK:
2350 if (mWakeLock.isHeld()) {
2351 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002352 // if we reach here, Browser should be still in the
2353 // background loading after WAKELOCK_TIMEOUT (5-min).
2354 // To avoid burning the battery, stop loading.
2355 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 }
2357 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002358
2359 case UPDATE_BOOKMARK_THUMBNAIL:
2360 WebView view = (WebView) msg.obj;
2361 if (view != null) {
2362 updateScreenshot(view);
2363 }
2364 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 }
2366 }
2367 };
2368
Leon Scroggins96afcb12009-12-10 12:35:56 -05002369 /**
2370 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2371 * an {@link Intent} to launch the Activity chooser.
2372 * @param c Context used to launch a new Activity.
2373 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002374 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002375 * @param url URL of the page. Stored in the Intent with
2376 * {@link Intent#EXTRA_TEXT}
2377 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2378 * with {@link Browser#EXTRA_SHARE_FAVICON}
2379 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2380 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2381 */
2382 public static final void sharePage(Context c, String title, String url,
2383 Bitmap favicon, Bitmap screenshot) {
2384 Intent send = new Intent(Intent.ACTION_SEND);
2385 send.setType("text/plain");
2386 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002387 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002388 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2389 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2390 try {
2391 c.startActivity(Intent.createChooser(send, c.getString(
2392 R.string.choosertitle_sharevia)));
2393 } catch(android.content.ActivityNotFoundException ex) {
2394 // if no app handles it, do nothing
2395 }
2396 }
2397
Leon Scroggins89c6d362009-07-15 16:54:37 -04002398 private void updateScreenshot(WebView view) {
2399 // If this is a bookmarked site, add a screenshot to the database.
2400 // FIXME: When should we update? Every time?
2401 // FIXME: Would like to make sure there is actually something to
2402 // draw, but the API for that (WebViewCore.pictureReady()) is not
2403 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002404
Patrick Scottcb192b52010-04-14 14:38:55 -04002405 final Bitmap bm = createScreenshot(view);
2406 if (bm == null) {
2407 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002408 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002409
2410 final ContentResolver cr = getContentResolver();
2411 final String url = view.getUrl();
2412 final String originalUrl = view.getOriginalUrl();
2413
2414 new AsyncTask<Void, Void, Void>() {
2415 @Override
2416 protected Void doInBackground(Void... unused) {
2417 Cursor c = null;
2418 try {
2419 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2420 cr, originalUrl, url, true);
2421 if (c != null) {
2422 if (c.moveToFirst()) {
2423 ContentValues values = new ContentValues();
2424 final ByteArrayOutputStream os
2425 = new ByteArrayOutputStream();
2426 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2427 values.put(Browser.BookmarkColumns.THUMBNAIL,
2428 os.toByteArray());
2429 do {
2430 cr.update(ContentUris.withAppendedId(
2431 Browser.BOOKMARKS_URI, c.getInt(0)),
2432 values, null, null);
2433 } while (c.moveToNext());
2434 }
2435 }
2436 } catch (IllegalStateException e) {
2437 // Ignore
2438 } finally {
2439 if (c != null) c.close();
2440 }
2441 return null;
2442 }
2443 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002444 }
2445
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002446 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002447 * Values for the size of the thumbnail created when taking a screenshot.
2448 * Lazily initialized. Instead of using these directly, use
2449 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002450 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002451 private static int THUMBNAIL_WIDTH = 0;
2452 private static int THUMBNAIL_HEIGHT = 0;
2453
2454 /**
2455 * Return the desired width for thumbnail screenshots, which are stored in
2456 * the database, and used on the bookmarks screen.
2457 * @param context Context for finding out the density of the screen.
2458 * @return int desired width for thumbnail screenshot.
2459 */
2460 /* package */ static int getDesiredThumbnailWidth(Context context) {
2461 if (THUMBNAIL_WIDTH == 0) {
2462 float density = context.getResources().getDisplayMetrics().density;
2463 THUMBNAIL_WIDTH = (int) (90 * density);
2464 THUMBNAIL_HEIGHT = (int) (80 * density);
2465 }
2466 return THUMBNAIL_WIDTH;
2467 }
2468
2469 /**
2470 * Return the desired height for thumbnail screenshots, which are stored in
2471 * the database, and used on the bookmarks screen.
2472 * @param context Context for finding out the density of the screen.
2473 * @return int desired height for thumbnail screenshot.
2474 */
2475 /* package */ static int getDesiredThumbnailHeight(Context context) {
2476 // To ensure that they are both initialized.
2477 getDesiredThumbnailWidth(context);
2478 return THUMBNAIL_HEIGHT;
2479 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002480
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002481 private Bitmap createScreenshot(WebView view) {
2482 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002483 if (thumbnail == null) {
2484 return null;
2485 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002486 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002487 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002488 Canvas canvas = new Canvas(bm);
2489 // May need to tweak these values to determine what is the
2490 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002491 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002492 int thumbnailHeight = thumbnail.getHeight();
2493 float scaleFactorX = 1.0f;
2494 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002495 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002496 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002497 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002498 } else {
2499 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002500 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002501
2502 if (view.getWidth() > view.getHeight() &&
2503 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2504 // If the device is in landscape and the page is shorter
2505 // than the height of the view, stretch the thumbnail to fill the
2506 // space.
2507 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2508 (float)thumbnailHeight;
2509 } else {
2510 // In the portrait case, this looks nice.
2511 scaleFactorY = scaleFactorX;
2512 }
2513
2514 canvas.scale(scaleFactorX, scaleFactorY);
2515
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002516 thumbnail.draw(canvas);
2517 return bm;
2518 }
2519
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002521 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002522 //-------------------------------------------------------------------------
2523
2524 // Use in overrideUrlLoading
2525 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2526 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2527 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2528 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2529
Leon Scroggins92472e82010-02-17 16:32:28 -05002530 // Keep this initial progress in sync with initialProgressValue (* 100)
2531 // in ProgressTracker.cpp
2532 private final static int INITIAL_PROGRESS = 10;
2533
Grace Kloba22ac16e2009-10-07 18:00:23 -07002534 void onPageStarted(WebView view, String url, Bitmap favicon) {
2535 // when BrowserActivity just starts, onPageStarted may be called before
2536 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2537 // to start the timer. As we won't switch tabs while an activity is in
2538 // pause state, we can ensure calling resume and pause in pair.
2539 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 resetLockIcon(url);
2542 setUrlTitle(url, null);
2543 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002544 // Show some progress so that the user knows the page is beginning to
2545 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002546 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002547 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002548 if (!mIsNetworkUp) createAndShowNetworkDialog();
Cary Clark2c326e62010-08-19 18:40:57 -04002549 closeDialogs();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 if (mSettings.isTracing()) {
2551 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002552 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002553 WebAddress uri = new WebAddress(url);
2554 host = uri.mHost;
2555 } catch (android.net.ParseException ex) {
2556 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002558 host = host.replace('.', '_');
2559 host += ".trace";
2560 mInTrace = true;
2561 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2562 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002563
Grace Kloba22ac16e2009-10-07 18:00:23 -07002564 // Performance probe
2565 if (false) {
2566 mStart = SystemClock.uptimeMillis();
2567 mProcessStart = Process.getElapsedCpuTime();
2568 long[] sysCpu = new long[7];
2569 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2570 sysCpu, null)) {
2571 mUserStart = sysCpu[0] + sysCpu[1];
2572 mSystemStart = sysCpu[2];
2573 mIdleStart = sysCpu[3];
2574 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2575 }
2576 mUiStart = SystemClock.currentThreadTimeMillis();
2577 }
2578 }
2579
2580 void onPageFinished(WebView view, String url) {
2581 // Reset the title and icon in case we stopped a provisional load.
2582 resetTitleAndIcon(view);
2583 // Update the lock icon image only once we are done loading
2584 updateLockIconToLatest();
2585 // pause the WebView timer and release the wake lock if it is finished
2586 // while BrowserActivity is in pause state.
2587 if (mActivityInPause && pauseWebViewTimers()) {
2588 if (mWakeLock.isHeld()) {
2589 mHandler.removeMessages(RELEASE_WAKELOCK);
2590 mWakeLock.release();
2591 }
2592 }
2593
2594 // Performance probe
2595 if (false) {
2596 long[] sysCpu = new long[7];
2597 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2598 sysCpu, null)) {
2599 String uiInfo = "UI thread used "
2600 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2601 + " ms";
2602 if (LOGD_ENABLED) {
2603 Log.d(LOGTAG, uiInfo);
2604 }
2605 //The string that gets written to the log
2606 String performanceString = "It took total "
2607 + (SystemClock.uptimeMillis() - mStart)
2608 + " ms clock time to load the page."
2609 + "\nbrowser process used "
2610 + (Process.getElapsedCpuTime() - mProcessStart)
2611 + " ms, user processes used "
2612 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2613 + " ms, kernel used "
2614 + (sysCpu[2] - mSystemStart) * 10
2615 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2616 + " ms and irq took "
2617 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2618 * 10 + " ms, " + uiInfo;
2619 if (LOGD_ENABLED) {
2620 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2621 }
2622 if (url != null) {
2623 // strip the url to maintain consistency
2624 String newUrl = new String(url);
2625 if (newUrl.startsWith("http://www.")) {
2626 newUrl = newUrl.substring(11);
2627 } else if (newUrl.startsWith("http://")) {
2628 newUrl = newUrl.substring(7);
2629 } else if (newUrl.startsWith("https://www.")) {
2630 newUrl = newUrl.substring(12);
2631 } else if (newUrl.startsWith("https://")) {
2632 newUrl = newUrl.substring(8);
2633 }
2634 if (LOGD_ENABLED) {
2635 Log.d(LOGTAG, newUrl + " loaded");
2636 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002637 }
2638 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002640
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 if (mInTrace) {
2642 mInTrace = false;
2643 Debug.stopMethodTracing();
2644 }
2645 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002646
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 boolean shouldOverrideUrlLoading(WebView view, String url) {
2648 if (url.startsWith(SCHEME_WTAI)) {
2649 // wtai://wp/mc;number
2650 // number=string(phone-number)
2651 if (url.startsWith(SCHEME_WTAI_MC)) {
2652 Intent intent = new Intent(Intent.ACTION_VIEW,
2653 Uri.parse(WebView.SCHEME_TEL +
2654 url.substring(SCHEME_WTAI_MC.length())));
2655 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002656 return true;
2657 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002658 // wtai://wp/sd;dtmf
2659 // dtmf=string(dialstring)
2660 if (url.startsWith(SCHEME_WTAI_SD)) {
2661 // TODO: only send when there is active voice connection
2662 return false;
2663 }
2664 // wtai://wp/ap;number;name
2665 // number=string(phone-number)
2666 // name=string
2667 if (url.startsWith(SCHEME_WTAI_AP)) {
2668 // TODO
2669 return false;
2670 }
2671 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002672
Grace Kloba22ac16e2009-10-07 18:00:23 -07002673 // The "about:" schemes are internal to the browser; don't want these to
John Reck096bae22011-06-21 14:15:19 -07002674 // be dispatched to other apps. Similarly, javascript: schemas are private
2675 // to the page
2676 if (url.startsWith("about:") || url.startsWith("javascript:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002677 return false;
2678 }
2679
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 Intent intent;
2681 // perform generic parsing of the URI to turn it into an Intent.
2682 try {
2683 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2684 } catch (URISyntaxException ex) {
2685 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2686 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002687 }
2688
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 // check whether the intent can be resolved. If not, we will see
2690 // whether we can download it from the Market.
2691 if (getPackageManager().resolveActivity(intent, 0) == null) {
2692 String packagename = intent.getPackage();
2693 if (packagename != null) {
2694 intent = new Intent(Intent.ACTION_VIEW, Uri
2695 .parse("market://search?q=pname:" + packagename));
2696 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2697 startActivity(intent);
2698 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002699 } else {
2700 return false;
2701 }
2702 }
2703
Grace Kloba22ac16e2009-10-07 18:00:23 -07002704 // sanitize the Intent, ensuring web pages can not bypass browser
2705 // security (only access to BROWSABLE activities).
2706 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2707 intent.setComponent(null);
2708 try {
2709 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002710 return true;
2711 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002712 } catch (ActivityNotFoundException ex) {
2713 // ignore the error. If no application can handle the URL,
2714 // eg about:blank, assume the browser can handle it.
2715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716
Grace Kloba22ac16e2009-10-07 18:00:23 -07002717 if (mMenuIsDown) {
2718 openTab(url);
2719 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 return true;
2721 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 return false;
2723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002724
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 // -------------------------------------------------------------------------
2726 // Helper function for WebChromeClient
2727 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 if (newProgress == 100) {
2733 // onProgressChanged() may continue to be called after the main
2734 // frame has finished loading, as any remaining sub frames continue
2735 // to load. We'll only get called once though with newProgress as
2736 // 100 when everything is loaded. (onPageFinished is called once
2737 // when the main frame completes loading regardless of the state of
2738 // any sub frames so calls to onProgressChanges may continue after
2739 // onPageFinished has executed)
2740 if (mInLoad) {
2741 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002742 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 // If the options menu is open, leave the title bar
2744 if (!mOptionsMenuOpen || !mIconView) {
2745 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002746 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002748 } else {
2749 if (!mInLoad) {
2750 // onPageFinished may have already been called but a subframe is
2751 // still loading and updating the progress. Reset mInLoad and
2752 // update the menu items.
2753 mInLoad = true;
2754 updateInLoadMenuItems();
2755 }
2756 // When the page first begins to load, the Activity may still be
2757 // paused, in which case showFakeTitleBar will do nothing. Call
2758 // again as the page continues to load so that it will be shown.
2759 // (Calling it will the fake title bar is already showing will also
2760 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 if (!mOptionsMenuOpen || mIconView) {
2762 // This page has begun to load, so show the title bar
2763 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
2765 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002766 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002769 // if a view already exists then immediately terminate the new one
2770 if (mCustomView != null) {
2771 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002772 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002773 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002774
2775 // Add the custom view to its container.
2776 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2777 mCustomView = view;
2778 mCustomViewCallback = callback;
2779 // Save the menu state and set it to empty while the custom
2780 // view is showing.
2781 mOldMenuState = mMenuState;
2782 mMenuState = EMPTY_MENU;
2783 // Hide the content view.
2784 mContentView.setVisibility(View.GONE);
2785 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002786 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002787 mCustomViewContainer.setVisibility(View.VISIBLE);
2788 mCustomViewContainer.bringToFront();
2789 }
2790
2791 void onHideCustomView() {
2792 if (mCustomView == null)
2793 return;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 // Hide the custom view.
2795 mCustomView.setVisibility(View.GONE);
2796 // Remove the custom view from its container.
2797 mCustomViewContainer.removeView(mCustomView);
2798 mCustomView = null;
2799 // Reset the old menu state.
2800 mMenuState = mOldMenuState;
2801 mOldMenuState = EMPTY_MENU;
2802 mCustomViewContainer.setVisibility(View.GONE);
2803 mCustomViewCallback.onCustomViewHidden();
2804 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002805 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 mContentView.setVisibility(View.VISIBLE);
2807 }
2808
2809 Bitmap getDefaultVideoPoster() {
2810 if (mDefaultVideoPoster == null) {
2811 mDefaultVideoPoster = BitmapFactory.decodeResource(
2812 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002813 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 return mDefaultVideoPoster;
2815 }
Patrick Scott3918d442009-08-04 13:22:29 -04002816
Grace Kloba22ac16e2009-10-07 18:00:23 -07002817 View getVideoLoadingProgressView() {
2818 if (mVideoProgressView == null) {
2819 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2820 mVideoProgressView = inflater.inflate(
2821 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002823 return mVideoProgressView;
2824 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002825
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002826 /*
2827 * The Object used to inform the WebView of the file to upload.
2828 */
2829 private ValueCallback<Uri> mUploadMessage;
2830
Grace Kloba22ac16e2009-10-07 18:00:23 -07002831 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2832 if (mUploadMessage != null) return;
2833 mUploadMessage = uploadMsg;
2834 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2835 i.addCategory(Intent.CATEGORY_OPENABLE);
2836 i.setType("*/*");
2837 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2838 getString(R.string.choose_upload)), FILE_SELECTED);
2839 }
2840
2841 // -------------------------------------------------------------------------
2842 // Implement functions for DownloadListener
2843 // -------------------------------------------------------------------------
2844
The Android Open Source Project0c908882009-03-03 19:32:16 -08002845 /**
2846 * Notify the host application a download should be done, or that
2847 * the data should be streamed if a streaming viewer is available.
2848 * @param url The full url to the content that should be downloaded
2849 * @param contentDisposition Content-disposition http header, if
2850 * present.
2851 * @param mimetype The mimetype of the content reported by the server
2852 * @param contentLength The file size reported by the server
2853 */
2854 public void onDownloadStart(String url, String userAgent,
2855 String contentDisposition, String mimetype, long contentLength) {
2856 // if we're dealing wih A/V content that's not explicitly marked
2857 // for download, check if it's streamable.
2858 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002859 || !contentDisposition.regionMatches(
2860 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002861 // query the package manager to see if there's a registered handler
2862 // that matches.
2863 Intent intent = new Intent(Intent.ACTION_VIEW);
2864 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002865 ResolveInfo info = getPackageManager().resolveActivity(intent,
2866 PackageManager.MATCH_DEFAULT_ONLY);
2867 if (info != null) {
2868 ComponentName myName = getComponentName();
2869 // If we resolved to ourselves, we don't want to attempt to
2870 // load the url only to try and download it again.
2871 if (!myName.getPackageName().equals(
2872 info.activityInfo.packageName)
2873 || !myName.getClassName().equals(
2874 info.activityInfo.name)) {
2875 // someone (other than us) knows how to handle this mime
2876 // type with this scheme, don't download.
2877 try {
2878 startActivity(intent);
2879 return;
2880 } catch (ActivityNotFoundException ex) {
2881 if (LOGD_ENABLED) {
2882 Log.d(LOGTAG, "activity not found for " + mimetype
2883 + " over " + Uri.parse(url).getScheme(),
2884 ex);
2885 }
2886 // Best behavior is to fall back to a download in this
2887 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 }
2890 }
2891 }
2892 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2893 }
2894
Kristian Monsenfa52d172010-03-25 18:29:21 +00002895 // This is to work around the fact that java.net.URI throws Exceptions
2896 // instead of just encoding URL's properly
2897 // Helper method for onDownloadStartNoStream
2898 private static String encodePath(String path) {
2899 char[] chars = path.toCharArray();
2900
2901 boolean needed = false;
2902 for (char c : chars) {
2903 if (c == '[' || c == ']') {
2904 needed = true;
2905 break;
2906 }
2907 }
2908 if (needed == false) {
2909 return path;
2910 }
2911
2912 StringBuilder sb = new StringBuilder("");
2913 for (char c : chars) {
2914 if (c == '[' || c == ']') {
2915 sb.append('%');
2916 sb.append(Integer.toHexString(c));
2917 } else {
2918 sb.append(c);
2919 }
2920 }
2921
2922 return sb.toString();
2923 }
2924
The Android Open Source Project0c908882009-03-03 19:32:16 -08002925 /**
2926 * Notify the host application a download should be done, even if there
2927 * is a streaming viewer available for thise type.
2928 * @param url The full url to the content that should be downloaded
2929 * @param contentDisposition Content-disposition http header, if
2930 * present.
2931 * @param mimetype The mimetype of the content reported by the server
2932 * @param contentLength The file size reported by the server
2933 */
2934 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2935 String contentDisposition, String mimetype, long contentLength) {
2936
2937 String filename = URLUtil.guessFileName(url,
2938 contentDisposition, mimetype);
2939
2940 // Check to see if we have an SDCard
2941 String status = Environment.getExternalStorageState();
2942 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2943 int title;
2944 String msg;
2945
2946 // Check to see if the SDCard is busy, same as the music app
2947 if (status.equals(Environment.MEDIA_SHARED)) {
2948 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2949 title = R.string.download_sdcard_busy_dlg_title;
2950 } else {
2951 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2952 title = R.string.download_no_sdcard_dlg_title;
2953 }
2954
2955 new AlertDialog.Builder(this)
2956 .setTitle(title)
2957 .setIcon(android.R.drawable.ic_dialog_alert)
2958 .setMessage(msg)
2959 .setPositiveButton(R.string.ok, null)
2960 .show();
2961 return;
2962 }
2963
Kristian Monsenfa52d172010-03-25 18:29:21 +00002964 // java.net.URI is a lot stricter than KURL so we have to encode some
2965 // extra characters. Fix for b 2538060 and b 1634719
2966 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002967 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002968 webAddress = new WebAddress(url);
2969 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002971 // This only happens for very bad urls, we want to chatch the
2972 // exception here
2973 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002974 return;
2975 }
2976
2977 // XXX: Have to use the old url since the cookies were stored using the
2978 // old percent-encoded url.
2979 String cookies = CookieManager.getInstance().getCookie(url);
2980
2981 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002982 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002983 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2984 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2985 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002986 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002987 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002988 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002989 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2990 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2991 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2992 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002993 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002994 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002995 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 }
2997 if (mimetype == null) {
2998 // We must have long pressed on a link or image to download it. We
2999 // are not sure of the mimetype in this case, so do a head request
3000 new FetchUrlMimeType(this).execute(values);
3001 } else {
3002 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003003 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003004 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04003005 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
3006 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 }
3008
Grace Kloba22ac16e2009-10-07 18:00:23 -07003009 // -------------------------------------------------------------------------
3010
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 /**
3012 * Resets the lock icon. This method is called when we start a new load and
3013 * know the url to be loaded.
3014 */
3015 private void resetLockIcon(String url) {
3016 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003017 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003018 updateLockIconImage(LOCK_ICON_UNSECURE);
3019 }
3020
The Android Open Source Project0c908882009-03-03 19:32:16 -08003021 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003022 * Update the lock icon to correspond to our latest state.
3023 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003024 private void updateLockIconToLatest() {
3025 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003026 }
3027
3028 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029 * Updates the lock-icon image in the title-bar.
3030 */
3031 private void updateLockIconImage(int lockIconType) {
3032 Drawable d = null;
3033 if (lockIconType == LOCK_ICON_SECURE) {
3034 d = mSecLockIcon;
3035 } else if (lockIconType == LOCK_ICON_MIXED) {
3036 d = mMixLockIcon;
3037 }
Leon Scroggins68579392009-09-15 15:31:54 -04003038 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003039 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003040 }
3041
3042 /**
3043 * Displays a page-info dialog.
3044 * @param tab The tab to show info about
3045 * @param fromShowSSLCertificateOnError The flag that indicates whether
3046 * this dialog was opened from the SSL-certificate-on-error dialog or
3047 * not. This is important, since we need to know whether to return to
3048 * the parent dialog or simply dismiss.
3049 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003050 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 final boolean fromShowSSLCertificateOnError) {
3052 final LayoutInflater factory = LayoutInflater
3053 .from(this);
3054
3055 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3056
3057 final WebView view = tab.getWebView();
3058
3059 String url = null;
3060 String title = null;
3061
3062 if (view == null) {
3063 url = tab.getUrl();
3064 title = tab.getTitle();
3065 } else if (view == mTabControl.getCurrentWebView()) {
3066 // Use the cached title and url if this is the current WebView
3067 url = mUrl;
3068 title = mTitle;
3069 } else {
3070 url = view.getUrl();
3071 title = view.getTitle();
3072 }
3073
3074 if (url == null) {
3075 url = "";
3076 }
3077 if (title == null) {
3078 title = "";
3079 }
3080
3081 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3082 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3083
3084 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003085 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003086
3087 AlertDialog.Builder alertDialogBuilder =
3088 new AlertDialog.Builder(this)
3089 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3090 .setView(pageInfoView)
3091 .setPositiveButton(
3092 R.string.ok,
3093 new DialogInterface.OnClickListener() {
3094 public void onClick(DialogInterface dialog,
3095 int whichButton) {
3096 mPageInfoDialog = null;
3097 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098
3099 // if we came here from the SSL error dialog
3100 if (fromShowSSLCertificateOnError) {
3101 // go back to the SSL error dialog
3102 showSSLCertificateOnError(
3103 mSSLCertificateOnErrorView,
3104 mSSLCertificateOnErrorHandler,
3105 mSSLCertificateOnErrorError);
3106 }
3107 }
3108 })
3109 .setOnCancelListener(
3110 new DialogInterface.OnCancelListener() {
3111 public void onCancel(DialogInterface dialog) {
3112 mPageInfoDialog = null;
3113 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114
3115 // if we came here from the SSL error dialog
3116 if (fromShowSSLCertificateOnError) {
3117 // go back to the SSL error dialog
3118 showSSLCertificateOnError(
3119 mSSLCertificateOnErrorView,
3120 mSSLCertificateOnErrorHandler,
3121 mSSLCertificateOnErrorError);
3122 }
3123 }
3124 });
3125
3126 // if we have a main top-level page SSL certificate set or a certificate
3127 // error
3128 if (fromShowSSLCertificateOnError ||
3129 (view != null && view.getCertificate() != null)) {
3130 // add a 'View Certificate' button
3131 alertDialogBuilder.setNeutralButton(
3132 R.string.view_certificate,
3133 new DialogInterface.OnClickListener() {
3134 public void onClick(DialogInterface dialog,
3135 int whichButton) {
3136 mPageInfoDialog = null;
3137 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003138
3139 // if we came here from the SSL error dialog
3140 if (fromShowSSLCertificateOnError) {
3141 // go back to the SSL error dialog
3142 showSSLCertificateOnError(
3143 mSSLCertificateOnErrorView,
3144 mSSLCertificateOnErrorHandler,
3145 mSSLCertificateOnErrorError);
3146 } else {
3147 // otherwise, display the top-most certificate from
3148 // the chain
3149 if (view.getCertificate() != null) {
3150 showSSLCertificate(tab);
3151 }
3152 }
3153 }
3154 });
3155 }
3156
3157 mPageInfoDialog = alertDialogBuilder.show();
3158 }
3159
3160 /**
3161 * Displays the main top-level page SSL certificate dialog
3162 * (accessible from the Page-Info dialog).
3163 * @param tab The tab to show certificate for.
3164 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003165 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166 final View certificateView =
3167 inflateCertificateView(tab.getWebView().getCertificate());
3168 if (certificateView == null) {
3169 return;
3170 }
3171
3172 LayoutInflater factory = LayoutInflater.from(this);
3173
3174 final LinearLayout placeholder =
3175 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3176
3177 LinearLayout ll = (LinearLayout) factory.inflate(
3178 R.layout.ssl_success, placeholder);
3179 ((TextView)ll.findViewById(R.id.success))
3180 .setText(R.string.ssl_certificate_is_valid);
3181
3182 mSSLCertificateView = tab;
3183 mSSLCertificateDialog =
3184 new AlertDialog.Builder(this)
3185 .setTitle(R.string.ssl_certificate).setIcon(
3186 R.drawable.ic_dialog_browser_certificate_secure)
3187 .setView(certificateView)
3188 .setPositiveButton(R.string.ok,
3189 new DialogInterface.OnClickListener() {
3190 public void onClick(DialogInterface dialog,
3191 int whichButton) {
3192 mSSLCertificateDialog = null;
3193 mSSLCertificateView = null;
3194
3195 showPageInfo(tab, false);
3196 }
3197 })
3198 .setOnCancelListener(
3199 new DialogInterface.OnCancelListener() {
3200 public void onCancel(DialogInterface dialog) {
3201 mSSLCertificateDialog = null;
3202 mSSLCertificateView = null;
3203
3204 showPageInfo(tab, false);
3205 }
3206 })
3207 .show();
3208 }
3209
3210 /**
3211 * Displays the SSL error certificate dialog.
3212 * @param view The target web-view.
3213 * @param handler The SSL error handler responsible for cancelling the
3214 * connection that resulted in an SSL error or proceeding per user request.
3215 * @param error The SSL error object.
3216 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003217 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 final WebView view, final SslErrorHandler handler, final SslError error) {
3219
3220 final View certificateView =
3221 inflateCertificateView(error.getCertificate());
3222 if (certificateView == null) {
3223 return;
3224 }
3225
3226 LayoutInflater factory = LayoutInflater.from(this);
3227
3228 final LinearLayout placeholder =
3229 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3230
3231 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3232 LinearLayout ll = (LinearLayout)factory
3233 .inflate(R.layout.ssl_warning, placeholder);
3234 ((TextView)ll.findViewById(R.id.warning))
3235 .setText(R.string.ssl_untrusted);
3236 }
3237
3238 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3239 LinearLayout ll = (LinearLayout)factory
3240 .inflate(R.layout.ssl_warning, placeholder);
3241 ((TextView)ll.findViewById(R.id.warning))
3242 .setText(R.string.ssl_mismatch);
3243 }
3244
3245 if (error.hasError(SslError.SSL_EXPIRED)) {
3246 LinearLayout ll = (LinearLayout)factory
3247 .inflate(R.layout.ssl_warning, placeholder);
3248 ((TextView)ll.findViewById(R.id.warning))
3249 .setText(R.string.ssl_expired);
3250 }
3251
3252 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3253 LinearLayout ll = (LinearLayout)factory
3254 .inflate(R.layout.ssl_warning, placeholder);
3255 ((TextView)ll.findViewById(R.id.warning))
3256 .setText(R.string.ssl_not_yet_valid);
3257 }
3258
3259 mSSLCertificateOnErrorHandler = handler;
3260 mSSLCertificateOnErrorView = view;
3261 mSSLCertificateOnErrorError = error;
3262 mSSLCertificateOnErrorDialog =
3263 new AlertDialog.Builder(this)
3264 .setTitle(R.string.ssl_certificate).setIcon(
3265 R.drawable.ic_dialog_browser_certificate_partially_secure)
3266 .setView(certificateView)
3267 .setPositiveButton(R.string.ok,
3268 new DialogInterface.OnClickListener() {
3269 public void onClick(DialogInterface dialog,
3270 int whichButton) {
3271 mSSLCertificateOnErrorDialog = null;
3272 mSSLCertificateOnErrorView = null;
3273 mSSLCertificateOnErrorHandler = null;
3274 mSSLCertificateOnErrorError = null;
3275
Grace Kloba22ac16e2009-10-07 18:00:23 -07003276 view.getWebViewClient().onReceivedSslError(
3277 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003278 }
3279 })
3280 .setNeutralButton(R.string.page_info_view,
3281 new DialogInterface.OnClickListener() {
3282 public void onClick(DialogInterface dialog,
3283 int whichButton) {
3284 mSSLCertificateOnErrorDialog = null;
3285
3286 // do not clear the dialog state: we will
3287 // need to show the dialog again once the
3288 // user is done exploring the page-info details
3289
3290 showPageInfo(mTabControl.getTabFromView(view),
3291 true);
3292 }
3293 })
3294 .setOnCancelListener(
3295 new DialogInterface.OnCancelListener() {
3296 public void onCancel(DialogInterface dialog) {
3297 mSSLCertificateOnErrorDialog = null;
3298 mSSLCertificateOnErrorView = null;
3299 mSSLCertificateOnErrorHandler = null;
3300 mSSLCertificateOnErrorError = null;
3301
Grace Kloba22ac16e2009-10-07 18:00:23 -07003302 view.getWebViewClient().onReceivedSslError(
3303 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003304 }
3305 })
3306 .show();
3307 }
3308
3309 /**
3310 * Inflates the SSL certificate view (helper method).
3311 * @param certificate The SSL certificate.
3312 * @return The resultant certificate view with issued-to, issued-by,
3313 * issued-on, expires-on, and possibly other fields set.
3314 * If the input certificate is null, returns null.
3315 */
3316 private View inflateCertificateView(SslCertificate certificate) {
3317 if (certificate == null) {
3318 return null;
3319 }
3320
3321 LayoutInflater factory = LayoutInflater.from(this);
3322
3323 View certificateView = factory.inflate(
3324 R.layout.ssl_certificate, null);
3325
3326 // issued to:
3327 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3328 if (issuedTo != null) {
3329 ((TextView) certificateView.findViewById(R.id.to_common))
3330 .setText(issuedTo.getCName());
3331 ((TextView) certificateView.findViewById(R.id.to_org))
3332 .setText(issuedTo.getOName());
3333 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3334 .setText(issuedTo.getUName());
3335 }
3336
3337 // issued by:
3338 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3339 if (issuedBy != null) {
3340 ((TextView) certificateView.findViewById(R.id.by_common))
3341 .setText(issuedBy.getCName());
3342 ((TextView) certificateView.findViewById(R.id.by_org))
3343 .setText(issuedBy.getOName());
3344 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3345 .setText(issuedBy.getUName());
3346 }
3347
3348 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003349 String issuedOn = formatCertificateDate(
3350 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003351 ((TextView) certificateView.findViewById(R.id.issued_on))
3352 .setText(issuedOn);
3353
3354 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003355 String expiresOn = formatCertificateDate(
3356 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 ((TextView) certificateView.findViewById(R.id.expires_on))
3358 .setText(expiresOn);
3359
3360 return certificateView;
3361 }
3362
3363 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003364 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003365 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003366 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003368 private String formatCertificateDate(Date certificateDate) {
3369 if (certificateDate == null) {
3370 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003371 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003372 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3373 if (formattedDate == null) {
3374 return "";
3375 }
3376 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 }
3378
3379 /**
3380 * Displays an http-authentication dialog.
3381 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003382 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383 final String host, final String realm, final String title,
3384 final String name, final String password, int focusId) {
3385 LayoutInflater factory = LayoutInflater.from(this);
3386 final View v = factory
3387 .inflate(R.layout.http_authentication, null);
3388 if (name != null) {
3389 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3390 }
3391 if (password != null) {
3392 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3393 }
3394
3395 String titleText = title;
3396 if (titleText == null) {
3397 titleText = getText(R.string.sign_in_to).toString().replace(
3398 "%s1", host).replace("%s2", realm);
3399 }
3400
3401 mHttpAuthHandler = handler;
3402 AlertDialog dialog = new AlertDialog.Builder(this)
3403 .setTitle(titleText)
3404 .setIcon(android.R.drawable.ic_dialog_alert)
3405 .setView(v)
3406 .setPositiveButton(R.string.action,
3407 new DialogInterface.OnClickListener() {
3408 public void onClick(DialogInterface dialog,
3409 int whichButton) {
3410 String nm = ((EditText) v
3411 .findViewById(R.id.username_edit))
3412 .getText().toString();
3413 String pw = ((EditText) v
3414 .findViewById(R.id.password_edit))
3415 .getText().toString();
3416 BrowserActivity.this.setHttpAuthUsernamePassword
3417 (host, realm, nm, pw);
3418 handler.proceed(nm, pw);
3419 mHttpAuthenticationDialog = null;
3420 mHttpAuthHandler = null;
3421 }})
3422 .setNegativeButton(R.string.cancel,
3423 new DialogInterface.OnClickListener() {
3424 public void onClick(DialogInterface dialog,
3425 int whichButton) {
3426 handler.cancel();
3427 BrowserActivity.this.resetTitleAndRevertLockIcon();
3428 mHttpAuthenticationDialog = null;
3429 mHttpAuthHandler = null;
3430 }})
3431 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3432 public void onCancel(DialogInterface dialog) {
3433 handler.cancel();
3434 BrowserActivity.this.resetTitleAndRevertLockIcon();
3435 mHttpAuthenticationDialog = null;
3436 mHttpAuthHandler = null;
3437 }})
3438 .create();
3439 // Make the IME appear when the dialog is displayed if applicable.
3440 dialog.getWindow().setSoftInputMode(
3441 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3442 dialog.show();
3443 if (focusId != 0) {
3444 dialog.findViewById(focusId).requestFocus();
3445 } else {
3446 v.findViewById(R.id.username_edit).requestFocus();
3447 }
3448 mHttpAuthenticationDialog = dialog;
3449 }
3450
3451 public int getProgress() {
3452 WebView w = mTabControl.getCurrentWebView();
3453 if (w != null) {
3454 return w.getProgress();
3455 } else {
3456 return 100;
3457 }
3458 }
3459
3460 /**
3461 * Set HTTP authentication password.
3462 *
3463 * @param host The host for the password
3464 * @param realm The realm for the password
3465 * @param username The username for the password. If it is null, it means
3466 * password can't be saved.
3467 * @param password The password
3468 */
3469 public void setHttpAuthUsernamePassword(String host, String realm,
3470 String username,
3471 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003472 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 if (w != null) {
3474 w.setHttpAuthUsernamePassword(host, realm, username, password);
3475 }
3476 }
3477
3478 /**
3479 * connectivity manager says net has come or gone... inform the user
3480 * @param up true if net has come up, false if net has gone down
3481 */
3482 public void onNetworkToggle(boolean up) {
3483 if (up == mIsNetworkUp) {
3484 return;
3485 } else if (up) {
3486 mIsNetworkUp = true;
3487 if (mAlertDialog != null) {
3488 mAlertDialog.cancel();
3489 mAlertDialog = null;
3490 }
3491 } else {
3492 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003493 if (mInLoad) {
3494 createAndShowNetworkDialog();
3495 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 }
3497 WebView w = mTabControl.getCurrentWebView();
3498 if (w != null) {
3499 w.setNetworkAvailable(up);
3500 }
3501 }
3502
Grace Kloba22ac16e2009-10-07 18:00:23 -07003503 boolean isNetworkUp() {
3504 return mIsNetworkUp;
3505 }
3506
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003507 // This method shows the network dialog alerting the user that the net is
3508 // down. It will only show the dialog if mAlertDialog is null.
3509 private void createAndShowNetworkDialog() {
3510 if (mAlertDialog == null) {
3511 mAlertDialog = new AlertDialog.Builder(this)
3512 .setTitle(R.string.loadSuspendedTitle)
3513 .setMessage(R.string.loadSuspended)
3514 .setPositiveButton(R.string.ok, null)
3515 .show();
3516 }
3517 }
3518
The Android Open Source Project0c908882009-03-03 19:32:16 -08003519 @Override
3520 protected void onActivityResult(int requestCode, int resultCode,
3521 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003522 if (getTopWindow() == null) return;
3523
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 switch (requestCode) {
3525 case COMBO_PAGE:
3526 if (resultCode == RESULT_OK && intent != null) {
3527 String data = intent.getAction();
3528 Bundle extras = intent.getExtras();
3529 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003530 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003532 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003534 dismissSubWindow(currentTab);
3535 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003536 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003537 }
3538 }
3539 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003540 // Deliberately fall through to PREFERENCES_PAGE, since the
3541 // same extra may be attached to the COMBO_PAGE
3542 case PREFERENCES_PAGE:
3543 if (resultCode == RESULT_OK && intent != null) {
3544 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3545 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3546 mTabControl.removeParentChildRelationShips();
3547 }
3548 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003550 // Choose a file from the file picker.
3551 case FILE_SELECTED:
3552 if (null == mUploadMessage) break;
3553 Uri result = intent == null || resultCode != RESULT_OK ? null
3554 : intent.getData();
3555 mUploadMessage.onReceiveValue(result);
3556 mUploadMessage = null;
3557 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 default:
3559 break;
3560 }
Leon Scroggins30444232009-09-04 18:36:20 -04003561 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 }
3563
3564 /*
3565 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003566 * menu to see the download window. It shows the download window on top of
3567 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003568 */
Leon Scroggins IIIa682a3c2010-09-27 12:32:40 -04003569 private void viewDownloads() {
3570 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
3571 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 }
3573
Leon Scroggins160a7e72009-08-14 18:28:01 -04003574 /**
3575 * Open the Go page.
3576 * @param startWithHistory If true, open starting on the history tab.
3577 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003578 */
Leon Scroggins30444232009-09-04 18:36:20 -04003579 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003580 WebView current = mTabControl.getCurrentWebView();
3581 if (current == null) {
3582 return;
3583 }
3584 Intent intent = new Intent(this,
3585 CombinedBookmarkHistoryActivity.class);
3586 String title = current.getTitle();
3587 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003588 Bitmap thumbnail = createScreenshot(current);
3589
The Android Open Source Project0c908882009-03-03 19:32:16 -08003590 // Just in case the user opens bookmarks before a page finishes loading
3591 // so the current history item, and therefore the page, is null.
3592 if (null == url) {
3593 url = mLastEnteredUrl;
3594 // This can happen.
3595 if (null == url) {
3596 url = mSettings.getHomePage();
3597 }
3598 }
3599 // In case the web page has not yet received its associated title.
3600 if (title == null) {
3601 title = url;
3602 }
3603 intent.putExtra("title", title);
3604 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003605 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003606 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003607 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003608 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 if (startWithHistory) {
3610 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3611 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3612 }
3613 startActivityForResult(intent, COMBO_PAGE);
3614 }
3615
3616 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003617 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003618 // In case the user enters nothing.
3619 if (url != null && url.length() != 0 && view != null) {
3620 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003621 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003622 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003623 }
3624 }
3625 }
3626
Leon Scroggins92472e82010-02-17 16:32:28 -05003627 /**
3628 * Load the URL into the given WebView and update the title bar
3629 * to reflect the new load. Call this instead of WebView.loadUrl
3630 * directly.
3631 * @param view The WebView used to load url.
3632 * @param url The URL to load.
3633 */
3634 private void loadUrl(WebView view, String url) {
3635 updateTitleBarForNewLoad(view, url);
3636 view.loadUrl(url);
3637 }
3638
3639 /**
3640 * Load UrlData into a Tab and update the title bar to reflect the new
3641 * load. Call this instead of UrlData.loadIn directly.
3642 * @param t The Tab used to load.
3643 * @param data The UrlData being loaded.
3644 */
3645 private void loadUrlDataIn(Tab t, UrlData data) {
3646 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3647 data.loadIn(t);
3648 }
3649
3650 /**
3651 * If the WebView is the top window, update the title bar to reflect
3652 * loading the new URL. i.e. set its text, clear the favicon (which
3653 * will be set once the page begins loading), and set the progress to
3654 * INITIAL_PROGRESS to show that the page has begun to load. Called
3655 * by loadUrl and loadUrlDataIn.
3656 * @param view The WebView that is starting a load.
3657 * @param url The URL that is being loaded.
3658 */
3659 private void updateTitleBarForNewLoad(WebView view, String url) {
3660 if (view == getTopWindow()) {
3661 setUrlTitle(url, null);
3662 setFavicon(null);
3663 onProgressChanged(view, INITIAL_PROGRESS);
3664 }
3665 }
3666
The Android Open Source Project0c908882009-03-03 19:32:16 -08003667 private String smartUrlFilter(Uri inUri) {
3668 if (inUri != null) {
3669 return smartUrlFilter(inUri.toString());
3670 }
3671 return null;
3672 }
3673
Feng Qianb34f87a2009-03-24 21:27:26 -07003674 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003675 "(?i)" + // switch on case insensitive matching
3676 "(" + // begin group for schema
3677 "(?:http|https|file):\\/\\/" +
Huahui Wu604a5982011-03-22 15:00:11 -07003678 "|(?:inline|data|about|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003679 ")" +
3680 "(.*)" );
3681
3682 /**
3683 * Attempts to determine whether user input is a URL or search
3684 * terms. Anything with a space is passed to search.
3685 *
3686 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3687 * "Http://" converts to "http://"
3688 *
3689 * @return Original or modified URL
3690 *
3691 */
3692 String smartUrlFilter(String url) {
3693
3694 String inUrl = url.trim();
3695 boolean hasSpace = inUrl.indexOf(' ') != -1;
3696
3697 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3698 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003699 // force scheme to lowercase
3700 String scheme = matcher.group(1);
3701 String lcScheme = scheme.toLowerCase();
3702 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003703 inUrl = lcScheme + matcher.group(2);
3704 }
3705 if (hasSpace) {
3706 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003707 }
3708 return inUrl;
3709 }
Leon Scroggins956cf012010-10-07 13:51:57 -04003710 if (!hasSpace) {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003711 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712 return URLUtil.guessUrl(inUrl);
3713 }
3714 }
3715
Leon Scroggins956cf012010-10-07 13:51:57 -04003716 // FIXME: Is this the correct place to add to searches?
3717 // what if someone else calls this function?
3718
The Android Open Source Project0c908882009-03-03 19:32:16 -08003719 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003720 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003721 }
3722
Ben Murdochbff2d602009-07-01 20:19:05 +01003723 /* package */ void setShouldShowErrorConsole(boolean flag) {
3724 if (flag == mShouldShowErrorConsole) {
3725 // Nothing to do.
3726 return;
3727 }
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003728 Tab t = mTabControl.getCurrentTab();
3729 if (t == null) {
3730 // There is no current tab so we cannot toggle the error console
3731 return;
3732 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003733
3734 mShouldShowErrorConsole = flag;
3735
Leon Scroggins IIIa9e35b62010-09-16 15:30:15 -04003736 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003737
3738 if (flag) {
3739 // Setting the show state of the console will cause it's the layout to be inflated.
3740 if (errorConsole.numberOfErrors() > 0) {
3741 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3742 } else {
3743 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3744 }
3745
3746 // Now we can add it to the main view.
3747 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003748 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003749 ViewGroup.LayoutParams.WRAP_CONTENT));
3750 } else {
3751 mErrorConsoleContainer.removeView(errorConsole);
3752 }
3753
3754 }
3755
Grace Kloba22ac16e2009-10-07 18:00:23 -07003756 boolean shouldShowErrorConsole() {
3757 return mShouldShowErrorConsole;
3758 }
3759
Andrei Popescu163ab742009-10-20 17:58:23 +01003760 private void setStatusBarVisibility(boolean visible) {
3761 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3762 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3763 }
3764
Andrei Popescu56199cc2010-01-12 22:39:16 +00003765
3766 private void sendNetworkType(String type, String subtype) {
3767 WebView w = mTabControl.getCurrentWebView();
3768 if (w != null) {
3769 w.setNetworkType(type, subtype);
3770 }
3771 }
3772
Andrei Popescu30995e72010-02-09 16:59:58 +00003773 private void packageChanged(String packageName, boolean wasAdded) {
3774 WebView w = mTabControl.getCurrentWebView();
3775 if (w == null) {
3776 return;
3777 }
3778
3779 if (wasAdded) {
3780 w.addPackageName(packageName);
3781 } else {
3782 w.removePackageName(packageName);
3783 }
3784 }
3785
3786 private void addPackageNames(Set<String> packageNames) {
3787 WebView w = mTabControl.getCurrentWebView();
3788 if (w == null) {
3789 return;
3790 }
3791
3792 w.addPackageNames(packageNames);
3793 }
3794
3795 private void getInstalledPackages() {
3796 AsyncTask<Void, Void, Set<String> > task =
3797 new AsyncTask<Void, Void, Set<String> >() {
3798 protected Set<String> doInBackground(Void... unused) {
3799 Set<String> installedPackages = new HashSet<String>();
3800 PackageManager pm = BrowserActivity.this.getPackageManager();
3801 if (pm != null) {
3802 List<PackageInfo> packages = pm.getInstalledPackages(0);
3803 for (PackageInfo p : packages) {
3804 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3805 installedPackages.add(p.packageName);
3806 }
3807 }
3808 }
3809
3810 return installedPackages;
3811 }
3812
3813 // Executes on the UI thread
3814 protected void onPostExecute(Set<String> installedPackages) {
3815 addPackageNames(installedPackages);
3816 }
3817 };
3818 task.execute();
3819 }
3820
Grace Klobaeb6eef42009-09-15 17:56:32 -07003821 final static int LOCK_ICON_UNSECURE = 0;
3822 final static int LOCK_ICON_SECURE = 1;
3823 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824
The Android Open Source Project0c908882009-03-03 19:32:16 -08003825 private BrowserSettings mSettings;
3826 private TabControl mTabControl;
3827 private ContentResolver mResolver;
3828 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003829 private View mCustomView;
3830 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003831 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003832
3833 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3834 // view, we should rewrite this.
3835 private int mCurrentMenuState = 0;
3836 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003837 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838 private static final int EMPTY_MENU = -1;
3839 private Menu mMenu;
3840
3841 private FindDialog mFindDialog;
Cary Clark2c326e62010-08-19 18:40:57 -04003842 private SelectDialog mSelectDialog;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843 // Used to prevent chording to result in firing two shortcuts immediately
3844 // one after another. Fixes bug 1211714.
3845 boolean mCanChord;
3846
3847 private boolean mInLoad;
3848 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003849 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003850
Cary Clark1f10cbf2010-03-22 11:45:23 -04003851 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003852
3853 private boolean mMenuIsDown;
3854
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 private static boolean mInTrace;
3856
3857 // Performance probe
3858 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3859 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3860 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3861 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3862 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3863 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3864 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3865 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3866 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3867 };
3868
3869 private long mStart;
3870 private long mProcessStart;
3871 private long mUserStart;
3872 private long mSystemStart;
3873 private long mIdleStart;
3874 private long mIrqStart;
3875
3876 private long mUiStart;
3877
3878 private Drawable mMixLockIcon;
3879 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003880
3881 /* hold a ref so we can auto-cancel if necessary */
3882 private AlertDialog mAlertDialog;
3883
The Android Open Source Project0c908882009-03-03 19:32:16 -08003884 // The up-to-date URL and title (these can be different from those stored
3885 // in WebView, since it takes some time for the information in WebView to
3886 // get updated)
3887 private String mUrl;
3888 private String mTitle;
3889
3890 // As PageInfo has different style for landscape / portrait, we have
3891 // to re-open it when configuration changed
3892 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003893 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003894 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3895 // dialog, we should not just dismiss it, but should get back to the
3896 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003897 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003898
3899 // as SSLCertificateOnError has different style for landscape / portrait,
3900 // we have to re-open it when configuration changed
3901 private AlertDialog mSSLCertificateOnErrorDialog;
3902 private WebView mSSLCertificateOnErrorView;
3903 private SslErrorHandler mSSLCertificateOnErrorHandler;
3904 private SslError mSSLCertificateOnErrorError;
3905
3906 // as SSLCertificate has different style for landscape / portrait, we
3907 // have to re-open it when configuration changed
3908 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003909 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003910
3911 // as HttpAuthentication has different style for landscape / portrait, we
3912 // have to re-open it when configuration changed
3913 private AlertDialog mHttpAuthenticationDialog;
3914 private HttpAuthHandler mHttpAuthHandler;
3915
3916 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3917 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003918 ViewGroup.LayoutParams.MATCH_PARENT,
3919 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003920 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3921 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003922 ViewGroup.LayoutParams.MATCH_PARENT,
3923 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003924 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003925 // Google search
3926 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003927
3928 final static String QUERY_PLACE_HOLDER = "%s";
3929
3930 // "source" parameter for Google search through search key
3931 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3932 // "source" parameter for Google search through goto menu
3933 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3934 // "source" parameter for Google search through simplily type
3935 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3936 // "source" parameter for Google search suggested by the browser
3937 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3938 // "source" parameter for Google search from unknown source
3939 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3940
3941 private final static String LOGTAG = "browser";
3942
The Android Open Source Project0c908882009-03-03 19:32:16 -08003943 private String mLastEnteredUrl;
3944
3945 private PowerManager.WakeLock mWakeLock;
3946 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3947
3948 private Toast mStopToast;
3949
Leon Scroggins68579392009-09-15 15:31:54 -04003950 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003951
Ben Murdochbff2d602009-07-01 20:19:05 +01003952 private LinearLayout mErrorConsoleContainer = null;
3953 private boolean mShouldShowErrorConsole = false;
3954
The Android Open Source Project0c908882009-03-03 19:32:16 -08003955 // As the ids are dynamically created, we can't guarantee that they will
3956 // be in sequence, so this static array maps ids to a window number.
3957 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3958 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3959 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3960 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3961
3962 // monitor platform changes
3963 private IntentFilter mNetworkStateChangedFilter;
3964 private BroadcastReceiver mNetworkStateIntentReceiver;
3965
Grace Klobab4da0ad2009-05-14 14:45:40 -07003966 private BroadcastReceiver mPackageInstallationReceiver;
3967
Bjorn Bringerta7611812010-03-24 11:12:02 +00003968 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3969
The Android Open Source Project0c908882009-03-03 19:32:16 -08003970 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003971 final static int COMBO_PAGE = 1;
Nicolas Roard78a98e42009-05-11 13:34:17 +01003972 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003973 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003974
Andrei Popescu540035d2009-09-18 18:59:20 +01003975 // the default <video> poster
3976 private Bitmap mDefaultVideoPoster;
3977 // the video progress view
3978 private View mVideoProgressView;
3979
Andrei Popescu30995e72010-02-09 16:59:58 +00003980 // The Google packages we monitor for the navigator.isApplicationInstalled()
3981 // API. Add as needed.
3982 private static Set<String> sGoogleApps;
3983 static {
3984 sGoogleApps = new HashSet<String>();
3985 sGoogleApps.add("com.google.android.youtube");
3986 }
3987
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003988 /**
3989 * A UrlData class to abstract how the content will be set to WebView.
3990 * This base class uses loadUrl to show the content.
3991 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003992 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003993 final String mUrl;
3994 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003995 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003996
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003997 UrlData(String url) {
3998 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003999 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004000 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004001 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004002
Leon Scroggins58d56c62010-01-28 15:12:40 -05004003 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004004 this.mUrl = url;
4005 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004006 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4007 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004008 this.mVoiceIntent = intent;
4009 } else {
4010 this.mVoiceIntent = null;
4011 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004012 }
4013
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004014 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004015 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004016 }
4017
Leon Scroggins92472e82010-02-17 16:32:28 -05004018 /**
4019 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4020 * the title bar as well.
4021 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004022 public void loadIn(Tab t) {
4023 if (mVoiceIntent != null) {
4024 t.activateVoiceSearchMode(mVoiceIntent);
4025 } else {
4026 t.getWebView().loadUrl(mUrl, mHeaders);
4027 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004028 }
4029 };
4030
Leon Scroggins1f005d32009-08-10 17:36:42 -04004031 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
Ed Tam8ba13bc2011-05-05 16:19:48 -07004032
4033 private static boolean needsRlz(Uri uri) {
4034 if ((uri.getQueryParameter("rlz") == null) &&
4035 (uri.getQueryParameter("q") != null) &&
4036 UrlUtils.isGoogleUri(uri)) {
4037 return true;
4038 }
4039 return false;
4040 }
4041
4042 private static Uri addRlzParameter(Uri uri, String rlz) {
4043 if (rlz.isEmpty()) {
4044 return uri;
4045 }
4046 return uri.buildUpon().appendQueryParameter("rlz", rlz).build();
4047 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004048}