blob: df80e99bdd0615b72d84c45d065eac56d9ca6d04 [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;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800138 implements View.OnCreateContextMenuListener, DownloadListener,
139 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140
Dave Bort31a6d1c2009-04-13 15:56:49 -0700141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
143 */
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
147
Satish Sampath565505b2009-05-29 15:37:27 +0100148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
154
Fred Quintana752b6562009-12-18 10:18:26 -0800155 private Account[] mAccountsGoogle;
156 private Account[] mAccountsPreferHosted;
157
Patrick Scott43914692010-02-19 10:10:10 -0500158 // XXX: These constants should be exposed through some public api. Hardcode
159 // the values for now until some solution for gsf can be worked out.
160 // http://b/issue?id=2425179
161 private static final String ACCOUNT_TYPE = "com.google";
162 private static final String FEATURE_LEGACY_GOOGLE = "legacy_google";
163 private static final String FEATURE_LEGACY_HOSTED_OR_GOOGLE =
164 "legacy_hosted_or_google";
165
Fred Quintana752b6562009-12-18 10:18:26 -0800166 private void startReadOfGoogleAccounts() {
167 mAccountsGoogle = null;
168 mAccountsPreferHosted = null;
169
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
Patrick Scott43914692010-02-19 10:10:10 -0500171 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_HOSTED_OR_GOOGLE },
Fred Quintana752b6562009-12-18 10:18:26 -0800172 this, null);
173 }
174
175 /** This implements AccountManagerCallback<Account[]> */
176 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
177 try {
178 if (mAccountsGoogle == null) {
179 mAccountsGoogle = accountManagerFuture.getResult();
180
181 AccountManager.get(this).getAccountsByTypeAndFeatures(
Patrick Scott43914692010-02-19 10:10:10 -0500182 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_GOOGLE },
Fred Quintana752b6562009-12-18 10:18:26 -0800183 this, null);
184 } else {
185 mAccountsPreferHosted = accountManagerFuture.getResult();
186 setupHomePage();
187 }
188 } catch (OperationCanceledException e) {
189 setupHomePage();
190 } catch (IOException e) {
191 setupHomePage();
192 } catch (AuthenticatorException e) {
193 setupHomePage();
194 }
195 }
196
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800198 // get the default home page
199 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200
Fred Quintana752b6562009-12-18 10:18:26 -0800201 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
202 // three cases:
203 //
204 // hostedUser == googleUser
205 // The device has only a google account
206 //
207 // hostedUser != googleUser
208 // The device has a hosted account and a google account
209 //
210 // hostedUser != null, googleUser == null
211 // The device has only a hosted account (so far)
212 String hostedUser = mAccountsPreferHosted.length == 0
213 ? null
214 : mAccountsPreferHosted[0].name;
215 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800216
Fred Quintana752b6562009-12-18 10:18:26 -0800217 // developers might have no accounts at all
218 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700219
Fred Quintana752b6562009-12-18 10:18:26 -0800220 if (googleUser == null || !hostedUser.equals(googleUser)) {
221 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
222 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800223 }
Fred Quintana752b6562009-12-18 10:18:26 -0800224 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225
Fred Quintana752b6562009-12-18 10:18:26 -0800226 mSettings.setHomePage(BrowserActivity.this, homepage);
227 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228 }
229
Cary Clarka9771242009-08-11 16:42:26 -0400230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 @Override
232 public Void doInBackground(File... files) {
233 if (files != null) {
234 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400235 if (!f.delete()) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 }
239 }
240 return null;
241 }
242 }
243
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400244 /**
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
247 */
248 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400249
Grace Kloba22ac16e2009-10-07 18:00:23 -0700250 @Override
251 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700252 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 Log.v(LOGTAG, this + " onStart");
254 }
255 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
258
Mike Reedd334bf52010-01-26 15:21:44 -0500259 // enable this to test the browser in 32bit
260 if (false) {
261 getWindow().setFormat(PixelFormat.RGBX_8888);
262 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
263 }
264
The Android Open Source Project0c908882009-03-03 19:32:16 -0800265 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
266
267 mResolver = getContentResolver();
268
Grace Kloba0923d692009-09-23 21:37:25 -0700269 // If this was a web search request, pass it on to the default web
270 // search provider and finish this activity.
271 if (handleWebSearchIntent(getIntent())) {
272 finish();
273 return;
274 }
275
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276 mSecLockIcon = Resources.getSystem().getDrawable(
277 android.R.drawable.ic_secure);
278 mMixLockIcon = Resources.getSystem().getDrawable(
279 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800280
Leon Scroggins81db3662009-06-04 17:45:11 -0400281 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
282 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400283 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
284 .inflate(R.layout.custom_screen, null);
285 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
286 R.id.main_content);
287 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
288 .findViewById(R.id.error_console);
289 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
290 .findViewById(R.id.fullscreen_custom_content);
291 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400292 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400293 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800294
295 // Create the tab control and our initial tab
296 mTabControl = new TabControl(this);
297
298 // Open the icon database and retain all the bookmark urls for favicons
299 retainIconsOnStartup();
300
301 // Keep a settings instance handy.
302 mSettings = BrowserSettings.getInstance();
303 mSettings.setTabControl(mTabControl);
304 mSettings.loadFromDb(this);
305
306 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
307 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
308
Grace Klobaa34f6862009-07-31 16:28:17 -0700309 /* enables registration for changes in network status from
310 http stack */
311 mNetworkStateChangedFilter = new IntentFilter();
312 mNetworkStateChangedFilter.addAction(
313 ConnectivityManager.CONNECTIVITY_ACTION);
314 mNetworkStateIntentReceiver = new BroadcastReceiver() {
315 @Override
316 public void onReceive(Context context, Intent intent) {
317 if (intent.getAction().equals(
318 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000319
320 NetworkInfo info = intent.getParcelableExtra(
321 ConnectivityManager.EXTRA_NETWORK_INFO);
322 String typeName = info.getTypeName();
323 String subtypeName = info.getSubtypeName();
324 sendNetworkType(typeName.toLowerCase(),
325 (subtypeName != null ? subtypeName.toLowerCase() : ""));
326
327 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700328 }
329 }
330 };
331
Grace Kloba615c6c92009-08-03 10:22:44 -0700332 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
333 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
334 filter.addDataScheme("package");
335 mPackageInstallationReceiver = new BroadcastReceiver() {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 final String action = intent.getAction();
339 final String packageName = intent.getData()
340 .getSchemeSpecificPart();
341 final boolean replacing = intent.getBooleanExtra(
342 Intent.EXTRA_REPLACING, false);
343 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
344 // if it is replacing, refreshPlugins() when adding
345 return;
346 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000347
348 if (sGoogleApps.contains(packageName)) {
349 BrowserActivity.this.packageChanged(packageName,
350 Intent.ACTION_PACKAGE_ADDED.equals(action));
351 }
352
Grace Kloba615c6c92009-08-03 10:22:44 -0700353 PackageManager pm = BrowserActivity.this.getPackageManager();
354 PackageInfo pkgInfo = null;
355 try {
356 pkgInfo = pm.getPackageInfo(packageName,
357 PackageManager.GET_PERMISSIONS);
358 } catch (PackageManager.NameNotFoundException e) {
359 return;
360 }
361 if (pkgInfo != null) {
362 String permissions[] = pkgInfo.requestedPermissions;
363 if (permissions == null) {
364 return;
365 }
366 boolean permissionOk = false;
367 for (String permit : permissions) {
368 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
369 permissionOk = true;
370 break;
371 }
372 }
373 if (permissionOk) {
374 PluginManager.getInstance(BrowserActivity.this)
375 .refreshPlugins(
376 Intent.ACTION_PACKAGE_ADDED
377 .equals(action));
378 }
379 }
380 }
381 };
382 registerReceiver(mPackageInstallationReceiver, filter);
383
The Android Open Source Project0c908882009-03-03 19:32:16 -0800384 if (!mTabControl.restoreState(icicle)) {
385 // clear up the thumbnail directory if we can't restore the state as
386 // none of the files in the directory are referenced any more.
387 new ClearThumbnails().execute(
388 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700389 // there is no quit on Android. But if we can't restore the state,
390 // we can treat it as a new Browser, remove the old session cookies.
391 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 final Intent intent = getIntent();
393 final Bundle extra = intent.getExtras();
394 // Create an initial tab.
395 // If the intent is ACTION_VIEW and data is not null, the Browser is
396 // invoked to view the content by another application. In this case,
397 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700398 UrlData urlData = getUrlDataFromIntent(intent);
399
Leon Scroggins58d56c62010-01-28 15:12:40 -0500400 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700401 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500402 (Intent.ACTION_VIEW.equals(action) &&
403 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500404 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
405 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700406 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800407 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800408 attachTabToContentView(t);
409 WebView webView = t.getWebView();
410 if (extra != null) {
411 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
412 if (scale > 0 && scale <= 1000) {
413 webView.setInitialScale(scale);
414 }
415 }
416 // If we are not restoring from an icicle, then there is a high
417 // likely hood this is the first run. So, check to see if the
418 // homepage needs to be configured and copy any plugins from our
419 // asset directory to the data partition.
420 if ((extra == null || !extra.getBoolean("testing"))
421 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800422 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700425 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400426 if (mSettings.isLoginInitialized()) {
Leon Scroggins92472e82010-02-17 16:32:28 -0500427 loadUrl(webView, mSettings.getHomePage());
Leon Scroggins30444232009-09-04 18:36:20 -0400428 } else {
429 waitForCredentials();
430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800431 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500432 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 }
434 } else {
435 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400436 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800437 attachTabToContentView(mTabControl.getCurrentTab());
438 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700439
Feng Qianb3c02da2009-06-29 15:58:08 -0700440 // Read JavaScript flags if it exists.
441 String jsFlags = mSettings.getJsFlags();
442 if (jsFlags.trim().length() != 0) {
443 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
444 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000445 // Work out which packages are installed on the system.
446 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800447 }
448
Leon Scroggins58d56c62010-01-28 15:12:40 -0500449 /**
450 * Feed the previously stored results strings to the BrowserProvider so that
451 * the SearchDialog will show them instead of the standard searches.
452 * @param result String to show on the editable line of the SearchDialog.
453 */
454 /* package */ void showVoiceSearchResults(String result) {
455 ContentProviderClient client = mResolver.acquireContentProviderClient(
456 Browser.BOOKMARKS_URI);
457 ContentProvider prov = client.getLocalContentProvider();
458 BrowserProvider bp = (BrowserProvider) prov;
459 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
460 client.release();
461
462 startSearch(result, false,
463 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
464 false);
465 }
466
The Android Open Source Project0c908882009-03-03 19:32:16 -0800467 @Override
468 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800470 // When a tab is closed on exit, the current tab index is set to -1.
471 // Reset before proceed as Browser requires the current tab to be set.
472 if (current == null) {
473 // Try to reset the tab in case the index was incorrect.
474 current = mTabControl.getTab(0);
475 if (current == null) {
476 // No tabs at all so just ignore this intent.
477 return;
478 }
479 mTabControl.setCurrentTab(current);
480 attachTabToContentView(current);
481 resetTitleAndIcon(current.getWebView());
482 }
483 final String action = intent.getAction();
484 final int flags = intent.getFlags();
485 if (Intent.ACTION_MAIN.equals(action) ||
486 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
487 // just resume the browser
488 return;
489 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500490 boolean activateVoiceSearch = RecognizerResultsIntent
491 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800492 if (Intent.ACTION_VIEW.equals(action)
493 || Intent.ACTION_SEARCH.equals(action)
494 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500495 || Intent.ACTION_WEB_SEARCH.equals(action)
496 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500497 if (current.isInVoiceSearchMode()) {
498 String title = current.getVoiceDisplayTitle();
499 if (title != null && title.equals(intent.getStringExtra(
500 SearchManager.QUERY))) {
501 // The user submitted the same search as the last voice
502 // search, so do nothing.
503 return;
504 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500505 if (Intent.ACTION_SEARCH.equals(action)
506 && current.voiceSearchSourceIsGoogle()) {
507 Intent logIntent = new Intent(
508 LoggingEvents.ACTION_LOG_EVENT);
509 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
510 LoggingEvents.VoiceSearch.QUERY_UPDATED);
511 logIntent.putExtra(
512 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
513 intent.getDataString());
514 sendBroadcast(logIntent);
515 // Note, onPageStarted will revert the voice title bar
516 // When http://b/issue?id=2379215 is fixed, we should update
517 // the title bar here.
518 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500519 }
Satish Sampath565505b2009-05-29 15:37:27 +0100520 // If this was a search request (e.g. search query directly typed into the address bar),
521 // pass it on to the default web search provider.
522 if (handleWebSearchIntent(intent)) {
523 return;
524 }
525
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700526 UrlData urlData = getUrlDataFromIntent(intent);
527 if (urlData.isEmpty()) {
528 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700530
Grace Klobacc634032009-07-28 15:58:19 -0700531 final String appId = intent
532 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500533 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700534 && !getPackageName().equals(appId)
535 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700536 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700537 if (appTab != null) {
538 Log.i(LOGTAG, "Reusing tab for " + appId);
539 // Dismiss the subwindow if applicable.
540 dismissSubWindow(appTab);
541 // Since we might kill the WebView, remove it from the
542 // content view first.
543 removeTabFromContentView(appTab);
544 // Recreate the main WebView after destroying the old one.
545 // If the WebView has the same original url and is on that
546 // page, it can be reused.
547 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700548 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100549
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700550 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400551 switchToTab(mTabControl.getTabIndex(appTab));
552 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500553 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400554 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700555 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400556 // If the tab was the current tab, we have to attach
557 // it to the view system again.
558 attachTabToContentView(appTab);
559 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500560 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700561 }
562 }
563 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400564 } else {
565 // No matching application tab, try to find a regular tab
566 // with a matching url.
567 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400568 if (appTab != null) {
569 if (current != appTab) {
570 switchToTab(mTabControl.getTabIndex(appTab));
571 }
572 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400573 } else {
574 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
575 // will be opened in a new tab unless we have reached
576 // MAX_TABS. Then the url will be opened in the current
577 // tab. If a new tab is created, it will have "true" for
578 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400579 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400580 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700581 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800582 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800583 if (!urlData.isEmpty()
584 && urlData.mUrl.startsWith("about:debug")) {
585 if ("about:debug.dom".equals(urlData.mUrl)) {
586 current.getWebView().dumpDomTree(false);
587 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
588 current.getWebView().dumpDomTree(true);
589 } else if ("about:debug.render".equals(urlData.mUrl)) {
590 current.getWebView().dumpRenderTree(false);
591 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
592 current.getWebView().dumpRenderTree(true);
593 } else if ("about:debug.display".equals(urlData.mUrl)) {
594 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800595 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
596 int index = urlData.mUrl.codePointAt(16) - '0';
597 if (index <= 0 || index > 9) {
598 current.getWebView().setDragTracker(null);
599 } else {
600 current.getWebView().setDragTracker(new MeshTracker(index));
601 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800602 } else {
603 mSettings.toggleDebugSettings();
604 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800605 return;
606 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400607 // Get rid of the subwindow if it exists
608 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500609 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800610 }
611 }
612 }
613
Satish Sampath565505b2009-05-29 15:37:27 +0100614 private int parseUrlShortcut(String url) {
615 if (url == null) return SHORTCUT_INVALID;
616
617 // FIXME: quick search, need to be customized by setting
618 if (url.length() > 2 && url.charAt(1) == ' ') {
619 switch (url.charAt(0)) {
620 case 'g': return SHORTCUT_GOOGLE_SEARCH;
621 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
622 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
623 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
624 }
625 }
626 return SHORTCUT_INVALID;
627 }
628
629 /**
630 * Launches the default web search activity with the query parameters if the given intent's data
631 * are identified as plain search terms and not URLs/shortcuts.
632 * @return true if the intent was handled and web search activity was launched, false if not.
633 */
634 private boolean handleWebSearchIntent(Intent intent) {
635 if (intent == null) return false;
636
637 String url = null;
638 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500639 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
640 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500641 return false;
642 }
Satish Sampath565505b2009-05-29 15:37:27 +0100643 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700644 Uri data = intent.getData();
645 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100646 } else if (Intent.ACTION_SEARCH.equals(action)
647 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
648 || Intent.ACTION_WEB_SEARCH.equals(action)) {
649 url = intent.getStringExtra(SearchManager.QUERY);
650 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100651 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
652 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100653 }
654
655 /**
656 * Launches the default web search activity with the query parameters if the given url string
657 * was identified as plain search terms and not URL/shortcut.
658 * @return true if the request was handled and web search activity was launched, false if not.
659 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100660 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100661 if (inUrl == null) return false;
662
663 // In general, we shouldn't modify URL from Intent.
664 // But currently, we get the user-typed URL from search box as well.
665 String url = fixUrl(inUrl).trim();
666
667 // URLs and site specific search shortcuts are handled by the regular flow of control, so
668 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800669 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100670 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100671 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
672 return false;
673 }
674
675 Browser.updateVisitedHistory(mResolver, url, false);
676 Browser.addSearchUrl(mResolver, url);
677
678 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
679 intent.addCategory(Intent.CATEGORY_DEFAULT);
680 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100681 if (appData != null) {
682 intent.putExtra(SearchManager.APP_DATA, appData);
683 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100684 if (extraData != null) {
685 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
686 }
Grace Klobacc634032009-07-28 15:58:19 -0700687 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100688 startActivity(intent);
689
690 return true;
691 }
692
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700693 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500694 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800695 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 if (intent != null) {
697 final String action = intent.getAction();
698 if (Intent.ACTION_VIEW.equals(action)) {
699 url = smartUrlFilter(intent.getData());
700 if (url != null && url.startsWith("content:")) {
701 /* Append mimetype so webview knows how to display */
702 String mimeType = intent.resolveType(getContentResolver());
703 if (mimeType != null) {
704 url += "?" + mimeType;
705 }
706 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800707 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800708 final Bundle pairs = intent
709 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800710 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800711 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800712 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800713 while (iter.hasNext()) {
714 String key = iter.next();
715 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800716 }
717 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700718 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800719 } else if (Intent.ACTION_SEARCH.equals(action)
720 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
721 || Intent.ACTION_WEB_SEARCH.equals(action)) {
722 url = intent.getStringExtra(SearchManager.QUERY);
723 if (url != null) {
724 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800725 // In general, we shouldn't modify URL from Intent.
726 // But currently, we get the user-typed URL from search box as well.
727 url = fixUrl(url);
728 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500729 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800730 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
731 if (url.contains(searchSource)) {
732 String source = null;
733 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
734 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000735 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 }
737 if (TextUtils.isEmpty(source)) {
738 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
739 }
740 url = url.replace(searchSource, "&source=android-"+source+"&");
741 }
742 }
743 }
744 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500745 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800746 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500747 /* package */ void showVoiceTitleBar(String title) {
748 mTitleBar.setInVoiceMode(true);
749 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750
Leon Scroggins58d56c62010-01-28 15:12:40 -0500751 mTitleBar.setDisplayTitle(title);
752 mFakeTitleBar.setDisplayTitle(title);
753 }
754 /* package */ void revertVoiceTitleBar() {
755 mTitleBar.setInVoiceMode(false);
756 mFakeTitleBar.setInVoiceMode(false);
757
758 mTitleBar.setDisplayTitle(mTitle);
759 mFakeTitleBar.setDisplayTitle(mTitle);
760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400762 // FIXME: Converting the url to lower case
763 // duplicates functionality in smartUrlFilter().
764 // However, changing all current callers of fixUrl to
765 // call smartUrlFilter in addition may have unwanted
766 // consequences, and is deferred for now.
767 int colon = inUrl.indexOf(':');
768 boolean allLower = true;
769 for (int index = 0; index < colon; index++) {
770 char ch = inUrl.charAt(index);
771 if (!Character.isLetter(ch)) {
772 break;
773 }
774 allLower &= Character.isLowerCase(ch);
775 if (index == colon - 1 && !allLower) {
776 inUrl = inUrl.substring(0, colon).toLowerCase()
777 + inUrl.substring(colon);
778 }
779 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800780 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
781 return inUrl;
782 if (inUrl.startsWith("http:") ||
783 inUrl.startsWith("https:")) {
784 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
785 inUrl = inUrl.replaceFirst("/", "//");
786 } else inUrl = inUrl.replaceFirst(":", "://");
787 }
788 return inUrl;
789 }
790
Grace Kloba22ac16e2009-10-07 18:00:23 -0700791 @Override
792 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700794 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800795 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
796 }
797
798 if (!mActivityInPause) {
799 Log.e(LOGTAG, "BrowserActivity is already resumed.");
800 return;
801 }
802
Mike Reed7bfa63b2009-05-28 11:08:32 -0400803 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800804 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400805 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800806
807 if (mWakeLock.isHeld()) {
808 mHandler.removeMessages(RELEASE_WAKELOCK);
809 mWakeLock.release();
810 }
811
812 if (mCredsDlg != null) {
813 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
814 // In case credential request never comes back
815 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
816 }
817 }
818
819 registerReceiver(mNetworkStateIntentReceiver,
820 mNetworkStateChangedFilter);
821 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800822 }
823
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400824 /**
825 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400826 * would change its appearance, use a different TitleBar to show overlayed
827 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 */
829 private TitleBar mFakeTitleBar;
830
831 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400832 * Holder for the fake title bar. It will have a foreground shadow, as well
833 * as a white background, so the fake title bar looks like the real one.
834 */
835 private ViewGroup mFakeTitleBarHolder;
836
837 /**
838 * Layout parameters for the fake title bar within mFakeTitleBarHolder
839 */
840 private FrameLayout.LayoutParams mFakeTitleBarParams
841 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800842 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400843 ViewGroup.LayoutParams.WRAP_CONTENT);
844 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400845 * Keeps track of whether the options menu is open. This is important in
846 * determining whether to show or hide the title bar overlay.
847 */
848 private boolean mOptionsMenuOpen;
849
850 /**
851 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
852 * of whether the configuration has changed. The first onMenuOpened call
853 * after a configuration change is simply a reopening of the same menu
854 * (i.e. mIconView did not change).
855 */
856 private boolean mConfigChanged;
857
858 /**
859 * Whether or not the options menu is in its smaller, icon menu form. When
860 * true, we want the title bar overlay to be up. When false, we do not.
861 * Only meaningful if mOptionsMenuOpen is true.
862 */
863 private boolean mIconView;
864
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400865 @Override
866 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400867 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
868 if (mOptionsMenuOpen) {
869 if (mConfigChanged) {
870 // We do not need to make any changes to the state of the
871 // title bar, since the only thing that happened was a
872 // change in orientation
873 mConfigChanged = false;
874 } else {
875 if (mIconView) {
876 // Switching the menu to expanded view, so hide the
877 // title bar.
878 hideFakeTitleBar();
879 mIconView = false;
880 } else {
881 // Switching the menu back to icon view, so show the
882 // title bar once again.
883 showFakeTitleBar();
884 mIconView = true;
885 }
886 }
887 } else {
888 // The options menu is closed, so open it, and show the title
889 showFakeTitleBar();
890 mOptionsMenuOpen = true;
891 mConfigChanged = false;
892 mIconView = true;
893 }
894 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400895 return true;
896 }
897
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400898 /**
899 * Special class used exclusively for the shadow drawn underneath the fake
900 * title bar. The shadow does not need to be drawn if the WebView
901 * underneath is scrolled to the top, because it will draw directly on top
902 * of the embedded shadow.
903 */
904 private static class Shadow extends View {
905 private WebView mWebView;
906
907 public Shadow(Context context, AttributeSet attrs) {
908 super(context, attrs);
909 }
910
911 public void setWebView(WebView view) {
912 mWebView = view;
913 }
914
915 @Override
916 public void draw(Canvas canvas) {
917 // In general onDraw is the method to override, but we care about
918 // whether or not the background gets drawn, which happens in draw()
919 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
920 super.draw(canvas);
921 }
922 // Need to invalidate so that if the scroll position changes, we
923 // still draw as appropriate.
924 invalidate();
925 }
926 }
927
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400928 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400929 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400930 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400931 && !mActivityInPause && decor != null
932 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400933 Rect visRect = new Rect();
934 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
935 if (LOGD_ENABLED) {
936 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
937 }
938 return;
939 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400940
941 WindowManager manager
942 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
943
944 // Add the title bar to the window manager so it can receive touches
945 // while the menu is up
946 WindowManager.LayoutParams params
947 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800948 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400949 ViewGroup.LayoutParams.WRAP_CONTENT,
950 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
951 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400952 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400953 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400954 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400955 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400956 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 // XXX : Without providing an offset, the fake title bar will be
958 // placed underneath the status bar. Use the global visible rect
959 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400960 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400961 // Add a holder for the title bar. It also holds a shadow to show
962 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400963 if (mFakeTitleBarHolder == null) {
964 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
965 .inflate(R.layout.title_bar_bg, null);
966 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400967 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
968 R.id.shadow);
969 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400970 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400971 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400972 }
973 }
974
975 @Override
976 public void onOptionsMenuClosed(Menu menu) {
977 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400978 if (!mInLoad) {
979 hideFakeTitleBar();
980 } else if (!mIconView) {
981 // The page is currently loading, and we are in expanded mode, so
982 // we were not showing the menu. Show it once again. It will be
983 // removed when the page finishes.
984 showFakeTitleBar();
985 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700987
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400988 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400989 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400990 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
991 mFakeTitleBarHolder.getLayoutParams();
992 WebView mainView = mTabControl.getCurrentWebView();
993 // Although we decided whether or not to animate based on the current
994 // scroll position, the scroll position may have changed since the
995 // fake title bar was displayed. Make sure it has the appropriate
996 // animation/lack thereof before removing.
997 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400998 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 WindowManager manager
1000 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001001 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001002 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1003 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001004 }
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001007 * Special method for the fake title bar to call when displaying its context
1008 * menu, since it is in its own Window, and its parent does not show a
1009 * context menu.
1010 */
1011 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001012 if (null == mTitleBar.getParent()) {
1013 return;
1014 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001015 openContextMenu(mTitleBar);
1016 }
1017
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001018 @Override
1019 public void onContextMenuClosed(Menu menu) {
1020 super.onContextMenuClosed(menu);
1021 if (mInLoad) {
1022 showFakeTitleBar();
1023 }
1024 }
1025
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001026 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 * onSaveInstanceState(Bundle map)
1028 * onSaveInstanceState is called right before onStop(). The map contains
1029 * the saved state.
1030 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 @Override
1032 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001033 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1035 }
1036 // the default implementation requires each view to have an id. As the
1037 // browser handles the state itself and it doesn't use id for the views,
1038 // don't call the default implementation. Otherwise it will trigger the
1039 // warning like this, "couldn't save which view has focus because the
1040 // focused view XXX has no id".
1041
1042 // Save all the tabs
1043 mTabControl.saveState(outState);
1044 }
1045
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 @Override
1047 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 super.onPause();
1049
1050 if (mActivityInPause) {
1051 Log.e(LOGTAG, "BrowserActivity is already paused.");
1052 return;
1053 }
1054
Mike Reed7bfa63b2009-05-28 11:08:32 -04001055 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001057 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 mWakeLock.acquire();
1059 mHandler.sendMessageDelayed(mHandler
1060 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1061 }
1062
1063 // Clear the credentials toast if it is up
1064 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1065 mCredsDlg.dismiss();
1066 }
1067 mCredsDlg = null;
1068
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001069 // FIXME: This removes the active tabs page and resets the menu to
1070 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1071 // but then we would need to save it in onSaveInstanceState and restore
1072 // it in onCreate/onRestoreInstanceState
1073 if (mActiveTabsPage != null) {
1074 removeActiveTabPage(true);
1075 }
1076
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 cancelStopToast();
1078
1079 // unregister network state listener
1080 unregisterReceiver(mNetworkStateIntentReceiver);
1081 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 }
1083
Grace Kloba22ac16e2009-10-07 18:00:23 -07001084 @Override
1085 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001086 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1088 }
1089 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001090
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001091 if (mUploadMessage != null) {
1092 mUploadMessage.onReceiveValue(null);
1093 mUploadMessage = null;
1094 }
1095
Grace Kloba0923d692009-09-23 21:37:25 -07001096 if (mTabControl == null) return;
1097
Grace Kloba1fc98a32009-10-21 13:23:08 -07001098 // Remove the fake title bar if it is there
1099 hideFakeTitleBar();
1100
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001103 if (t != null) {
1104 dismissSubWindow(t);
1105 removeTabFromContentView(t);
1106 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 // Destroy all the tabs
1108 mTabControl.destroy();
1109 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110
Grace Klobab4da0ad2009-05-14 14:45:40 -07001111 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 }
1113
1114 @Override
1115 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001116 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 super.onConfigurationChanged(newConfig);
1118
1119 if (mPageInfoDialog != null) {
1120 mPageInfoDialog.dismiss();
1121 showPageInfo(
1122 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001123 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 }
1125 if (mSSLCertificateDialog != null) {
1126 mSSLCertificateDialog.dismiss();
1127 showSSLCertificate(
1128 mSSLCertificateView);
1129 }
1130 if (mSSLCertificateOnErrorDialog != null) {
1131 mSSLCertificateOnErrorDialog.dismiss();
1132 showSSLCertificateOnError(
1133 mSSLCertificateOnErrorView,
1134 mSSLCertificateOnErrorHandler,
1135 mSSLCertificateOnErrorError);
1136 }
1137 if (mHttpAuthenticationDialog != null) {
1138 String title = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1140 .toString();
1141 String name = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(R.id.username_edit)).getText().toString();
1143 String password = ((TextView) mHttpAuthenticationDialog
1144 .findViewById(R.id.password_edit)).getText().toString();
1145 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1146 .getId();
1147 mHttpAuthenticationDialog.dismiss();
1148 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1149 name, password, focusId);
1150 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 }
1152
Grace Kloba22ac16e2009-10-07 18:00:23 -07001153 @Override
1154 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 super.onLowMemory();
1156 mTabControl.freeMemory();
1157 }
1158
Mike Reed7bfa63b2009-05-28 11:08:32 -04001159 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001160 Tab tab = mTabControl.getCurrentTab();
1161 boolean inLoad = tab.inLoad();
1162 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001164 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 if (w != null) {
1166 w.resumeTimers();
1167 }
1168 return true;
1169 } else {
1170 return false;
1171 }
1172 }
1173
Mike Reed7bfa63b2009-05-28 11:08:32 -04001174 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001175 Tab tab = mTabControl.getCurrentTab();
1176 boolean inLoad = tab.inLoad();
1177 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 CookieSyncManager.getInstance().stopSync();
1179 WebView w = mTabControl.getCurrentWebView();
1180 if (w != null) {
1181 w.pauseTimers();
1182 }
1183 return true;
1184 } else {
1185 return false;
1186 }
1187 }
1188
Leon Scroggins1f005d32009-08-10 17:36:42 -04001189 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 /*
1191 * This function is called when we are launching for the first time. We
1192 * are waiting for the login credentials before loading Google home
1193 * pages. This way the user will be logged in straight away.
1194 */
1195 private void waitForCredentials() {
1196 // Show a toast
1197 mCredsDlg = new ProgressDialog(this);
1198 mCredsDlg.setIndeterminate(true);
1199 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1200 // If the user cancels the operation, then cancel the Google
1201 // Credentials request.
1202 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1203 mCredsDlg.show();
1204
1205 // We set a timeout for the retrieval of credentials in onResume()
1206 // as that is when we have freed up some CPU time to get
1207 // the login credentials.
1208 }
1209
1210 /*
1211 * If we have received the credentials or we have timed out and we are
1212 * showing the credentials dialog, then it is time to move on.
1213 */
1214 private void resumeAfterCredentials() {
1215 if (mCredsDlg == null) {
1216 return;
1217 }
1218
1219 // Clear the toast
1220 if (mCredsDlg.isShowing()) {
1221 mCredsDlg.dismiss();
1222 }
1223 mCredsDlg = null;
1224
1225 // Clear any pending timeout
1226 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1227
1228 // Load the page
1229 WebView w = mTabControl.getCurrentWebView();
1230 if (w != null) {
Leon Scroggins92472e82010-02-17 16:32:28 -05001231 loadUrl(w, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 }
1233
1234 // Update the settings, need to do this last as it can take a moment
1235 // to persist the settings. In the mean time we could be loading
1236 // content.
1237 mSettings.setLoginInitialized(this);
1238 }
1239
1240 // Open the icon database and retain all the icons for visited sites.
1241 private void retainIconsOnStartup() {
1242 final WebIconDatabase db = WebIconDatabase.getInstance();
1243 db.open(getDir("icons", 0).getPath());
1244 try {
1245 Cursor c = Browser.getAllBookmarks(mResolver);
1246 if (!c.moveToFirst()) {
1247 c.deactivate();
1248 return;
1249 }
1250 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1251 do {
1252 String url = c.getString(urlIndex);
1253 db.retainIconForPageUrl(url);
1254 } while (c.moveToNext());
1255 c.deactivate();
1256 } catch (IllegalStateException e) {
1257 Log.e(LOGTAG, "retainIconsOnStartup", e);
1258 }
1259 }
1260
1261 // Helper method for getting the top window.
1262 WebView getTopWindow() {
1263 return mTabControl.getCurrentTopWebView();
1264 }
1265
Grace Kloba22ac16e2009-10-07 18:00:23 -07001266 TabControl getTabControl() {
1267 return mTabControl;
1268 }
1269
The Android Open Source Project0c908882009-03-03 19:32:16 -08001270 @Override
1271 public boolean onCreateOptionsMenu(Menu menu) {
1272 super.onCreateOptionsMenu(menu);
1273
1274 MenuInflater inflater = getMenuInflater();
1275 inflater.inflate(R.menu.browser, menu);
1276 mMenu = menu;
1277 updateInLoadMenuItems();
1278 return true;
1279 }
1280
1281 /**
1282 * As the menu can be open when loading state changes
1283 * we must manually update the state of the stop/reload menu
1284 * item
1285 */
1286 private void updateInLoadMenuItems() {
1287 if (mMenu == null) {
1288 return;
1289 }
1290 MenuItem src = mInLoad ?
1291 mMenu.findItem(R.id.stop_menu_id):
1292 mMenu.findItem(R.id.reload_menu_id);
1293 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1294 dest.setIcon(src.getIcon());
1295 dest.setTitle(src.getTitle());
1296 }
1297
1298 @Override
1299 public boolean onContextItemSelected(MenuItem item) {
1300 // chording is not an issue with context menus, but we use the same
1301 // options selector, so set mCanChord to true so we can access them.
1302 mCanChord = true;
1303 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001304 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001306 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001307 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001308 Tab currentTab = mTabControl.getCurrentTab();
1309 if (null == currentTab) {
1310 result = false;
1311 break;
1312 }
1313 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001314 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001315 result = false;
1316 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001317 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001318 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001319 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001320 // -- Browser context menu
1321 case R.id.open_context_menu_id:
1322 case R.id.open_newtab_context_menu_id:
1323 case R.id.bookmark_context_menu_id:
1324 case R.id.save_link_context_menu_id:
1325 case R.id.share_link_context_menu_id:
1326 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001327 final WebView webView = getTopWindow();
1328 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001329 result = false;
1330 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001331 }
1332 final HashMap hrefMap = new HashMap();
1333 hrefMap.put("webview", webView);
1334 final Message msg = mHandler.obtainMessage(
1335 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 webView.requestFocusNodeHref(msg);
1337 break;
1338
1339 default:
1340 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001341 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 }
1343 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001344 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 }
1346
1347 private Bundle createGoogleSearchSourceBundle(String source) {
1348 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001349 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001350 return bundle;
1351 }
1352
Leon Scroggins8ad29922010-02-16 12:33:55 -05001353 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001354 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001355 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001356 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001357 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 }
1359
Leon Scroggins8ad29922010-02-16 12:33:55 -05001360 /**
1361 * Overriding this to insert a local information bundle
1362 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 @Override
1364 public void startSearch(String initialQuery, boolean selectInitialQuery,
1365 Bundle appSearchData, boolean globalSearch) {
1366 if (appSearchData == null) {
1367 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1368 }
1369 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1370 }
1371
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 /**
1373 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1374 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001375 * @param index Index of the tab to change to, as defined by
1376 * mTabControl.getTabIndex(Tab t).
1377 * @return boolean True if we successfully switched to a different tab. If
1378 * the indexth tab is null, or if that tab is the same as
1379 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001382 Tab tab = mTabControl.getTab(index);
1383 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001384 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 }
1387 if (currentTab != null) {
1388 // currentTab may be null if it was just removed. In that case,
1389 // we do not need to remove it
1390 removeTabFromContentView(currentTab);
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 mTabControl.setCurrentTab(tab);
1393 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001394 resetTitleIconAndProgress();
1395 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001396 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001397 }
1398
Grace Kloba22ac16e2009-10-07 18:00:23 -07001399 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001400 return openTabAndShow(mSettings.getHomePage(), false, null);
1401 }
1402
Leon Scroggins1f005d32009-08-10 17:36:42 -04001403 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001404 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001406 // This is the last tab. Open a new one, with the home
1407 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001409 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001410 return;
1411 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001412 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001413 int indexToShow = -1;
1414 if (parent != null) {
1415 indexToShow = mTabControl.getTabIndex(parent);
1416 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001417 final int currentIndex = mTabControl.getCurrentIndex();
1418 // Try to move to the tab to the right
1419 indexToShow = currentIndex + 1;
1420 if (indexToShow > mTabControl.getTabCount() - 1) {
1421 // Try to move to the tab to the left
1422 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001423 }
1424 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001425 if (switchToTab(indexToShow)) {
1426 // Close window
1427 closeTab(current);
1428 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001429 }
1430
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001431 private ActiveTabsPage mActiveTabsPage;
1432
1433 /**
1434 * Remove the active tabs page.
1435 * @param needToAttach If true, the active tabs page did not attach a tab
1436 * to the content view, so we need to do that here.
1437 */
1438 /* package */ void removeActiveTabPage(boolean needToAttach) {
1439 mContentView.removeView(mActiveTabsPage);
1440 mActiveTabsPage = null;
1441 mMenuState = R.id.MAIN_MENU;
1442 if (needToAttach) {
1443 attachTabToContentView(mTabControl.getCurrentTab());
1444 }
1445 getTopWindow().requestFocus();
1446 }
1447
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 @Override
1449 public boolean onOptionsItemSelected(MenuItem item) {
1450 if (!mCanChord) {
1451 // The user has already fired a shortcut with this hold down of the
1452 // menu key.
1453 return false;
1454 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001455 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001456 return false;
1457 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001458 if (mMenuIsDown) {
1459 // The shortcut action consumes the MENU. Even if it is still down,
1460 // it won't trigger the next shortcut action. In the case of the
1461 // shortcut action triggering a new activity, like Bookmarks, we
1462 // won't get onKeyUp for MENU. So it is important to reset it here.
1463 mMenuIsDown = false;
1464 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 switch (item.getItemId()) {
1466 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001467 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001468 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001469 break;
1470
Leon Scroggins64b80f32009-08-07 12:03:34 -04001471 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001472 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001473 break;
1474
1475 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001476 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 break;
1478
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001479 case R.id.active_tabs_menu_id:
1480 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1481 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001482 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001483 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1484 mActiveTabsPage.requestFocus();
1485 mMenuState = EMPTY_MENU;
1486 break;
1487
Leon Scroggins1f005d32009-08-10 17:36:42 -04001488 case R.id.add_bookmark_menu_id:
1489 Intent i = new Intent(BrowserActivity.this,
1490 AddBookmarkPage.class);
1491 WebView w = getTopWindow();
1492 i.putExtra("url", w.getUrl());
1493 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001494 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001495 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001496 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 break;
1498
1499 case R.id.stop_reload_menu_id:
1500 if (mInLoad) {
1501 stopLoading();
1502 } else {
1503 getTopWindow().reload();
1504 }
1505 break;
1506
1507 case R.id.back_menu_id:
1508 getTopWindow().goBack();
1509 break;
1510
1511 case R.id.forward_menu_id:
1512 getTopWindow().goForward();
1513 break;
1514
1515 case R.id.close_menu_id:
1516 // Close the subwindow if it exists.
1517 if (mTabControl.getCurrentSubWindow() != null) {
1518 dismissSubWindow(mTabControl.getCurrentTab());
1519 break;
1520 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001521 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 break;
1523
1524 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001525 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 if (current != null) {
1527 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001528 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 }
1530 break;
1531
1532 case R.id.preferences_menu_id:
1533 Intent intent = new Intent(this,
1534 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001535 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1536 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 startActivityForResult(intent, PREFERENCES_PAGE);
1538 break;
1539
1540 case R.id.find_menu_id:
1541 if (null == mFindDialog) {
1542 mFindDialog = new FindDialog(this);
1543 }
1544 mFindDialog.setWebView(getTopWindow());
1545 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001546 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001547 mMenuState = EMPTY_MENU;
1548 break;
1549
1550 case R.id.select_text_id:
1551 getTopWindow().emulateShiftHeld();
1552 break;
1553 case R.id.page_info_menu_id:
1554 showPageInfo(mTabControl.getCurrentTab(), false);
1555 break;
1556
1557 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001558 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 break;
1560
Leon Scroggins96afcb12009-12-10 12:35:56 -05001561 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001562 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001563 Tab currentTab = mTabControl.getCurrentTab();
1564 if (null == currentTab) {
1565 mCanChord = false;
1566 return false;
1567 }
1568 currentTab.populatePickerData();
1569 sharePage(this, currentTab.getTitle(),
1570 currentTab.getUrl(), currentTab.getFavicon(),
1571 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001572 break;
1573
1574 case R.id.dump_nav_menu_id:
1575 getTopWindow().debugDump();
1576 break;
1577
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001578 case R.id.dump_counters_menu_id:
1579 getTopWindow().dumpV8Counters();
1580 break;
1581
The Android Open Source Project0c908882009-03-03 19:32:16 -08001582 case R.id.zoom_in_menu_id:
1583 getTopWindow().zoomIn();
1584 break;
1585
1586 case R.id.zoom_out_menu_id:
1587 getTopWindow().zoomOut();
1588 break;
1589
1590 case R.id.view_downloads_menu_id:
1591 viewDownloads(null);
1592 break;
1593
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 case R.id.window_one_menu_id:
1595 case R.id.window_two_menu_id:
1596 case R.id.window_three_menu_id:
1597 case R.id.window_four_menu_id:
1598 case R.id.window_five_menu_id:
1599 case R.id.window_six_menu_id:
1600 case R.id.window_seven_menu_id:
1601 case R.id.window_eight_menu_id:
1602 {
1603 int menuid = item.getItemId();
1604 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1605 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001606 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 if (desiredTab != null &&
1608 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001609 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001610 }
1611 break;
1612 }
1613 }
1614 }
1615 break;
1616
1617 default:
1618 if (!super.onOptionsItemSelected(item)) {
1619 return false;
1620 }
1621 // Otherwise fall through.
1622 }
1623 mCanChord = false;
1624 return true;
1625 }
1626
1627 public void closeFind() {
1628 mMenuState = R.id.MAIN_MENU;
1629 }
1630
Grace Kloba22ac16e2009-10-07 18:00:23 -07001631 @Override
1632 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 // This happens when the user begins to hold down the menu key, so
1634 // allow them to chord to get a shortcut.
1635 mCanChord = true;
1636 // Note: setVisible will decide whether an item is visible; while
1637 // setEnabled() will decide whether an item is enabled, which also means
1638 // whether the matching shortcut key will function.
1639 super.onPrepareOptionsMenu(menu);
1640 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 case EMPTY_MENU:
1642 if (mCurrentMenuState != mMenuState) {
1643 menu.setGroupVisible(R.id.MAIN_MENU, false);
1644 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1645 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001646 }
1647 break;
1648 default:
1649 if (mCurrentMenuState != mMenuState) {
1650 menu.setGroupVisible(R.id.MAIN_MENU, true);
1651 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1652 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001653 }
1654 final WebView w = getTopWindow();
1655 boolean canGoBack = false;
1656 boolean canGoForward = false;
1657 boolean isHome = false;
1658 if (w != null) {
1659 canGoBack = w.canGoBack();
1660 canGoForward = w.canGoForward();
1661 isHome = mSettings.getHomePage().equals(w.getUrl());
1662 }
1663 final MenuItem back = menu.findItem(R.id.back_menu_id);
1664 back.setEnabled(canGoBack);
1665
1666 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1667 home.setEnabled(!isHome);
1668
1669 menu.findItem(R.id.forward_menu_id)
1670 .setEnabled(canGoForward);
1671
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001672 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001673 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001674
The Android Open Source Project0c908882009-03-03 19:32:16 -08001675 // decide whether to show the share link option
1676 PackageManager pm = getPackageManager();
1677 Intent send = new Intent(Intent.ACTION_SEND);
1678 send.setType("text/plain");
1679 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1680 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1681
The Android Open Source Project0c908882009-03-03 19:32:16 -08001682 boolean isNavDump = mSettings.isNavDump();
1683 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1684 nav.setVisible(isNavDump);
1685 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001686
1687 boolean showDebugSettings = mSettings.showDebugSettings();
1688 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1689 counter.setVisible(showDebugSettings);
1690 counter.setEnabled(showDebugSettings);
1691
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 break;
1693 }
1694 mCurrentMenuState = mMenuState;
1695 return true;
1696 }
1697
1698 @Override
1699 public void onCreateContextMenu(ContextMenu menu, View v,
1700 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001701 if (v instanceof TitleBar) {
1702 return;
1703 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001704 WebView webview = (WebView) v;
1705 WebView.HitTestResult result = webview.getHitTestResult();
1706 if (result == null) {
1707 return;
1708 }
1709
1710 int type = result.getType();
1711 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1712 Log.w(LOGTAG,
1713 "We should not show context menu when nothing is touched");
1714 return;
1715 }
1716 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1717 // let TextView handles context menu
1718 return;
1719 }
1720
1721 // Note, http://b/issue?id=1106666 is requesting that
1722 // an inflated menu can be used again. This is not available
1723 // yet, so inflate each time (yuk!)
1724 MenuInflater inflater = getMenuInflater();
1725 inflater.inflate(R.menu.browsercontext, menu);
1726
1727 // Show the correct menu group
1728 String extra = result.getExtra();
1729 menu.setGroupVisible(R.id.PHONE_MENU,
1730 type == WebView.HitTestResult.PHONE_TYPE);
1731 menu.setGroupVisible(R.id.EMAIL_MENU,
1732 type == WebView.HitTestResult.EMAIL_TYPE);
1733 menu.setGroupVisible(R.id.GEO_MENU,
1734 type == WebView.HitTestResult.GEO_TYPE);
1735 menu.setGroupVisible(R.id.IMAGE_MENU,
1736 type == WebView.HitTestResult.IMAGE_TYPE
1737 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1738 menu.setGroupVisible(R.id.ANCHOR_MENU,
1739 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1740 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1741
1742 // Setup custom handling depending on the type
1743 switch (type) {
1744 case WebView.HitTestResult.PHONE_TYPE:
1745 menu.setHeaderTitle(Uri.decode(extra));
1746 menu.findItem(R.id.dial_context_menu_id).setIntent(
1747 new Intent(Intent.ACTION_VIEW, Uri
1748 .parse(WebView.SCHEME_TEL + extra)));
1749 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1750 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001751 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1753 addIntent);
1754 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1755 new Copy(extra));
1756 break;
1757
1758 case WebView.HitTestResult.EMAIL_TYPE:
1759 menu.setHeaderTitle(extra);
1760 menu.findItem(R.id.email_context_menu_id).setIntent(
1761 new Intent(Intent.ACTION_VIEW, Uri
1762 .parse(WebView.SCHEME_MAILTO + extra)));
1763 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1764 new Copy(extra));
1765 break;
1766
1767 case WebView.HitTestResult.GEO_TYPE:
1768 menu.setHeaderTitle(extra);
1769 menu.findItem(R.id.map_context_menu_id).setIntent(
1770 new Intent(Intent.ACTION_VIEW, Uri
1771 .parse(WebView.SCHEME_GEO
1772 + URLEncoder.encode(extra))));
1773 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1774 new Copy(extra));
1775 break;
1776
1777 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1778 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1779 TextView titleView = (TextView) LayoutInflater.from(this)
1780 .inflate(android.R.layout.browser_link_context_header,
1781 null);
1782 titleView.setText(extra);
1783 menu.setHeaderView(titleView);
1784 // decide whether to show the open link in new tab option
1785 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001786 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001787 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1788 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 PackageManager pm = getPackageManager();
1790 Intent send = new Intent(Intent.ACTION_SEND);
1791 send.setType("text/plain");
1792 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1793 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1794 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1795 break;
1796 }
1797 // otherwise fall through to handle image part
1798 case WebView.HitTestResult.IMAGE_TYPE:
1799 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1800 menu.setHeaderTitle(extra);
1801 }
1802 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1803 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1804 menu.findItem(R.id.download_context_menu_id).
1805 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001806 menu.findItem(R.id.set_wallpaper_context_menu_id).
1807 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001808 break;
1809
1810 default:
1811 Log.w(LOGTAG, "We should not get here.");
1812 break;
1813 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001814 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 }
1816
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001818 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001819 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001820 // Attach the container that contains the main WebView and any other UI
1821 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001822 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001823
1824 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001825 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001826 if (errorConsole.numberOfErrors() == 0) {
1827 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1828 } else {
1829 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1830 }
1831
1832 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001833 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001834 ViewGroup.LayoutParams.WRAP_CONTENT));
1835 }
1836
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001837 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001838 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001839 if (t.isInVoiceSearchMode()) {
1840 showVoiceTitleBar(t.getVoiceDisplayTitle());
1841 } else {
1842 revertVoiceTitleBar();
1843 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001844 // Request focus on the top window.
1845 t.getTopWindow().requestFocus();
1846 }
1847
1848 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001849 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001850 t.attachSubWindow(mContentView);
1851 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 }
1853
1854 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001855 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001856 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001857 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001858
Grace Kloba22ac16e2009-10-07 18:00:23 -07001859 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1860 if (errorConsole != null) {
1861 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001862 }
1863
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001864 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001865 if (view != null) {
1866 view.setEmbeddedTitleBar(null);
1867 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 }
1869
1870 // Remove the sub window if it exists. Also called by TabControl when the
1871 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001872 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001873 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001874 // dismiss the subwindow. This will destroy the WebView.
1875 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001876 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
1878
Leon Scroggins1f005d32009-08-10 17:36:42 -04001879 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001880 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001881 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001882 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 }
1884
1885 // This method does a ton of stuff. It will attempt to create a new tab
1886 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001887 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001888 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1889 String appId) {
1890 final Tab currentTab = mTabControl.getCurrentTab();
1891 if (mTabControl.canCreateNewTab()) {
1892 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1893 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001894 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001895 // If the last tab was removed from the active tabs page, currentTab
1896 // will be null.
1897 if (currentTab != null) {
1898 removeTabFromContentView(currentTab);
1899 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001900 // We must set the new tab as the current tab to reflect the old
1901 // animation behavior.
1902 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001903 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001904 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001905 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001906 }
1907 return tab;
1908 } else {
1909 // Get rid of the subwindow if it exists
1910 dismissSubWindow(currentTab);
1911 if (!urlData.isEmpty()) {
1912 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001913 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001914 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001915 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001916 }
1917 }
1918
Grace Kloba22ac16e2009-10-07 18:00:23 -07001919 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001920 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001921 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001923 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001924 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 }
Grace Klobac9181842009-04-14 08:53:22 -07001926 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001927 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001928 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 }
1930 }
1931
1932 private class Copy implements OnMenuItemClickListener {
1933 private CharSequence mText;
1934
1935 public boolean onMenuItemClick(MenuItem item) {
1936 copy(mText);
1937 return true;
1938 }
1939
1940 public Copy(CharSequence toCopy) {
1941 mText = toCopy;
1942 }
1943 }
1944
1945 private class Download implements OnMenuItemClickListener {
1946 private String mText;
1947
1948 public boolean onMenuItemClick(MenuItem item) {
1949 onDownloadStartNoStream(mText, null, null, null, -1);
1950 return true;
1951 }
1952
1953 public Download(String toDownload) {
1954 mText = toDownload;
1955 }
1956 }
1957
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001958 private class SetAsWallpaper extends Thread implements
1959 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1960 private URL mUrl;
1961 private ProgressDialog mWallpaperProgress;
1962 private boolean mCanceled = false;
1963
1964 public SetAsWallpaper(String url) {
1965 try {
1966 mUrl = new URL(url);
1967 } catch (MalformedURLException e) {
1968 mUrl = null;
1969 }
1970 }
1971
1972 public void onCancel(DialogInterface dialog) {
1973 mCanceled = true;
1974 }
1975
1976 public boolean onMenuItemClick(MenuItem item) {
1977 if (mUrl != null) {
1978 // The user may have tried to set a image with a large file size as their
1979 // background so it may take a few moments to perform the operation. Display
1980 // a progress spinner while it is working.
1981 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1982 mWallpaperProgress.setIndeterminate(true);
1983 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1984 mWallpaperProgress.setCancelable(true);
1985 mWallpaperProgress.setOnCancelListener(this);
1986 mWallpaperProgress.show();
1987 start();
1988 }
1989 return true;
1990 }
1991
1992 public void run() {
1993 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1994 try {
1995 // TODO: This will cause the resource to be downloaded again, when we
1996 // should in most cases be able to grab it from the cache. To fix this
1997 // we should query WebCore to see if we can access a cached version and
1998 // instead open an input stream on that. This pattern could also be used
1999 // in the download manager where the same problem exists.
2000 InputStream inputstream = mUrl.openStream();
2001 if (inputstream != null) {
2002 setWallpaper(inputstream);
2003 }
2004 } catch (IOException e) {
2005 Log.e(LOGTAG, "Unable to set new wallpaper");
2006 // Act as though the user canceled the operation so we try to
2007 // restore the old wallpaper.
2008 mCanceled = true;
2009 }
2010
2011 if (mCanceled) {
2012 // Restore the old wallpaper if the user cancelled whilst we were setting
2013 // the new wallpaper.
2014 int width = oldWallpaper.getIntrinsicWidth();
2015 int height = oldWallpaper.getIntrinsicHeight();
2016 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2017 Canvas canvas = new Canvas(bm);
2018 oldWallpaper.setBounds(0, 0, width, height);
2019 oldWallpaper.draw(canvas);
2020 try {
2021 setWallpaper(bm);
2022 } catch (IOException e) {
2023 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2024 }
2025 mCanceled = false;
2026 }
2027
2028 if (mWallpaperProgress.isShowing()) {
2029 mWallpaperProgress.dismiss();
2030 }
2031 }
2032 }
2033
The Android Open Source Project0c908882009-03-03 19:32:16 -08002034 private void copy(CharSequence text) {
2035 try {
2036 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2037 if (clip != null) {
2038 clip.setClipboardText(text);
2039 }
2040 } catch (android.os.RemoteException e) {
2041 Log.e(LOGTAG, "Copy failed", e);
2042 }
2043 }
2044
2045 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 * Resets the browser title-view to whatever it must be
2047 * (for example, if we had a loading error)
2048 * When we have a new page, we call resetTitle, when we
2049 * have to reset the titlebar to whatever it used to be
2050 * (for example, if the user chose to stop loading), we
2051 * call resetTitleAndRevertLockIcon.
2052 */
2053 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002054 mTabControl.getCurrentTab().revertLockIcon();
2055 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 resetTitleIconAndProgress();
2057 }
2058
2059 /**
2060 * Reset the title, favicon, and progress.
2061 */
2062 private void resetTitleIconAndProgress() {
2063 WebView current = mTabControl.getCurrentWebView();
2064 if (current == null) {
2065 return;
2066 }
2067 resetTitleAndIcon(current);
2068 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002069 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002070 }
2071
2072 // Reset the title and the icon based on the given item.
2073 private void resetTitleAndIcon(WebView view) {
2074 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2075 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002076 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 setFavicon(item.getFavicon());
2078 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002079 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 setFavicon(null);
2081 }
2082 }
2083
2084 /**
2085 * Sets a title composed of the URL and the title string.
2086 * @param url The URL of the site being loaded.
2087 * @param title The title of the site being loaded.
2088 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002089 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 mUrl = url;
2091 mTitle = title;
2092
Leon Scroggins58d56c62010-01-28 15:12:40 -05002093 // If we are in voice search mode, the title has already been set.
2094 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2095 mTitleBar.setDisplayTitle(url);
2096 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098
2099 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 * @param url The URL to build a title version of the URL from.
2101 * @return The title version of the URL or null if fails.
2102 * The title version of the URL can be either the URL hostname,
2103 * or the hostname with an "https://" prefix (for secure URLs),
2104 * or an empty string if, for example, the URL in question is a
2105 * file:// URL with no hostname.
2106 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002107 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 String titleUrl = null;
2109
2110 if (url != null) {
2111 try {
2112 // parse the url string
2113 URL urlObj = new URL(url);
2114 if (urlObj != null) {
2115 titleUrl = "";
2116
2117 String protocol = urlObj.getProtocol();
2118 String host = urlObj.getHost();
2119
2120 if (host != null && 0 < host.length()) {
2121 titleUrl = host;
2122 if (protocol != null) {
2123 // if a secure site, add an "https://" prefix!
2124 if (protocol.equalsIgnoreCase("https")) {
2125 titleUrl = protocol + "://" + host;
2126 }
2127 }
2128 }
2129 }
2130 } catch (MalformedURLException e) {}
2131 }
2132
2133 return titleUrl;
2134 }
2135
2136 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002137 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002138 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002139 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002140 }
2141
2142 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002143 * Close the tab, remove its associated title bar, and adjust mTabControl's
2144 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002145 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002146 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002147 int currentIndex = mTabControl.getCurrentIndex();
2148 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002149 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002150 if (currentIndex >= removeIndex && currentIndex != 0) {
2151 currentIndex--;
2152 }
2153 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002154 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002155 }
2156
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002157 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002158 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 if (current == null) {
2160 /*
2161 * Instead of finishing the activity, simply push this to the back
2162 * of the stack and let ActivityManager to choose the foreground
2163 * activity. As BrowserActivity is singleTask, it will be always the
2164 * root of the task. So we can use either true or false for
2165 * moveTaskToBack().
2166 */
2167 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002168 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 }
2170 WebView w = current.getWebView();
2171 if (w.canGoBack()) {
2172 w.goBack();
2173 } else {
2174 // Check to see if we are closing a window that was created by
2175 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002176 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002178 switchToTab(mTabControl.getTabIndex(parent));
2179 // Now we close the other tab
2180 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002181 } else {
2182 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002183 // force the tab's inLoad() to be false as we are going to
2184 // either finish the activity or remove the tab. This will
2185 // ensure pauseWebViewTimers() taking action.
2186 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 if (mTabControl.getTabCount() == 1) {
2188 finish();
2189 return;
2190 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002191 // call pauseWebViewTimers() now, we won't be able to call
2192 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002193 // Temporarily change mActivityInPause to be true as
2194 // pauseWebViewTimers() will do nothing if mActivityInPause
2195 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002196 boolean savedState = mActivityInPause;
2197 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002198 Log.e(LOGTAG, "BrowserActivity is already paused "
2199 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002200 }
2201 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002202 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002203 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 removeTabFromContentView(current);
2205 mTabControl.removeTab(current);
2206 }
2207 /*
2208 * Instead of finishing the activity, simply push this to the back
2209 * of the stack and let ActivityManager to choose the foreground
2210 * activity. As BrowserActivity is singleTask, it will be always the
2211 * root of the task. So we can use either true or false for
2212 * moveTaskToBack().
2213 */
2214 moveTaskToBack(true);
2215 }
2216 }
2217 }
2218
Grace Kloba22ac16e2009-10-07 18:00:23 -07002219 boolean isMenuDown() {
2220 return mMenuIsDown;
2221 }
2222
Grace Kloba5942df02009-09-18 11:48:29 -07002223 @Override
2224 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002225 // Even if MENU is already held down, we need to call to super to open
2226 // the IME on long press.
2227 if (KeyEvent.KEYCODE_MENU == keyCode) {
2228 mMenuIsDown = true;
2229 return super.onKeyDown(keyCode, event);
2230 }
Grace Kloba5942df02009-09-18 11:48:29 -07002231 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2232 // still down, we don't want to trigger the search. Pretend to consume
2233 // the key and do nothing.
2234 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235
Grace Kloba5942df02009-09-18 11:48:29 -07002236 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002237 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002238 // WebView/WebTextView handle the keys in the KeyDown. As
2239 // the Activity's shortcut keys are only handled when WebView
2240 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2241 if (event.isShiftPressed()) {
2242 getTopWindow().pageUp(false);
2243 } else {
2244 getTopWindow().pageDown(false);
2245 }
Grace Kloba5942df02009-09-18 11:48:29 -07002246 return true;
2247 case KeyEvent.KEYCODE_BACK:
2248 if (event.getRepeatCount() == 0) {
2249 event.startTracking();
2250 return true;
2251 } else if (mCustomView == null && mActiveTabsPage == null
2252 && event.isLongPress()) {
2253 bookmarksOrHistoryPicker(true);
2254 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255 }
Grace Kloba5942df02009-09-18 11:48:29 -07002256 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 }
Grace Kloba5942df02009-09-18 11:48:29 -07002258 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002259 }
2260
Grace Kloba5942df02009-09-18 11:48:29 -07002261 @Override
2262 public boolean onKeyUp(int keyCode, KeyEvent event) {
2263 switch(keyCode) {
2264 case KeyEvent.KEYCODE_MENU:
2265 mMenuIsDown = false;
2266 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002267 case KeyEvent.KEYCODE_BACK:
2268 if (event.isTracking() && !event.isCanceled()) {
2269 if (mCustomView != null) {
2270 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 mTabControl.getCurrentWebView().getWebChromeClient()
2272 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002273 } else if (mActiveTabsPage != null) {
2274 // if tab page is showing, hide it
2275 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002277 WebView subwindow = mTabControl.getCurrentSubWindow();
2278 if (subwindow != null) {
2279 if (subwindow.canGoBack()) {
2280 subwindow.goBack();
2281 } else {
2282 dismissSubWindow(mTabControl.getCurrentTab());
2283 }
2284 } else {
2285 goBackOnePageOrQuit();
2286 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002287 }
Grace Kloba5942df02009-09-18 11:48:29 -07002288 return true;
2289 }
2290 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291 }
Grace Kloba5942df02009-09-18 11:48:29 -07002292 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002293 }
2294
Leon Scroggins68579392009-09-15 15:31:54 -04002295 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002296 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 resetTitleAndRevertLockIcon();
2298 WebView w = getTopWindow();
2299 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002300 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2301 // same logic here. But for subwindow case, should we call into the main
2302 // WebView's onPageFinished as we never call its onPageStarted and if
2303 // the page finishes itself, we don't call onPageFinished.
2304 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2305 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306
2307 cancelStopToast();
2308 mStopToast = Toast
2309 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2310 mStopToast.show();
2311 }
2312
Grace Kloba22ac16e2009-10-07 18:00:23 -07002313 boolean didUserStopLoading() {
2314 return mDidStopLoad;
2315 }
2316
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317 private void cancelStopToast() {
2318 if (mStopToast != null) {
2319 mStopToast.cancel();
2320 mStopToast = null;
2321 }
2322 }
2323
Grace Kloba22ac16e2009-10-07 18:00:23 -07002324 // called by a UI or non-UI thread to post the message
2325 public void postMessage(int what, int arg1, int arg2, Object obj,
2326 long delayMillis) {
2327 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2328 obj), delayMillis);
2329 }
2330
2331 // called by a UI or non-UI thread to remove the message
2332 void removeMessages(int what, Object object) {
2333 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002334 }
2335
2336 // public message ids
2337 public final static int LOAD_URL = 1001;
2338 public final static int STOP_LOAD = 1002;
2339
2340 // Message Ids
2341 private static final int FOCUS_NODE_HREF = 102;
2342 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002343 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002344
Grace Kloba22ac16e2009-10-07 18:00:23 -07002345 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002346
The Android Open Source Project0c908882009-03-03 19:32:16 -08002347 // Private handler for handling javascript and saving passwords
2348 private Handler mHandler = new Handler() {
2349
2350 public void handleMessage(Message msg) {
2351 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002353 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002354 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002355 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 if (url == null || url.length() == 0) {
2357 break;
2358 }
2359 HashMap focusNodeMap = (HashMap) msg.obj;
2360 WebView view = (WebView) focusNodeMap.get("webview");
2361 // Only apply the action if the top window did not change.
2362 if (getTopWindow() != view) {
2363 break;
2364 }
2365 switch (msg.arg1) {
2366 case R.id.open_context_menu_id:
2367 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002368 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002369 break;
2370 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002371 final Tab parent = mTabControl.getCurrentTab();
2372 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002373 if (newTab != parent) {
2374 parent.addChildTab(newTab);
2375 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002376 break;
2377 case R.id.bookmark_context_menu_id:
2378 Intent intent = new Intent(BrowserActivity.this,
2379 AddBookmarkPage.class);
2380 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002381 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 startActivity(intent);
2383 break;
2384 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002385 // See if this site has been visited before
2386 StringBuilder sb = new StringBuilder(
2387 Browser.BookmarkColumns.URL + " = ");
2388 DatabaseUtils.appendEscapedSQLString(sb, url);
2389 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2390 Browser.HISTORY_PROJECTION,
2391 sb.toString(),
2392 null,
2393 null);
2394 if (c.moveToFirst()) {
2395 // The site has been visited before, so grab the
2396 // info from the database.
2397 Bitmap favicon = null;
2398 Bitmap thumbnail = null;
2399 String linkTitle = c.getString(Browser.
2400 HISTORY_PROJECTION_TITLE_INDEX);
2401 byte[] data = c.getBlob(Browser.
2402 HISTORY_PROJECTION_FAVICON_INDEX);
2403 if (data != null) {
2404 favicon = BitmapFactory.decodeByteArray(
2405 data, 0, data.length);
2406 }
2407 data = c.getBlob(Browser.
2408 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2409 if (data != null) {
2410 thumbnail = BitmapFactory.decodeByteArray(
2411 data, 0, data.length);
2412 }
2413 sharePage(BrowserActivity.this,
2414 linkTitle, url, favicon, thumbnail);
2415 } else {
2416 Browser.sendString(BrowserActivity.this, url,
2417 getString(
2418 R.string.choosertitle_sharevia));
2419 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 break;
2421 case R.id.copy_link_context_menu_id:
2422 copy(url);
2423 break;
2424 case R.id.save_link_context_menu_id:
2425 case R.id.download_context_menu_id:
2426 onDownloadStartNoStream(url, null, null, null, -1);
2427 break;
2428 }
2429 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002431
2432 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002433 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002434 break;
2435
2436 case STOP_LOAD:
2437 stopLoading();
2438 break;
2439
2440 case CANCEL_CREDS_REQUEST:
2441 resumeAfterCredentials();
2442 break;
2443
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444 case RELEASE_WAKELOCK:
2445 if (mWakeLock.isHeld()) {
2446 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002447 // if we reach here, Browser should be still in the
2448 // background loading after WAKELOCK_TIMEOUT (5-min).
2449 // To avoid burning the battery, stop loading.
2450 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002451 }
2452 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002453
2454 case UPDATE_BOOKMARK_THUMBNAIL:
2455 WebView view = (WebView) msg.obj;
2456 if (view != null) {
2457 updateScreenshot(view);
2458 }
2459 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002460 }
2461 }
2462 };
2463
Leon Scroggins96afcb12009-12-10 12:35:56 -05002464 /**
2465 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2466 * an {@link Intent} to launch the Activity chooser.
2467 * @param c Context used to launch a new Activity.
2468 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002469 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002470 * @param url URL of the page. Stored in the Intent with
2471 * {@link Intent#EXTRA_TEXT}
2472 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2473 * with {@link Browser#EXTRA_SHARE_FAVICON}
2474 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2475 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2476 */
2477 public static final void sharePage(Context c, String title, String url,
2478 Bitmap favicon, Bitmap screenshot) {
2479 Intent send = new Intent(Intent.ACTION_SEND);
2480 send.setType("text/plain");
2481 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002482 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002483 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2484 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2485 try {
2486 c.startActivity(Intent.createChooser(send, c.getString(
2487 R.string.choosertitle_sharevia)));
2488 } catch(android.content.ActivityNotFoundException ex) {
2489 // if no app handles it, do nothing
2490 }
2491 }
2492
Leon Scroggins89c6d362009-07-15 16:54:37 -04002493 private void updateScreenshot(WebView view) {
2494 // If this is a bookmarked site, add a screenshot to the database.
2495 // FIXME: When should we update? Every time?
2496 // FIXME: Would like to make sure there is actually something to
2497 // draw, but the API for that (WebViewCore.pictureReady()) is not
2498 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002499
Patrick Scott3918d442009-08-04 13:22:29 -04002500 ContentResolver cr = getContentResolver();
2501 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002502 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002503 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002504 boolean succeed = c.moveToFirst();
2505 ContentValues values = null;
2506 while (succeed) {
2507 if (values == null) {
2508 final ByteArrayOutputStream os
2509 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002510 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002511 if (bm == null) {
2512 c.close();
2513 return;
2514 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002515 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2516 values = new ContentValues();
2517 values.put(Browser.BookmarkColumns.THUMBNAIL,
2518 os.toByteArray());
2519 }
2520 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2521 c.getInt(0)), values, null, null);
2522 succeed = c.moveToNext();
2523 }
2524 c.close();
2525 }
2526 }
2527
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002528 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002529 * Values for the size of the thumbnail created when taking a screenshot.
2530 * Lazily initialized. Instead of using these directly, use
2531 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002532 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002533 private static int THUMBNAIL_WIDTH = 0;
2534 private static int THUMBNAIL_HEIGHT = 0;
2535
2536 /**
2537 * Return the desired width for thumbnail screenshots, which are stored in
2538 * the database, and used on the bookmarks screen.
2539 * @param context Context for finding out the density of the screen.
2540 * @return int desired width for thumbnail screenshot.
2541 */
2542 /* package */ static int getDesiredThumbnailWidth(Context context) {
2543 if (THUMBNAIL_WIDTH == 0) {
2544 float density = context.getResources().getDisplayMetrics().density;
2545 THUMBNAIL_WIDTH = (int) (90 * density);
2546 THUMBNAIL_HEIGHT = (int) (80 * density);
2547 }
2548 return THUMBNAIL_WIDTH;
2549 }
2550
2551 /**
2552 * Return the desired height for thumbnail screenshots, which are stored in
2553 * the database, and used on the bookmarks screen.
2554 * @param context Context for finding out the density of the screen.
2555 * @return int desired height for thumbnail screenshot.
2556 */
2557 /* package */ static int getDesiredThumbnailHeight(Context context) {
2558 // To ensure that they are both initialized.
2559 getDesiredThumbnailWidth(context);
2560 return THUMBNAIL_HEIGHT;
2561 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002562
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002563 private Bitmap createScreenshot(WebView view) {
2564 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002565 if (thumbnail == null) {
2566 return null;
2567 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002568 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2569 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002570 Canvas canvas = new Canvas(bm);
2571 // May need to tweak these values to determine what is the
2572 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002573 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002574 int thumbnailHeight = thumbnail.getHeight();
2575 float scaleFactorX = 1.0f;
2576 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002577 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002578 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002579 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002580 } else {
2581 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002582 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002583
2584 if (view.getWidth() > view.getHeight() &&
2585 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2586 // If the device is in landscape and the page is shorter
2587 // than the height of the view, stretch the thumbnail to fill the
2588 // space.
2589 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2590 (float)thumbnailHeight;
2591 } else {
2592 // In the portrait case, this looks nice.
2593 scaleFactorY = scaleFactorX;
2594 }
2595
2596 canvas.scale(scaleFactorX, scaleFactorY);
2597
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002598 thumbnail.draw(canvas);
2599 return bm;
2600 }
2601
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 //-------------------------------------------------------------------------
2605
2606 // Use in overrideUrlLoading
2607 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2608 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2609 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2610 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2611
Leon Scroggins92472e82010-02-17 16:32:28 -05002612 // Keep this initial progress in sync with initialProgressValue (* 100)
2613 // in ProgressTracker.cpp
2614 private final static int INITIAL_PROGRESS = 10;
2615
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 void onPageStarted(WebView view, String url, Bitmap favicon) {
2617 // when BrowserActivity just starts, onPageStarted may be called before
2618 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2619 // to start the timer. As we won't switch tabs while an activity is in
2620 // pause state, we can ensure calling resume and pause in pair.
2621 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002622
Grace Kloba22ac16e2009-10-07 18:00:23 -07002623 resetLockIcon(url);
2624 setUrlTitle(url, null);
2625 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002626 // Show some progress so that the user knows the page is beginning to
2627 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002628 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002630 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002631
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 if (mSettings.isTracing()) {
2633 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 WebAddress uri = new WebAddress(url);
2636 host = uri.mHost;
2637 } catch (android.net.ParseException ex) {
2638 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002639 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 host = host.replace('.', '_');
2641 host += ".trace";
2642 mInTrace = true;
2643 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2644 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 // Performance probe
2647 if (false) {
2648 mStart = SystemClock.uptimeMillis();
2649 mProcessStart = Process.getElapsedCpuTime();
2650 long[] sysCpu = new long[7];
2651 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2652 sysCpu, null)) {
2653 mUserStart = sysCpu[0] + sysCpu[1];
2654 mSystemStart = sysCpu[2];
2655 mIdleStart = sysCpu[3];
2656 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2657 }
2658 mUiStart = SystemClock.currentThreadTimeMillis();
2659 }
2660 }
2661
2662 void onPageFinished(WebView view, String url) {
2663 // Reset the title and icon in case we stopped a provisional load.
2664 resetTitleAndIcon(view);
2665 // Update the lock icon image only once we are done loading
2666 updateLockIconToLatest();
2667 // pause the WebView timer and release the wake lock if it is finished
2668 // while BrowserActivity is in pause state.
2669 if (mActivityInPause && pauseWebViewTimers()) {
2670 if (mWakeLock.isHeld()) {
2671 mHandler.removeMessages(RELEASE_WAKELOCK);
2672 mWakeLock.release();
2673 }
2674 }
2675
2676 // Performance probe
2677 if (false) {
2678 long[] sysCpu = new long[7];
2679 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2680 sysCpu, null)) {
2681 String uiInfo = "UI thread used "
2682 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2683 + " ms";
2684 if (LOGD_ENABLED) {
2685 Log.d(LOGTAG, uiInfo);
2686 }
2687 //The string that gets written to the log
2688 String performanceString = "It took total "
2689 + (SystemClock.uptimeMillis() - mStart)
2690 + " ms clock time to load the page."
2691 + "\nbrowser process used "
2692 + (Process.getElapsedCpuTime() - mProcessStart)
2693 + " ms, user processes used "
2694 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2695 + " ms, kernel used "
2696 + (sysCpu[2] - mSystemStart) * 10
2697 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2698 + " ms and irq took "
2699 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2700 * 10 + " ms, " + uiInfo;
2701 if (LOGD_ENABLED) {
2702 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2703 }
2704 if (url != null) {
2705 // strip the url to maintain consistency
2706 String newUrl = new String(url);
2707 if (newUrl.startsWith("http://www.")) {
2708 newUrl = newUrl.substring(11);
2709 } else if (newUrl.startsWith("http://")) {
2710 newUrl = newUrl.substring(7);
2711 } else if (newUrl.startsWith("https://www.")) {
2712 newUrl = newUrl.substring(12);
2713 } else if (newUrl.startsWith("https://")) {
2714 newUrl = newUrl.substring(8);
2715 }
2716 if (LOGD_ENABLED) {
2717 Log.d(LOGTAG, newUrl + " loaded");
2718 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002719 }
2720 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002722
Grace Kloba22ac16e2009-10-07 18:00:23 -07002723 if (mInTrace) {
2724 mInTrace = false;
2725 Debug.stopMethodTracing();
2726 }
2727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 boolean shouldOverrideUrlLoading(WebView view, String url) {
2730 if (url.startsWith(SCHEME_WTAI)) {
2731 // wtai://wp/mc;number
2732 // number=string(phone-number)
2733 if (url.startsWith(SCHEME_WTAI_MC)) {
2734 Intent intent = new Intent(Intent.ACTION_VIEW,
2735 Uri.parse(WebView.SCHEME_TEL +
2736 url.substring(SCHEME_WTAI_MC.length())));
2737 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738 return true;
2739 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002740 // wtai://wp/sd;dtmf
2741 // dtmf=string(dialstring)
2742 if (url.startsWith(SCHEME_WTAI_SD)) {
2743 // TODO: only send when there is active voice connection
2744 return false;
2745 }
2746 // wtai://wp/ap;number;name
2747 // number=string(phone-number)
2748 // name=string
2749 if (url.startsWith(SCHEME_WTAI_AP)) {
2750 // TODO
2751 return false;
2752 }
2753 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 // The "about:" schemes are internal to the browser; don't want these to
2756 // be dispatched to other apps.
2757 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 return false;
2759 }
2760
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 Intent intent;
2762 // perform generic parsing of the URI to turn it into an Intent.
2763 try {
2764 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2765 } catch (URISyntaxException ex) {
2766 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2767 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002768 }
2769
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 // check whether the intent can be resolved. If not, we will see
2771 // whether we can download it from the Market.
2772 if (getPackageManager().resolveActivity(intent, 0) == null) {
2773 String packagename = intent.getPackage();
2774 if (packagename != null) {
2775 intent = new Intent(Intent.ACTION_VIEW, Uri
2776 .parse("market://search?q=pname:" + packagename));
2777 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2778 startActivity(intent);
2779 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780 } else {
2781 return false;
2782 }
2783 }
2784
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 // sanitize the Intent, ensuring web pages can not bypass browser
2786 // security (only access to BROWSABLE activities).
2787 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2788 intent.setComponent(null);
2789 try {
2790 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002791 return true;
2792 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002793 } catch (ActivityNotFoundException ex) {
2794 // ignore the error. If no application can handle the URL,
2795 // eg about:blank, assume the browser can handle it.
2796 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797
Grace Kloba22ac16e2009-10-07 18:00:23 -07002798 if (mMenuIsDown) {
2799 openTab(url);
2800 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002801 return true;
2802 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002803 return false;
2804 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002805
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 // -------------------------------------------------------------------------
2807 // Helper function for WebChromeClient
2808 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 void onProgressChanged(WebView view, int newProgress) {
2811 mTitleBar.setProgress(newProgress);
2812 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 if (newProgress == 100) {
2815 // onProgressChanged() may continue to be called after the main
2816 // frame has finished loading, as any remaining sub frames continue
2817 // to load. We'll only get called once though with newProgress as
2818 // 100 when everything is loaded. (onPageFinished is called once
2819 // when the main frame completes loading regardless of the state of
2820 // any sub frames so calls to onProgressChanges may continue after
2821 // onPageFinished has executed)
2822 if (mInLoad) {
2823 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002824 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002825 // If the options menu is open, leave the title bar
2826 if (!mOptionsMenuOpen || !mIconView) {
2827 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002828 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002829 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002830 } else if (!mInLoad) {
2831 // onPageFinished may have already been called but a subframe is
2832 // still loading and updating the progress. Reset mInLoad and update
2833 // the menu items.
2834 mInLoad = true;
2835 updateInLoadMenuItems();
2836 if (!mOptionsMenuOpen || mIconView) {
2837 // This page has begun to load, so show the title bar
2838 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002839 }
2840 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002841 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002842
Grace Kloba22ac16e2009-10-07 18:00:23 -07002843 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002844 // if a view already exists then immediately terminate the new one
2845 if (mCustomView != null) {
2846 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002847 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002848 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002849
2850 // Add the custom view to its container.
2851 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2852 mCustomView = view;
2853 mCustomViewCallback = callback;
2854 // Save the menu state and set it to empty while the custom
2855 // view is showing.
2856 mOldMenuState = mMenuState;
2857 mMenuState = EMPTY_MENU;
2858 // Hide the content view.
2859 mContentView.setVisibility(View.GONE);
2860 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002861 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 mCustomViewContainer.setVisibility(View.VISIBLE);
2863 mCustomViewContainer.bringToFront();
2864 }
2865
2866 void onHideCustomView() {
2867 if (mCustomView == null)
2868 return;
2869
2870 // Hide the custom view.
2871 mCustomView.setVisibility(View.GONE);
2872 // Remove the custom view from its container.
2873 mCustomViewContainer.removeView(mCustomView);
2874 mCustomView = null;
2875 // Reset the old menu state.
2876 mMenuState = mOldMenuState;
2877 mOldMenuState = EMPTY_MENU;
2878 mCustomViewContainer.setVisibility(View.GONE);
2879 mCustomViewCallback.onCustomViewHidden();
2880 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002881 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002882 mContentView.setVisibility(View.VISIBLE);
2883 }
2884
2885 Bitmap getDefaultVideoPoster() {
2886 if (mDefaultVideoPoster == null) {
2887 mDefaultVideoPoster = BitmapFactory.decodeResource(
2888 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002889 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002890 return mDefaultVideoPoster;
2891 }
Patrick Scott3918d442009-08-04 13:22:29 -04002892
Grace Kloba22ac16e2009-10-07 18:00:23 -07002893 View getVideoLoadingProgressView() {
2894 if (mVideoProgressView == null) {
2895 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2896 mVideoProgressView = inflater.inflate(
2897 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002898 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002899 return mVideoProgressView;
2900 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002902 /*
2903 * The Object used to inform the WebView of the file to upload.
2904 */
2905 private ValueCallback<Uri> mUploadMessage;
2906
Grace Kloba22ac16e2009-10-07 18:00:23 -07002907 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2908 if (mUploadMessage != null) return;
2909 mUploadMessage = uploadMsg;
2910 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2911 i.addCategory(Intent.CATEGORY_OPENABLE);
2912 i.setType("*/*");
2913 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2914 getString(R.string.choose_upload)), FILE_SELECTED);
2915 }
2916
2917 // -------------------------------------------------------------------------
2918 // Implement functions for DownloadListener
2919 // -------------------------------------------------------------------------
2920
The Android Open Source Project0c908882009-03-03 19:32:16 -08002921 /**
2922 * Notify the host application a download should be done, or that
2923 * the data should be streamed if a streaming viewer is available.
2924 * @param url The full url to the content that should be downloaded
2925 * @param contentDisposition Content-disposition http header, if
2926 * present.
2927 * @param mimetype The mimetype of the content reported by the server
2928 * @param contentLength The file size reported by the server
2929 */
2930 public void onDownloadStart(String url, String userAgent,
2931 String contentDisposition, String mimetype, long contentLength) {
2932 // if we're dealing wih A/V content that's not explicitly marked
2933 // for download, check if it's streamable.
2934 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002935 || !contentDisposition.regionMatches(
2936 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937 // query the package manager to see if there's a registered handler
2938 // that matches.
2939 Intent intent = new Intent(Intent.ACTION_VIEW);
2940 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002941 ResolveInfo info = getPackageManager().resolveActivity(intent,
2942 PackageManager.MATCH_DEFAULT_ONLY);
2943 if (info != null) {
2944 ComponentName myName = getComponentName();
2945 // If we resolved to ourselves, we don't want to attempt to
2946 // load the url only to try and download it again.
2947 if (!myName.getPackageName().equals(
2948 info.activityInfo.packageName)
2949 || !myName.getClassName().equals(
2950 info.activityInfo.name)) {
2951 // someone (other than us) knows how to handle this mime
2952 // type with this scheme, don't download.
2953 try {
2954 startActivity(intent);
2955 return;
2956 } catch (ActivityNotFoundException ex) {
2957 if (LOGD_ENABLED) {
2958 Log.d(LOGTAG, "activity not found for " + mimetype
2959 + " over " + Uri.parse(url).getScheme(),
2960 ex);
2961 }
2962 // Best behavior is to fall back to a download in this
2963 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002965 }
2966 }
2967 }
2968 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2969 }
2970
2971 /**
2972 * Notify the host application a download should be done, even if there
2973 * is a streaming viewer available for thise type.
2974 * @param url The full url to the content that should be downloaded
2975 * @param contentDisposition Content-disposition http header, if
2976 * present.
2977 * @param mimetype The mimetype of the content reported by the server
2978 * @param contentLength The file size reported by the server
2979 */
2980 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2981 String contentDisposition, String mimetype, long contentLength) {
2982
2983 String filename = URLUtil.guessFileName(url,
2984 contentDisposition, mimetype);
2985
2986 // Check to see if we have an SDCard
2987 String status = Environment.getExternalStorageState();
2988 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2989 int title;
2990 String msg;
2991
2992 // Check to see if the SDCard is busy, same as the music app
2993 if (status.equals(Environment.MEDIA_SHARED)) {
2994 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2995 title = R.string.download_sdcard_busy_dlg_title;
2996 } else {
2997 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2998 title = R.string.download_no_sdcard_dlg_title;
2999 }
3000
3001 new AlertDialog.Builder(this)
3002 .setTitle(title)
3003 .setIcon(android.R.drawable.ic_dialog_alert)
3004 .setMessage(msg)
3005 .setPositiveButton(R.string.ok, null)
3006 .show();
3007 return;
3008 }
3009
3010 // java.net.URI is a lot stricter than KURL so we have to undo
3011 // KURL's percent-encoding and redo the encoding using java.net.URI.
3012 URI uri = null;
3013 try {
3014 // Undo the percent-encoding that KURL may have done.
3015 String newUrl = new String(URLUtil.decode(url.getBytes()));
3016 // Parse the url into pieces
3017 WebAddress w = new WebAddress(newUrl);
3018 String frag = null;
3019 String query = null;
3020 String path = w.mPath;
3021 // Break the path into path, query, and fragment
3022 if (path.length() > 0) {
3023 // Strip the fragment
3024 int idx = path.lastIndexOf('#');
3025 if (idx != -1) {
3026 frag = path.substring(idx + 1);
3027 path = path.substring(0, idx);
3028 }
3029 idx = path.lastIndexOf('?');
3030 if (idx != -1) {
3031 query = path.substring(idx + 1);
3032 path = path.substring(0, idx);
3033 }
3034 }
3035 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3036 query, frag);
3037 } catch (Exception e) {
3038 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3039 return;
3040 }
3041
3042 // XXX: Have to use the old url since the cookies were stored using the
3043 // old percent-encoded url.
3044 String cookies = CookieManager.getInstance().getCookie(url);
3045
3046 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003047 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3048 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3049 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3050 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003052 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003053 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003054 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3055 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3056 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3057 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3058 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003059 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003060 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003061 }
3062 if (mimetype == null) {
3063 // We must have long pressed on a link or image to download it. We
3064 // are not sure of the mimetype in this case, so do a head request
3065 new FetchUrlMimeType(this).execute(values);
3066 } else {
3067 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003068 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069 }
3070
3071 }
3072
Grace Kloba22ac16e2009-10-07 18:00:23 -07003073 // -------------------------------------------------------------------------
3074
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 /**
3076 * Resets the lock icon. This method is called when we start a new load and
3077 * know the url to be loaded.
3078 */
3079 private void resetLockIcon(String url) {
3080 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003081 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003082 updateLockIconImage(LOCK_ICON_UNSECURE);
3083 }
3084
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003086 * Update the lock icon to correspond to our latest state.
3087 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003088 private void updateLockIconToLatest() {
3089 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003090 }
3091
3092 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003093 * Updates the lock-icon image in the title-bar.
3094 */
3095 private void updateLockIconImage(int lockIconType) {
3096 Drawable d = null;
3097 if (lockIconType == LOCK_ICON_SECURE) {
3098 d = mSecLockIcon;
3099 } else if (lockIconType == LOCK_ICON_MIXED) {
3100 d = mMixLockIcon;
3101 }
Leon Scroggins68579392009-09-15 15:31:54 -04003102 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003103 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003104 }
3105
3106 /**
3107 * Displays a page-info dialog.
3108 * @param tab The tab to show info about
3109 * @param fromShowSSLCertificateOnError The flag that indicates whether
3110 * this dialog was opened from the SSL-certificate-on-error dialog or
3111 * not. This is important, since we need to know whether to return to
3112 * the parent dialog or simply dismiss.
3113 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003114 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003115 final boolean fromShowSSLCertificateOnError) {
3116 final LayoutInflater factory = LayoutInflater
3117 .from(this);
3118
3119 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3120
3121 final WebView view = tab.getWebView();
3122
3123 String url = null;
3124 String title = null;
3125
3126 if (view == null) {
3127 url = tab.getUrl();
3128 title = tab.getTitle();
3129 } else if (view == mTabControl.getCurrentWebView()) {
3130 // Use the cached title and url if this is the current WebView
3131 url = mUrl;
3132 title = mTitle;
3133 } else {
3134 url = view.getUrl();
3135 title = view.getTitle();
3136 }
3137
3138 if (url == null) {
3139 url = "";
3140 }
3141 if (title == null) {
3142 title = "";
3143 }
3144
3145 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3146 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3147
3148 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003149 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003150
3151 AlertDialog.Builder alertDialogBuilder =
3152 new AlertDialog.Builder(this)
3153 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3154 .setView(pageInfoView)
3155 .setPositiveButton(
3156 R.string.ok,
3157 new DialogInterface.OnClickListener() {
3158 public void onClick(DialogInterface dialog,
3159 int whichButton) {
3160 mPageInfoDialog = null;
3161 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003162
3163 // if we came here from the SSL error dialog
3164 if (fromShowSSLCertificateOnError) {
3165 // go back to the SSL error dialog
3166 showSSLCertificateOnError(
3167 mSSLCertificateOnErrorView,
3168 mSSLCertificateOnErrorHandler,
3169 mSSLCertificateOnErrorError);
3170 }
3171 }
3172 })
3173 .setOnCancelListener(
3174 new DialogInterface.OnCancelListener() {
3175 public void onCancel(DialogInterface dialog) {
3176 mPageInfoDialog = null;
3177 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003178
3179 // if we came here from the SSL error dialog
3180 if (fromShowSSLCertificateOnError) {
3181 // go back to the SSL error dialog
3182 showSSLCertificateOnError(
3183 mSSLCertificateOnErrorView,
3184 mSSLCertificateOnErrorHandler,
3185 mSSLCertificateOnErrorError);
3186 }
3187 }
3188 });
3189
3190 // if we have a main top-level page SSL certificate set or a certificate
3191 // error
3192 if (fromShowSSLCertificateOnError ||
3193 (view != null && view.getCertificate() != null)) {
3194 // add a 'View Certificate' button
3195 alertDialogBuilder.setNeutralButton(
3196 R.string.view_certificate,
3197 new DialogInterface.OnClickListener() {
3198 public void onClick(DialogInterface dialog,
3199 int whichButton) {
3200 mPageInfoDialog = null;
3201 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003202
3203 // if we came here from the SSL error dialog
3204 if (fromShowSSLCertificateOnError) {
3205 // go back to the SSL error dialog
3206 showSSLCertificateOnError(
3207 mSSLCertificateOnErrorView,
3208 mSSLCertificateOnErrorHandler,
3209 mSSLCertificateOnErrorError);
3210 } else {
3211 // otherwise, display the top-most certificate from
3212 // the chain
3213 if (view.getCertificate() != null) {
3214 showSSLCertificate(tab);
3215 }
3216 }
3217 }
3218 });
3219 }
3220
3221 mPageInfoDialog = alertDialogBuilder.show();
3222 }
3223
3224 /**
3225 * Displays the main top-level page SSL certificate dialog
3226 * (accessible from the Page-Info dialog).
3227 * @param tab The tab to show certificate for.
3228 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003229 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 final View certificateView =
3231 inflateCertificateView(tab.getWebView().getCertificate());
3232 if (certificateView == null) {
3233 return;
3234 }
3235
3236 LayoutInflater factory = LayoutInflater.from(this);
3237
3238 final LinearLayout placeholder =
3239 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3240
3241 LinearLayout ll = (LinearLayout) factory.inflate(
3242 R.layout.ssl_success, placeholder);
3243 ((TextView)ll.findViewById(R.id.success))
3244 .setText(R.string.ssl_certificate_is_valid);
3245
3246 mSSLCertificateView = tab;
3247 mSSLCertificateDialog =
3248 new AlertDialog.Builder(this)
3249 .setTitle(R.string.ssl_certificate).setIcon(
3250 R.drawable.ic_dialog_browser_certificate_secure)
3251 .setView(certificateView)
3252 .setPositiveButton(R.string.ok,
3253 new DialogInterface.OnClickListener() {
3254 public void onClick(DialogInterface dialog,
3255 int whichButton) {
3256 mSSLCertificateDialog = null;
3257 mSSLCertificateView = null;
3258
3259 showPageInfo(tab, false);
3260 }
3261 })
3262 .setOnCancelListener(
3263 new DialogInterface.OnCancelListener() {
3264 public void onCancel(DialogInterface dialog) {
3265 mSSLCertificateDialog = null;
3266 mSSLCertificateView = null;
3267
3268 showPageInfo(tab, false);
3269 }
3270 })
3271 .show();
3272 }
3273
3274 /**
3275 * Displays the SSL error certificate dialog.
3276 * @param view The target web-view.
3277 * @param handler The SSL error handler responsible for cancelling the
3278 * connection that resulted in an SSL error or proceeding per user request.
3279 * @param error The SSL error object.
3280 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003281 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 final WebView view, final SslErrorHandler handler, final SslError error) {
3283
3284 final View certificateView =
3285 inflateCertificateView(error.getCertificate());
3286 if (certificateView == null) {
3287 return;
3288 }
3289
3290 LayoutInflater factory = LayoutInflater.from(this);
3291
3292 final LinearLayout placeholder =
3293 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3294
3295 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3296 LinearLayout ll = (LinearLayout)factory
3297 .inflate(R.layout.ssl_warning, placeholder);
3298 ((TextView)ll.findViewById(R.id.warning))
3299 .setText(R.string.ssl_untrusted);
3300 }
3301
3302 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3303 LinearLayout ll = (LinearLayout)factory
3304 .inflate(R.layout.ssl_warning, placeholder);
3305 ((TextView)ll.findViewById(R.id.warning))
3306 .setText(R.string.ssl_mismatch);
3307 }
3308
3309 if (error.hasError(SslError.SSL_EXPIRED)) {
3310 LinearLayout ll = (LinearLayout)factory
3311 .inflate(R.layout.ssl_warning, placeholder);
3312 ((TextView)ll.findViewById(R.id.warning))
3313 .setText(R.string.ssl_expired);
3314 }
3315
3316 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3317 LinearLayout ll = (LinearLayout)factory
3318 .inflate(R.layout.ssl_warning, placeholder);
3319 ((TextView)ll.findViewById(R.id.warning))
3320 .setText(R.string.ssl_not_yet_valid);
3321 }
3322
3323 mSSLCertificateOnErrorHandler = handler;
3324 mSSLCertificateOnErrorView = view;
3325 mSSLCertificateOnErrorError = error;
3326 mSSLCertificateOnErrorDialog =
3327 new AlertDialog.Builder(this)
3328 .setTitle(R.string.ssl_certificate).setIcon(
3329 R.drawable.ic_dialog_browser_certificate_partially_secure)
3330 .setView(certificateView)
3331 .setPositiveButton(R.string.ok,
3332 new DialogInterface.OnClickListener() {
3333 public void onClick(DialogInterface dialog,
3334 int whichButton) {
3335 mSSLCertificateOnErrorDialog = null;
3336 mSSLCertificateOnErrorView = null;
3337 mSSLCertificateOnErrorHandler = null;
3338 mSSLCertificateOnErrorError = null;
3339
Grace Kloba22ac16e2009-10-07 18:00:23 -07003340 view.getWebViewClient().onReceivedSslError(
3341 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003342 }
3343 })
3344 .setNeutralButton(R.string.page_info_view,
3345 new DialogInterface.OnClickListener() {
3346 public void onClick(DialogInterface dialog,
3347 int whichButton) {
3348 mSSLCertificateOnErrorDialog = null;
3349
3350 // do not clear the dialog state: we will
3351 // need to show the dialog again once the
3352 // user is done exploring the page-info details
3353
3354 showPageInfo(mTabControl.getTabFromView(view),
3355 true);
3356 }
3357 })
3358 .setOnCancelListener(
3359 new DialogInterface.OnCancelListener() {
3360 public void onCancel(DialogInterface dialog) {
3361 mSSLCertificateOnErrorDialog = null;
3362 mSSLCertificateOnErrorView = null;
3363 mSSLCertificateOnErrorHandler = null;
3364 mSSLCertificateOnErrorError = null;
3365
Grace Kloba22ac16e2009-10-07 18:00:23 -07003366 view.getWebViewClient().onReceivedSslError(
3367 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003368 }
3369 })
3370 .show();
3371 }
3372
3373 /**
3374 * Inflates the SSL certificate view (helper method).
3375 * @param certificate The SSL certificate.
3376 * @return The resultant certificate view with issued-to, issued-by,
3377 * issued-on, expires-on, and possibly other fields set.
3378 * If the input certificate is null, returns null.
3379 */
3380 private View inflateCertificateView(SslCertificate certificate) {
3381 if (certificate == null) {
3382 return null;
3383 }
3384
3385 LayoutInflater factory = LayoutInflater.from(this);
3386
3387 View certificateView = factory.inflate(
3388 R.layout.ssl_certificate, null);
3389
3390 // issued to:
3391 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3392 if (issuedTo != null) {
3393 ((TextView) certificateView.findViewById(R.id.to_common))
3394 .setText(issuedTo.getCName());
3395 ((TextView) certificateView.findViewById(R.id.to_org))
3396 .setText(issuedTo.getOName());
3397 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3398 .setText(issuedTo.getUName());
3399 }
3400
3401 // issued by:
3402 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3403 if (issuedBy != null) {
3404 ((TextView) certificateView.findViewById(R.id.by_common))
3405 .setText(issuedBy.getCName());
3406 ((TextView) certificateView.findViewById(R.id.by_org))
3407 .setText(issuedBy.getOName());
3408 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3409 .setText(issuedBy.getUName());
3410 }
3411
3412 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003413 String issuedOn = formatCertificateDate(
3414 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 ((TextView) certificateView.findViewById(R.id.issued_on))
3416 .setText(issuedOn);
3417
3418 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003419 String expiresOn = formatCertificateDate(
3420 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003421 ((TextView) certificateView.findViewById(R.id.expires_on))
3422 .setText(expiresOn);
3423
3424 return certificateView;
3425 }
3426
3427 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003428 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003429 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003430 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003432 private String formatCertificateDate(Date certificateDate) {
3433 if (certificateDate == null) {
3434 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003435 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003436 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3437 if (formattedDate == null) {
3438 return "";
3439 }
3440 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003441 }
3442
3443 /**
3444 * Displays an http-authentication dialog.
3445 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003446 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 final String host, final String realm, final String title,
3448 final String name, final String password, int focusId) {
3449 LayoutInflater factory = LayoutInflater.from(this);
3450 final View v = factory
3451 .inflate(R.layout.http_authentication, null);
3452 if (name != null) {
3453 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3454 }
3455 if (password != null) {
3456 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3457 }
3458
3459 String titleText = title;
3460 if (titleText == null) {
3461 titleText = getText(R.string.sign_in_to).toString().replace(
3462 "%s1", host).replace("%s2", realm);
3463 }
3464
3465 mHttpAuthHandler = handler;
3466 AlertDialog dialog = new AlertDialog.Builder(this)
3467 .setTitle(titleText)
3468 .setIcon(android.R.drawable.ic_dialog_alert)
3469 .setView(v)
3470 .setPositiveButton(R.string.action,
3471 new DialogInterface.OnClickListener() {
3472 public void onClick(DialogInterface dialog,
3473 int whichButton) {
3474 String nm = ((EditText) v
3475 .findViewById(R.id.username_edit))
3476 .getText().toString();
3477 String pw = ((EditText) v
3478 .findViewById(R.id.password_edit))
3479 .getText().toString();
3480 BrowserActivity.this.setHttpAuthUsernamePassword
3481 (host, realm, nm, pw);
3482 handler.proceed(nm, pw);
3483 mHttpAuthenticationDialog = null;
3484 mHttpAuthHandler = null;
3485 }})
3486 .setNegativeButton(R.string.cancel,
3487 new DialogInterface.OnClickListener() {
3488 public void onClick(DialogInterface dialog,
3489 int whichButton) {
3490 handler.cancel();
3491 BrowserActivity.this.resetTitleAndRevertLockIcon();
3492 mHttpAuthenticationDialog = null;
3493 mHttpAuthHandler = null;
3494 }})
3495 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3496 public void onCancel(DialogInterface dialog) {
3497 handler.cancel();
3498 BrowserActivity.this.resetTitleAndRevertLockIcon();
3499 mHttpAuthenticationDialog = null;
3500 mHttpAuthHandler = null;
3501 }})
3502 .create();
3503 // Make the IME appear when the dialog is displayed if applicable.
3504 dialog.getWindow().setSoftInputMode(
3505 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3506 dialog.show();
3507 if (focusId != 0) {
3508 dialog.findViewById(focusId).requestFocus();
3509 } else {
3510 v.findViewById(R.id.username_edit).requestFocus();
3511 }
3512 mHttpAuthenticationDialog = dialog;
3513 }
3514
3515 public int getProgress() {
3516 WebView w = mTabControl.getCurrentWebView();
3517 if (w != null) {
3518 return w.getProgress();
3519 } else {
3520 return 100;
3521 }
3522 }
3523
3524 /**
3525 * Set HTTP authentication password.
3526 *
3527 * @param host The host for the password
3528 * @param realm The realm for the password
3529 * @param username The username for the password. If it is null, it means
3530 * password can't be saved.
3531 * @param password The password
3532 */
3533 public void setHttpAuthUsernamePassword(String host, String realm,
3534 String username,
3535 String password) {
3536 WebView w = mTabControl.getCurrentWebView();
3537 if (w != null) {
3538 w.setHttpAuthUsernamePassword(host, realm, username, password);
3539 }
3540 }
3541
3542 /**
3543 * connectivity manager says net has come or gone... inform the user
3544 * @param up true if net has come up, false if net has gone down
3545 */
3546 public void onNetworkToggle(boolean up) {
3547 if (up == mIsNetworkUp) {
3548 return;
3549 } else if (up) {
3550 mIsNetworkUp = true;
3551 if (mAlertDialog != null) {
3552 mAlertDialog.cancel();
3553 mAlertDialog = null;
3554 }
3555 } else {
3556 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003557 if (mInLoad) {
3558 createAndShowNetworkDialog();
3559 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003560 }
3561 WebView w = mTabControl.getCurrentWebView();
3562 if (w != null) {
3563 w.setNetworkAvailable(up);
3564 }
3565 }
3566
Grace Kloba22ac16e2009-10-07 18:00:23 -07003567 boolean isNetworkUp() {
3568 return mIsNetworkUp;
3569 }
3570
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003571 // This method shows the network dialog alerting the user that the net is
3572 // down. It will only show the dialog if mAlertDialog is null.
3573 private void createAndShowNetworkDialog() {
3574 if (mAlertDialog == null) {
3575 mAlertDialog = new AlertDialog.Builder(this)
3576 .setTitle(R.string.loadSuspendedTitle)
3577 .setMessage(R.string.loadSuspended)
3578 .setPositiveButton(R.string.ok, null)
3579 .show();
3580 }
3581 }
3582
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 @Override
3584 protected void onActivityResult(int requestCode, int resultCode,
3585 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003586 if (getTopWindow() == null) return;
3587
The Android Open Source Project0c908882009-03-03 19:32:16 -08003588 switch (requestCode) {
3589 case COMBO_PAGE:
3590 if (resultCode == RESULT_OK && intent != null) {
3591 String data = intent.getAction();
3592 Bundle extras = intent.getExtras();
3593 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003594 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003596 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003597 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003598 dismissSubWindow(currentTab);
3599 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003600 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 }
3602 }
3603 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003604 // Deliberately fall through to PREFERENCES_PAGE, since the
3605 // same extra may be attached to the COMBO_PAGE
3606 case PREFERENCES_PAGE:
3607 if (resultCode == RESULT_OK && intent != null) {
3608 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3609 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3610 mTabControl.removeParentChildRelationShips();
3611 }
3612 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003614 // Choose a file from the file picker.
3615 case FILE_SELECTED:
3616 if (null == mUploadMessage) break;
3617 Uri result = intent == null || resultCode != RESULT_OK ? null
3618 : intent.getData();
3619 mUploadMessage.onReceiveValue(result);
3620 mUploadMessage = null;
3621 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003622 default:
3623 break;
3624 }
Leon Scroggins30444232009-09-04 18:36:20 -04003625 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 }
3627
3628 /*
3629 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003630 * menu to see the download window. It shows the download window on top of
3631 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003632 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003633 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003634 Intent intent = new Intent(this,
3635 BrowserDownloadPage.class);
3636 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003637 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638
3639 }
3640
Leon Scroggins160a7e72009-08-14 18:28:01 -04003641 /**
3642 * Open the Go page.
3643 * @param startWithHistory If true, open starting on the history tab.
3644 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003645 */
Leon Scroggins30444232009-09-04 18:36:20 -04003646 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003647 WebView current = mTabControl.getCurrentWebView();
3648 if (current == null) {
3649 return;
3650 }
3651 Intent intent = new Intent(this,
3652 CombinedBookmarkHistoryActivity.class);
3653 String title = current.getTitle();
3654 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003655 Bitmap thumbnail = createScreenshot(current);
3656
The Android Open Source Project0c908882009-03-03 19:32:16 -08003657 // Just in case the user opens bookmarks before a page finishes loading
3658 // so the current history item, and therefore the page, is null.
3659 if (null == url) {
3660 url = mLastEnteredUrl;
3661 // This can happen.
3662 if (null == url) {
3663 url = mSettings.getHomePage();
3664 }
3665 }
3666 // In case the web page has not yet received its associated title.
3667 if (title == null) {
3668 title = url;
3669 }
3670 intent.putExtra("title", title);
3671 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003672 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003673 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003674 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003675 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003676 if (startWithHistory) {
3677 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3678 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3679 }
3680 startActivityForResult(intent, COMBO_PAGE);
3681 }
3682
3683 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003684 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 // In case the user enters nothing.
3686 if (url != null && url.length() != 0 && view != null) {
3687 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003688 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003689 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003690 }
3691 }
3692 }
3693
Leon Scroggins92472e82010-02-17 16:32:28 -05003694 /**
3695 * Load the URL into the given WebView and update the title bar
3696 * to reflect the new load. Call this instead of WebView.loadUrl
3697 * directly.
3698 * @param view The WebView used to load url.
3699 * @param url The URL to load.
3700 */
3701 private void loadUrl(WebView view, String url) {
3702 updateTitleBarForNewLoad(view, url);
3703 view.loadUrl(url);
3704 }
3705
3706 /**
3707 * Load UrlData into a Tab and update the title bar to reflect the new
3708 * load. Call this instead of UrlData.loadIn directly.
3709 * @param t The Tab used to load.
3710 * @param data The UrlData being loaded.
3711 */
3712 private void loadUrlDataIn(Tab t, UrlData data) {
3713 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3714 data.loadIn(t);
3715 }
3716
3717 /**
3718 * If the WebView is the top window, update the title bar to reflect
3719 * loading the new URL. i.e. set its text, clear the favicon (which
3720 * will be set once the page begins loading), and set the progress to
3721 * INITIAL_PROGRESS to show that the page has begun to load. Called
3722 * by loadUrl and loadUrlDataIn.
3723 * @param view The WebView that is starting a load.
3724 * @param url The URL that is being loaded.
3725 */
3726 private void updateTitleBarForNewLoad(WebView view, String url) {
3727 if (view == getTopWindow()) {
3728 setUrlTitle(url, null);
3729 setFavicon(null);
3730 onProgressChanged(view, INITIAL_PROGRESS);
3731 }
3732 }
3733
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 private String smartUrlFilter(Uri inUri) {
3735 if (inUri != null) {
3736 return smartUrlFilter(inUri.toString());
3737 }
3738 return null;
3739 }
3740
Feng Qianb34f87a2009-03-24 21:27:26 -07003741 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 "(?i)" + // switch on case insensitive matching
3743 "(" + // begin group for schema
3744 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003745 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 ")" +
3747 "(.*)" );
3748
3749 /**
3750 * Attempts to determine whether user input is a URL or search
3751 * terms. Anything with a space is passed to search.
3752 *
3753 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3754 * "Http://" converts to "http://"
3755 *
3756 * @return Original or modified URL
3757 *
3758 */
3759 String smartUrlFilter(String url) {
3760
3761 String inUrl = url.trim();
3762 boolean hasSpace = inUrl.indexOf(' ') != -1;
3763
3764 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3765 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003766 // force scheme to lowercase
3767 String scheme = matcher.group(1);
3768 String lcScheme = scheme.toLowerCase();
3769 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003770 inUrl = lcScheme + matcher.group(2);
3771 }
3772 if (hasSpace) {
3773 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003774 }
3775 return inUrl;
3776 }
3777 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003778 // FIXME: Is this the correct place to add to searches?
3779 // what if someone else calls this function?
3780 int shortcut = parseUrlShortcut(inUrl);
3781 if (shortcut != SHORTCUT_INVALID) {
3782 Browser.addSearchUrl(mResolver, inUrl);
3783 String query = inUrl.substring(2);
3784 switch (shortcut) {
3785 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003786 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003787 case SHORTCUT_WIKIPEDIA_SEARCH:
3788 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3789 case SHORTCUT_DICTIONARY_SEARCH:
3790 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3791 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003793 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794 }
3795 }
3796 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003797 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798 return URLUtil.guessUrl(inUrl);
3799 }
3800 }
3801
3802 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003803 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003804 }
3805
Ben Murdochbff2d602009-07-01 20:19:05 +01003806 /* package */ void setShouldShowErrorConsole(boolean flag) {
3807 if (flag == mShouldShowErrorConsole) {
3808 // Nothing to do.
3809 return;
3810 }
3811
3812 mShouldShowErrorConsole = flag;
3813
Grace Kloba22ac16e2009-10-07 18:00:23 -07003814 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3815 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003816
3817 if (flag) {
3818 // Setting the show state of the console will cause it's the layout to be inflated.
3819 if (errorConsole.numberOfErrors() > 0) {
3820 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3821 } else {
3822 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3823 }
3824
3825 // Now we can add it to the main view.
3826 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003827 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003828 ViewGroup.LayoutParams.WRAP_CONTENT));
3829 } else {
3830 mErrorConsoleContainer.removeView(errorConsole);
3831 }
3832
3833 }
3834
Grace Kloba22ac16e2009-10-07 18:00:23 -07003835 boolean shouldShowErrorConsole() {
3836 return mShouldShowErrorConsole;
3837 }
3838
Andrei Popescu163ab742009-10-20 17:58:23 +01003839 private void setStatusBarVisibility(boolean visible) {
3840 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3841 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3842 }
3843
Andrei Popescu56199cc2010-01-12 22:39:16 +00003844
3845 private void sendNetworkType(String type, String subtype) {
3846 WebView w = mTabControl.getCurrentWebView();
3847 if (w != null) {
3848 w.setNetworkType(type, subtype);
3849 }
3850 }
3851
Andrei Popescu30995e72010-02-09 16:59:58 +00003852 private void packageChanged(String packageName, boolean wasAdded) {
3853 WebView w = mTabControl.getCurrentWebView();
3854 if (w == null) {
3855 return;
3856 }
3857
3858 if (wasAdded) {
3859 w.addPackageName(packageName);
3860 } else {
3861 w.removePackageName(packageName);
3862 }
3863 }
3864
3865 private void addPackageNames(Set<String> packageNames) {
3866 WebView w = mTabControl.getCurrentWebView();
3867 if (w == null) {
3868 return;
3869 }
3870
3871 w.addPackageNames(packageNames);
3872 }
3873
3874 private void getInstalledPackages() {
3875 AsyncTask<Void, Void, Set<String> > task =
3876 new AsyncTask<Void, Void, Set<String> >() {
3877 protected Set<String> doInBackground(Void... unused) {
3878 Set<String> installedPackages = new HashSet<String>();
3879 PackageManager pm = BrowserActivity.this.getPackageManager();
3880 if (pm != null) {
3881 List<PackageInfo> packages = pm.getInstalledPackages(0);
3882 for (PackageInfo p : packages) {
3883 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3884 installedPackages.add(p.packageName);
3885 }
3886 }
3887 }
3888
3889 return installedPackages;
3890 }
3891
3892 // Executes on the UI thread
3893 protected void onPostExecute(Set<String> installedPackages) {
3894 addPackageNames(installedPackages);
3895 }
3896 };
3897 task.execute();
3898 }
3899
Grace Klobaeb6eef42009-09-15 17:56:32 -07003900 final static int LOCK_ICON_UNSECURE = 0;
3901 final static int LOCK_ICON_SECURE = 1;
3902 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003903
The Android Open Source Project0c908882009-03-03 19:32:16 -08003904 private BrowserSettings mSettings;
3905 private TabControl mTabControl;
3906 private ContentResolver mResolver;
3907 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003908 private View mCustomView;
3909 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003910 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003911
3912 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3913 // view, we should rewrite this.
3914 private int mCurrentMenuState = 0;
3915 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003916 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003917 private static final int EMPTY_MENU = -1;
3918 private Menu mMenu;
3919
3920 private FindDialog mFindDialog;
3921 // Used to prevent chording to result in firing two shortcuts immediately
3922 // one after another. Fixes bug 1211714.
3923 boolean mCanChord;
3924
3925 private boolean mInLoad;
3926 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003927 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003928
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929 private boolean mActivityInPause = true;
3930
3931 private boolean mMenuIsDown;
3932
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 private static boolean mInTrace;
3934
3935 // Performance probe
3936 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3937 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3938 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3939 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3940 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3941 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3942 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3943 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3944 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3945 };
3946
3947 private long mStart;
3948 private long mProcessStart;
3949 private long mUserStart;
3950 private long mSystemStart;
3951 private long mIdleStart;
3952 private long mIrqStart;
3953
3954 private long mUiStart;
3955
3956 private Drawable mMixLockIcon;
3957 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003958
3959 /* hold a ref so we can auto-cancel if necessary */
3960 private AlertDialog mAlertDialog;
3961
3962 // Wait for credentials before loading google.com
3963 private ProgressDialog mCredsDlg;
3964
3965 // The up-to-date URL and title (these can be different from those stored
3966 // in WebView, since it takes some time for the information in WebView to
3967 // get updated)
3968 private String mUrl;
3969 private String mTitle;
3970
3971 // As PageInfo has different style for landscape / portrait, we have
3972 // to re-open it when configuration changed
3973 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003974 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3976 // dialog, we should not just dismiss it, but should get back to the
3977 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003978 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003979
3980 // as SSLCertificateOnError has different style for landscape / portrait,
3981 // we have to re-open it when configuration changed
3982 private AlertDialog mSSLCertificateOnErrorDialog;
3983 private WebView mSSLCertificateOnErrorView;
3984 private SslErrorHandler mSSLCertificateOnErrorHandler;
3985 private SslError mSSLCertificateOnErrorError;
3986
3987 // as SSLCertificate has different style for landscape / portrait, we
3988 // have to re-open it when configuration changed
3989 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003990 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991
3992 // as HttpAuthentication has different style for landscape / portrait, we
3993 // have to re-open it when configuration changed
3994 private AlertDialog mHttpAuthenticationDialog;
3995 private HttpAuthHandler mHttpAuthHandler;
3996
3997 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3998 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003999 ViewGroup.LayoutParams.MATCH_PARENT,
4000 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004001 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4002 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004003 ViewGroup.LayoutParams.MATCH_PARENT,
4004 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004005 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004006 // Google search
4007 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004008 // Wikipedia search
4009 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4010 // Dictionary search
4011 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4012 // Google Mobile Local search
4013 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4014
4015 final static String QUERY_PLACE_HOLDER = "%s";
4016
4017 // "source" parameter for Google search through search key
4018 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4019 // "source" parameter for Google search through goto menu
4020 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4021 // "source" parameter for Google search through simplily type
4022 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4023 // "source" parameter for Google search suggested by the browser
4024 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4025 // "source" parameter for Google search from unknown source
4026 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4027
4028 private final static String LOGTAG = "browser";
4029
The Android Open Source Project0c908882009-03-03 19:32:16 -08004030 private String mLastEnteredUrl;
4031
4032 private PowerManager.WakeLock mWakeLock;
4033 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4034
4035 private Toast mStopToast;
4036
Leon Scroggins68579392009-09-15 15:31:54 -04004037 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004038
Ben Murdochbff2d602009-07-01 20:19:05 +01004039 private LinearLayout mErrorConsoleContainer = null;
4040 private boolean mShouldShowErrorConsole = false;
4041
The Android Open Source Project0c908882009-03-03 19:32:16 -08004042 // As the ids are dynamically created, we can't guarantee that they will
4043 // be in sequence, so this static array maps ids to a window number.
4044 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4045 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4046 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4047 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4048
4049 // monitor platform changes
4050 private IntentFilter mNetworkStateChangedFilter;
4051 private BroadcastReceiver mNetworkStateIntentReceiver;
4052
Grace Klobab4da0ad2009-05-14 14:45:40 -07004053 private BroadcastReceiver mPackageInstallationReceiver;
4054
The Android Open Source Project0c908882009-03-03 19:32:16 -08004055 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004056 final static int COMBO_PAGE = 1;
4057 final static int DOWNLOAD_PAGE = 2;
4058 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004059 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004060
Andrei Popescu540035d2009-09-18 18:59:20 +01004061 // the default <video> poster
4062 private Bitmap mDefaultVideoPoster;
4063 // the video progress view
4064 private View mVideoProgressView;
4065
Andrei Popescu30995e72010-02-09 16:59:58 +00004066 // The Google packages we monitor for the navigator.isApplicationInstalled()
4067 // API. Add as needed.
4068 private static Set<String> sGoogleApps;
4069 static {
4070 sGoogleApps = new HashSet<String>();
4071 sGoogleApps.add("com.google.android.youtube");
4072 }
4073
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004074 /**
4075 * A UrlData class to abstract how the content will be set to WebView.
4076 * This base class uses loadUrl to show the content.
4077 */
4078 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004079 final String mUrl;
4080 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004081 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004082
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004083 UrlData(String url) {
4084 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004085 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004086 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004087 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004088
Leon Scroggins58d56c62010-01-28 15:12:40 -05004089 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004090 this.mUrl = url;
4091 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004092 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4093 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004094 this.mVoiceIntent = intent;
4095 } else {
4096 this.mVoiceIntent = null;
4097 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004098 }
4099
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004100 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004101 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004102 }
4103
Leon Scroggins92472e82010-02-17 16:32:28 -05004104 /**
4105 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4106 * the title bar as well.
4107 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004108 public void loadIn(Tab t) {
4109 if (mVoiceIntent != null) {
4110 t.activateVoiceSearchMode(mVoiceIntent);
4111 } else {
4112 t.getWebView().loadUrl(mUrl, mHeaders);
4113 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004114 }
4115 };
4116
Leon Scroggins1f005d32009-08-10 17:36:42 -04004117 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004118}