blob: 1903713bc3e02552c5c793a645fd9139e935bf29 [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
Patrick Scott6adacc92010-03-05 08:24:51 -0500309 // Find out if the network is currently up.
310 ConnectivityManager cm = (ConnectivityManager) getSystemService(
311 Context.CONNECTIVITY_SERVICE);
312 NetworkInfo info = cm.getActiveNetworkInfo();
313 if (info != null) {
314 mIsNetworkUp = info.isAvailable();
315 }
316
Grace Klobaa34f6862009-07-31 16:28:17 -0700317 /* enables registration for changes in network status from
318 http stack */
319 mNetworkStateChangedFilter = new IntentFilter();
320 mNetworkStateChangedFilter.addAction(
321 ConnectivityManager.CONNECTIVITY_ACTION);
322 mNetworkStateIntentReceiver = new BroadcastReceiver() {
323 @Override
324 public void onReceive(Context context, Intent intent) {
325 if (intent.getAction().equals(
326 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000327
328 NetworkInfo info = intent.getParcelableExtra(
329 ConnectivityManager.EXTRA_NETWORK_INFO);
330 String typeName = info.getTypeName();
331 String subtypeName = info.getSubtypeName();
332 sendNetworkType(typeName.toLowerCase(),
333 (subtypeName != null ? subtypeName.toLowerCase() : ""));
334
335 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700336 }
337 }
338 };
339
Grace Kloba615c6c92009-08-03 10:22:44 -0700340 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
341 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
342 filter.addDataScheme("package");
343 mPackageInstallationReceiver = new BroadcastReceiver() {
344 @Override
345 public void onReceive(Context context, Intent intent) {
346 final String action = intent.getAction();
347 final String packageName = intent.getData()
348 .getSchemeSpecificPart();
349 final boolean replacing = intent.getBooleanExtra(
350 Intent.EXTRA_REPLACING, false);
351 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
352 // if it is replacing, refreshPlugins() when adding
353 return;
354 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000355
356 if (sGoogleApps.contains(packageName)) {
357 BrowserActivity.this.packageChanged(packageName,
358 Intent.ACTION_PACKAGE_ADDED.equals(action));
359 }
360
Grace Kloba615c6c92009-08-03 10:22:44 -0700361 PackageManager pm = BrowserActivity.this.getPackageManager();
362 PackageInfo pkgInfo = null;
363 try {
364 pkgInfo = pm.getPackageInfo(packageName,
365 PackageManager.GET_PERMISSIONS);
366 } catch (PackageManager.NameNotFoundException e) {
367 return;
368 }
369 if (pkgInfo != null) {
370 String permissions[] = pkgInfo.requestedPermissions;
371 if (permissions == null) {
372 return;
373 }
374 boolean permissionOk = false;
375 for (String permit : permissions) {
376 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
377 permissionOk = true;
378 break;
379 }
380 }
381 if (permissionOk) {
382 PluginManager.getInstance(BrowserActivity.this)
383 .refreshPlugins(
384 Intent.ACTION_PACKAGE_ADDED
385 .equals(action));
386 }
387 }
388 }
389 };
390 registerReceiver(mPackageInstallationReceiver, filter);
391
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 if (!mTabControl.restoreState(icicle)) {
393 // clear up the thumbnail directory if we can't restore the state as
394 // none of the files in the directory are referenced any more.
395 new ClearThumbnails().execute(
396 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700397 // there is no quit on Android. But if we can't restore the state,
398 // we can treat it as a new Browser, remove the old session cookies.
399 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800400 final Intent intent = getIntent();
401 final Bundle extra = intent.getExtras();
402 // Create an initial tab.
403 // If the intent is ACTION_VIEW and data is not null, the Browser is
404 // invoked to view the content by another application. In this case,
405 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700406 UrlData urlData = getUrlDataFromIntent(intent);
407
Leon Scroggins58d56c62010-01-28 15:12:40 -0500408 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700409 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500410 (Intent.ACTION_VIEW.equals(action) &&
411 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500412 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
413 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700414 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800415 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 attachTabToContentView(t);
417 WebView webView = t.getWebView();
418 if (extra != null) {
419 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
420 if (scale > 0 && scale <= 1000) {
421 webView.setInitialScale(scale);
422 }
423 }
424 // If we are not restoring from an icicle, then there is a high
425 // likely hood this is the first run. So, check to see if the
426 // homepage needs to be configured and copy any plugins from our
427 // asset directory to the data partition.
428 if ((extra == null || !extra.getBoolean("testing"))
429 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800430 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800431 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700433 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400434 if (mSettings.isLoginInitialized()) {
Leon Scroggins92472e82010-02-17 16:32:28 -0500435 loadUrl(webView, mSettings.getHomePage());
Leon Scroggins30444232009-09-04 18:36:20 -0400436 } else {
437 waitForCredentials();
438 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800439 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500440 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800441 }
442 } else {
443 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400444 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800445 attachTabToContentView(mTabControl.getCurrentTab());
446 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700447
Feng Qianb3c02da2009-06-29 15:58:08 -0700448 // Read JavaScript flags if it exists.
449 String jsFlags = mSettings.getJsFlags();
450 if (jsFlags.trim().length() != 0) {
451 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
452 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000453 // Work out which packages are installed on the system.
454 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800455 }
456
Leon Scroggins58d56c62010-01-28 15:12:40 -0500457 /**
458 * Feed the previously stored results strings to the BrowserProvider so that
459 * the SearchDialog will show them instead of the standard searches.
460 * @param result String to show on the editable line of the SearchDialog.
461 */
462 /* package */ void showVoiceSearchResults(String result) {
463 ContentProviderClient client = mResolver.acquireContentProviderClient(
464 Browser.BOOKMARKS_URI);
465 ContentProvider prov = client.getLocalContentProvider();
466 BrowserProvider bp = (BrowserProvider) prov;
467 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
468 client.release();
469
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500470 Bundle bundle = createGoogleSearchSourceBundle(
471 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
472 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
473 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500474 }
475
The Android Open Source Project0c908882009-03-03 19:32:16 -0800476 @Override
477 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700478 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800479 // When a tab is closed on exit, the current tab index is set to -1.
480 // Reset before proceed as Browser requires the current tab to be set.
481 if (current == null) {
482 // Try to reset the tab in case the index was incorrect.
483 current = mTabControl.getTab(0);
484 if (current == null) {
485 // No tabs at all so just ignore this intent.
486 return;
487 }
488 mTabControl.setCurrentTab(current);
489 attachTabToContentView(current);
490 resetTitleAndIcon(current.getWebView());
491 }
492 final String action = intent.getAction();
493 final int flags = intent.getFlags();
494 if (Intent.ACTION_MAIN.equals(action) ||
495 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
496 // just resume the browser
497 return;
498 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500499 boolean activateVoiceSearch = RecognizerResultsIntent
500 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800501 if (Intent.ACTION_VIEW.equals(action)
502 || Intent.ACTION_SEARCH.equals(action)
503 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500504 || Intent.ACTION_WEB_SEARCH.equals(action)
505 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500506 if (current.isInVoiceSearchMode()) {
507 String title = current.getVoiceDisplayTitle();
508 if (title != null && title.equals(intent.getStringExtra(
509 SearchManager.QUERY))) {
510 // The user submitted the same search as the last voice
511 // search, so do nothing.
512 return;
513 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500514 if (Intent.ACTION_SEARCH.equals(action)
515 && current.voiceSearchSourceIsGoogle()) {
516 Intent logIntent = new Intent(
517 LoggingEvents.ACTION_LOG_EVENT);
518 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
519 LoggingEvents.VoiceSearch.QUERY_UPDATED);
520 logIntent.putExtra(
521 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
522 intent.getDataString());
523 sendBroadcast(logIntent);
524 // Note, onPageStarted will revert the voice title bar
525 // When http://b/issue?id=2379215 is fixed, we should update
526 // the title bar here.
527 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500528 }
Satish Sampath565505b2009-05-29 15:37:27 +0100529 // If this was a search request (e.g. search query directly typed into the address bar),
530 // pass it on to the default web search provider.
531 if (handleWebSearchIntent(intent)) {
532 return;
533 }
534
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700535 UrlData urlData = getUrlDataFromIntent(intent);
536 if (urlData.isEmpty()) {
537 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800538 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700539
Grace Klobacc634032009-07-28 15:58:19 -0700540 final String appId = intent
541 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500542 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700543 && !getPackageName().equals(appId)
544 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700545 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700546 if (appTab != null) {
547 Log.i(LOGTAG, "Reusing tab for " + appId);
548 // Dismiss the subwindow if applicable.
549 dismissSubWindow(appTab);
550 // Since we might kill the WebView, remove it from the
551 // content view first.
552 removeTabFromContentView(appTab);
553 // Recreate the main WebView after destroying the old one.
554 // If the WebView has the same original url and is on that
555 // page, it can be reused.
556 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700557 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100558
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700559 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400560 switchToTab(mTabControl.getTabIndex(appTab));
561 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500562 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400563 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700564 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400565 // If the tab was the current tab, we have to attach
566 // it to the view system again.
567 attachTabToContentView(appTab);
568 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500569 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700570 }
571 }
572 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400573 } else {
574 // No matching application tab, try to find a regular tab
575 // with a matching url.
576 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400577 if (appTab != null) {
578 if (current != appTab) {
579 switchToTab(mTabControl.getTabIndex(appTab));
580 }
581 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400582 } else {
583 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
584 // will be opened in a new tab unless we have reached
585 // MAX_TABS. Then the url will be opened in the current
586 // tab. If a new tab is created, it will have "true" for
587 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400588 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400589 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700590 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800591 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800592 if (!urlData.isEmpty()
593 && urlData.mUrl.startsWith("about:debug")) {
594 if ("about:debug.dom".equals(urlData.mUrl)) {
595 current.getWebView().dumpDomTree(false);
596 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
597 current.getWebView().dumpDomTree(true);
598 } else if ("about:debug.render".equals(urlData.mUrl)) {
599 current.getWebView().dumpRenderTree(false);
600 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
601 current.getWebView().dumpRenderTree(true);
602 } else if ("about:debug.display".equals(urlData.mUrl)) {
603 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800604 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
605 int index = urlData.mUrl.codePointAt(16) - '0';
606 if (index <= 0 || index > 9) {
607 current.getWebView().setDragTracker(null);
608 } else {
609 current.getWebView().setDragTracker(new MeshTracker(index));
610 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800611 } else {
612 mSettings.toggleDebugSettings();
613 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800614 return;
615 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400616 // Get rid of the subwindow if it exists
617 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500618 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800619 }
620 }
621 }
622
Satish Sampath565505b2009-05-29 15:37:27 +0100623 private int parseUrlShortcut(String url) {
624 if (url == null) return SHORTCUT_INVALID;
625
626 // FIXME: quick search, need to be customized by setting
627 if (url.length() > 2 && url.charAt(1) == ' ') {
628 switch (url.charAt(0)) {
629 case 'g': return SHORTCUT_GOOGLE_SEARCH;
630 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
631 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
632 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
633 }
634 }
635 return SHORTCUT_INVALID;
636 }
637
638 /**
639 * Launches the default web search activity with the query parameters if the given intent's data
640 * are identified as plain search terms and not URLs/shortcuts.
641 * @return true if the intent was handled and web search activity was launched, false if not.
642 */
643 private boolean handleWebSearchIntent(Intent intent) {
644 if (intent == null) return false;
645
646 String url = null;
647 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500648 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
649 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500650 return false;
651 }
Satish Sampath565505b2009-05-29 15:37:27 +0100652 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700653 Uri data = intent.getData();
654 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100655 } else if (Intent.ACTION_SEARCH.equals(action)
656 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
657 || Intent.ACTION_WEB_SEARCH.equals(action)) {
658 url = intent.getStringExtra(SearchManager.QUERY);
659 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100660 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
661 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100662 }
663
664 /**
665 * Launches the default web search activity with the query parameters if the given url string
666 * was identified as plain search terms and not URL/shortcut.
667 * @return true if the request was handled and web search activity was launched, false if not.
668 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100669 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100670 if (inUrl == null) return false;
671
672 // In general, we shouldn't modify URL from Intent.
673 // But currently, we get the user-typed URL from search box as well.
674 String url = fixUrl(inUrl).trim();
675
676 // URLs and site specific search shortcuts are handled by the regular flow of control, so
677 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800678 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100679 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100680 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
681 return false;
682 }
683
684 Browser.updateVisitedHistory(mResolver, url, false);
685 Browser.addSearchUrl(mResolver, url);
686
687 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
688 intent.addCategory(Intent.CATEGORY_DEFAULT);
689 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100690 if (appData != null) {
691 intent.putExtra(SearchManager.APP_DATA, appData);
692 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100693 if (extraData != null) {
694 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
695 }
Grace Klobacc634032009-07-28 15:58:19 -0700696 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100697 startActivity(intent);
698
699 return true;
700 }
701
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700702 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500703 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800704 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 if (intent != null) {
706 final String action = intent.getAction();
707 if (Intent.ACTION_VIEW.equals(action)) {
708 url = smartUrlFilter(intent.getData());
709 if (url != null && url.startsWith("content:")) {
710 /* Append mimetype so webview knows how to display */
711 String mimeType = intent.resolveType(getContentResolver());
712 if (mimeType != null) {
713 url += "?" + mimeType;
714 }
715 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800716 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800717 final Bundle pairs = intent
718 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800719 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800720 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800721 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800722 while (iter.hasNext()) {
723 String key = iter.next();
724 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800725 }
726 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700727 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800728 } else if (Intent.ACTION_SEARCH.equals(action)
729 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
730 || Intent.ACTION_WEB_SEARCH.equals(action)) {
731 url = intent.getStringExtra(SearchManager.QUERY);
732 if (url != null) {
733 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800734 // In general, we shouldn't modify URL from Intent.
735 // But currently, we get the user-typed URL from search box as well.
736 url = fixUrl(url);
737 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500738 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
740 if (url.contains(searchSource)) {
741 String source = null;
742 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
743 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000744 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800745 }
746 if (TextUtils.isEmpty(source)) {
747 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
748 }
749 url = url.replace(searchSource, "&source=android-"+source+"&");
750 }
751 }
752 }
753 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500754 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800755 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500756 /* package */ void showVoiceTitleBar(String title) {
757 mTitleBar.setInVoiceMode(true);
758 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759
Leon Scroggins58d56c62010-01-28 15:12:40 -0500760 mTitleBar.setDisplayTitle(title);
761 mFakeTitleBar.setDisplayTitle(title);
762 }
763 /* package */ void revertVoiceTitleBar() {
764 mTitleBar.setInVoiceMode(false);
765 mFakeTitleBar.setInVoiceMode(false);
766
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500767 mTitleBar.setDisplayTitle(mUrl);
768 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500769 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800770 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400771 // FIXME: Converting the url to lower case
772 // duplicates functionality in smartUrlFilter().
773 // However, changing all current callers of fixUrl to
774 // call smartUrlFilter in addition may have unwanted
775 // consequences, and is deferred for now.
776 int colon = inUrl.indexOf(':');
777 boolean allLower = true;
778 for (int index = 0; index < colon; index++) {
779 char ch = inUrl.charAt(index);
780 if (!Character.isLetter(ch)) {
781 break;
782 }
783 allLower &= Character.isLowerCase(ch);
784 if (index == colon - 1 && !allLower) {
785 inUrl = inUrl.substring(0, colon).toLowerCase()
786 + inUrl.substring(colon);
787 }
788 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800789 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
790 return inUrl;
791 if (inUrl.startsWith("http:") ||
792 inUrl.startsWith("https:")) {
793 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
794 inUrl = inUrl.replaceFirst("/", "//");
795 } else inUrl = inUrl.replaceFirst(":", "://");
796 }
797 return inUrl;
798 }
799
Grace Kloba22ac16e2009-10-07 18:00:23 -0700800 @Override
801 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800802 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700803 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800804 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
805 }
806
807 if (!mActivityInPause) {
808 Log.e(LOGTAG, "BrowserActivity is already resumed.");
809 return;
810 }
811
Mike Reed7bfa63b2009-05-28 11:08:32 -0400812 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800813 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400814 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800815
816 if (mWakeLock.isHeld()) {
817 mHandler.removeMessages(RELEASE_WAKELOCK);
818 mWakeLock.release();
819 }
820
821 if (mCredsDlg != null) {
822 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
823 // In case credential request never comes back
824 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
825 }
826 }
827
828 registerReceiver(mNetworkStateIntentReceiver,
829 mNetworkStateChangedFilter);
830 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800831 }
832
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833 /**
834 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400835 * would change its appearance, use a different TitleBar to show overlayed
836 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400837 */
838 private TitleBar mFakeTitleBar;
839
840 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400841 * Holder for the fake title bar. It will have a foreground shadow, as well
842 * as a white background, so the fake title bar looks like the real one.
843 */
844 private ViewGroup mFakeTitleBarHolder;
845
846 /**
847 * Layout parameters for the fake title bar within mFakeTitleBarHolder
848 */
849 private FrameLayout.LayoutParams mFakeTitleBarParams
850 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800851 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400852 ViewGroup.LayoutParams.WRAP_CONTENT);
853 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400854 * Keeps track of whether the options menu is open. This is important in
855 * determining whether to show or hide the title bar overlay.
856 */
857 private boolean mOptionsMenuOpen;
858
859 /**
860 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
861 * of whether the configuration has changed. The first onMenuOpened call
862 * after a configuration change is simply a reopening of the same menu
863 * (i.e. mIconView did not change).
864 */
865 private boolean mConfigChanged;
866
867 /**
868 * Whether or not the options menu is in its smaller, icon menu form. When
869 * true, we want the title bar overlay to be up. When false, we do not.
870 * Only meaningful if mOptionsMenuOpen is true.
871 */
872 private boolean mIconView;
873
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400874 @Override
875 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400876 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
877 if (mOptionsMenuOpen) {
878 if (mConfigChanged) {
879 // We do not need to make any changes to the state of the
880 // title bar, since the only thing that happened was a
881 // change in orientation
882 mConfigChanged = false;
883 } else {
884 if (mIconView) {
885 // Switching the menu to expanded view, so hide the
886 // title bar.
887 hideFakeTitleBar();
888 mIconView = false;
889 } else {
890 // Switching the menu back to icon view, so show the
891 // title bar once again.
892 showFakeTitleBar();
893 mIconView = true;
894 }
895 }
896 } else {
897 // The options menu is closed, so open it, and show the title
898 showFakeTitleBar();
899 mOptionsMenuOpen = true;
900 mConfigChanged = false;
901 mIconView = true;
902 }
903 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400904 return true;
905 }
906
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400907 /**
908 * Special class used exclusively for the shadow drawn underneath the fake
909 * title bar. The shadow does not need to be drawn if the WebView
910 * underneath is scrolled to the top, because it will draw directly on top
911 * of the embedded shadow.
912 */
913 private static class Shadow extends View {
914 private WebView mWebView;
915
916 public Shadow(Context context, AttributeSet attrs) {
917 super(context, attrs);
918 }
919
920 public void setWebView(WebView view) {
921 mWebView = view;
922 }
923
924 @Override
925 public void draw(Canvas canvas) {
926 // In general onDraw is the method to override, but we care about
927 // whether or not the background gets drawn, which happens in draw()
928 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
929 super.draw(canvas);
930 }
931 // Need to invalidate so that if the scroll position changes, we
932 // still draw as appropriate.
933 invalidate();
934 }
935 }
936
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400937 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400938 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400939 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400940 && !mActivityInPause && decor != null
941 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400942 Rect visRect = new Rect();
943 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
944 if (LOGD_ENABLED) {
945 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
946 }
947 return;
948 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400949
950 WindowManager manager
951 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
952
953 // Add the title bar to the window manager so it can receive touches
954 // while the menu is up
955 WindowManager.LayoutParams params
956 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800957 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400958 ViewGroup.LayoutParams.WRAP_CONTENT,
959 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
960 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400961 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400962 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400963 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400964 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400965 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400966 // XXX : Without providing an offset, the fake title bar will be
967 // placed underneath the status bar. Use the global visible rect
968 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400969 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400970 // Add a holder for the title bar. It also holds a shadow to show
971 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400972 if (mFakeTitleBarHolder == null) {
973 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
974 .inflate(R.layout.title_bar_bg, null);
975 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400976 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
977 R.id.shadow);
978 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400979 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400980 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400981 }
982 }
983
984 @Override
985 public void onOptionsMenuClosed(Menu menu) {
986 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400987 if (!mInLoad) {
988 hideFakeTitleBar();
989 } else if (!mIconView) {
990 // The page is currently loading, and we are in expanded mode, so
991 // we were not showing the menu. Show it once again. It will be
992 // removed when the page finishes.
993 showFakeTitleBar();
994 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400995 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700996
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400997 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400998 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400999 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1000 mFakeTitleBarHolder.getLayoutParams();
1001 WebView mainView = mTabControl.getCurrentWebView();
1002 // Although we decided whether or not to animate based on the current
1003 // scroll position, the scroll position may have changed since the
1004 // fake title bar was displayed. Make sure it has the appropriate
1005 // animation/lack thereof before removing.
1006 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001007 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001008 WindowManager manager
1009 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001010 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001011 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1012 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001013 }
1014
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001016 * Special method for the fake title bar to call when displaying its context
1017 * menu, since it is in its own Window, and its parent does not show a
1018 * context menu.
1019 */
1020 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001021 if (null == mTitleBar.getParent()) {
1022 return;
1023 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001024 openContextMenu(mTitleBar);
1025 }
1026
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001027 @Override
1028 public void onContextMenuClosed(Menu menu) {
1029 super.onContextMenuClosed(menu);
1030 if (mInLoad) {
1031 showFakeTitleBar();
1032 }
1033 }
1034
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001035 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 * onSaveInstanceState(Bundle map)
1037 * onSaveInstanceState is called right before onStop(). The map contains
1038 * the saved state.
1039 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001040 @Override
1041 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001042 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001043 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1044 }
1045 // the default implementation requires each view to have an id. As the
1046 // browser handles the state itself and it doesn't use id for the views,
1047 // don't call the default implementation. Otherwise it will trigger the
1048 // warning like this, "couldn't save which view has focus because the
1049 // focused view XXX has no id".
1050
1051 // Save all the tabs
1052 mTabControl.saveState(outState);
1053 }
1054
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 @Override
1056 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001057 super.onPause();
1058
1059 if (mActivityInPause) {
1060 Log.e(LOGTAG, "BrowserActivity is already paused.");
1061 return;
1062 }
1063
Mike Reed7bfa63b2009-05-28 11:08:32 -04001064 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001066 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 mWakeLock.acquire();
1068 mHandler.sendMessageDelayed(mHandler
1069 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1070 }
1071
1072 // Clear the credentials toast if it is up
1073 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1074 mCredsDlg.dismiss();
1075 }
1076 mCredsDlg = null;
1077
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001078 // FIXME: This removes the active tabs page and resets the menu to
1079 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1080 // but then we would need to save it in onSaveInstanceState and restore
1081 // it in onCreate/onRestoreInstanceState
1082 if (mActiveTabsPage != null) {
1083 removeActiveTabPage(true);
1084 }
1085
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 cancelStopToast();
1087
1088 // unregister network state listener
1089 unregisterReceiver(mNetworkStateIntentReceiver);
1090 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001091 }
1092
Grace Kloba22ac16e2009-10-07 18:00:23 -07001093 @Override
1094 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001095 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001096 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1097 }
1098 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001099
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001100 if (mUploadMessage != null) {
1101 mUploadMessage.onReceiveValue(null);
1102 mUploadMessage = null;
1103 }
1104
Grace Kloba0923d692009-09-23 21:37:25 -07001105 if (mTabControl == null) return;
1106
Grace Kloba1fc98a32009-10-21 13:23:08 -07001107 // Remove the fake title bar if it is there
1108 hideFakeTitleBar();
1109
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001111 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001112 if (t != null) {
1113 dismissSubWindow(t);
1114 removeTabFromContentView(t);
1115 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001116 // Destroy all the tabs
1117 mTabControl.destroy();
1118 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001119
Grace Klobab4da0ad2009-05-14 14:45:40 -07001120 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001121 }
1122
1123 @Override
1124 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001125 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 super.onConfigurationChanged(newConfig);
1127
1128 if (mPageInfoDialog != null) {
1129 mPageInfoDialog.dismiss();
1130 showPageInfo(
1131 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001132 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001133 }
1134 if (mSSLCertificateDialog != null) {
1135 mSSLCertificateDialog.dismiss();
1136 showSSLCertificate(
1137 mSSLCertificateView);
1138 }
1139 if (mSSLCertificateOnErrorDialog != null) {
1140 mSSLCertificateOnErrorDialog.dismiss();
1141 showSSLCertificateOnError(
1142 mSSLCertificateOnErrorView,
1143 mSSLCertificateOnErrorHandler,
1144 mSSLCertificateOnErrorError);
1145 }
1146 if (mHttpAuthenticationDialog != null) {
1147 String title = ((TextView) mHttpAuthenticationDialog
1148 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1149 .toString();
1150 String name = ((TextView) mHttpAuthenticationDialog
1151 .findViewById(R.id.username_edit)).getText().toString();
1152 String password = ((TextView) mHttpAuthenticationDialog
1153 .findViewById(R.id.password_edit)).getText().toString();
1154 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1155 .getId();
1156 mHttpAuthenticationDialog.dismiss();
1157 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1158 name, password, focusId);
1159 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001160 }
1161
Grace Kloba22ac16e2009-10-07 18:00:23 -07001162 @Override
1163 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001164 super.onLowMemory();
1165 mTabControl.freeMemory();
1166 }
1167
Mike Reed7bfa63b2009-05-28 11:08:32 -04001168 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001169 Tab tab = mTabControl.getCurrentTab();
1170 boolean inLoad = tab.inLoad();
1171 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001172 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001173 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001174 if (w != null) {
1175 w.resumeTimers();
1176 }
1177 return true;
1178 } else {
1179 return false;
1180 }
1181 }
1182
Mike Reed7bfa63b2009-05-28 11:08:32 -04001183 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001184 Tab tab = mTabControl.getCurrentTab();
1185 boolean inLoad = tab.inLoad();
1186 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001187 CookieSyncManager.getInstance().stopSync();
1188 WebView w = mTabControl.getCurrentWebView();
1189 if (w != null) {
1190 w.pauseTimers();
1191 }
1192 return true;
1193 } else {
1194 return false;
1195 }
1196 }
1197
Leon Scroggins1f005d32009-08-10 17:36:42 -04001198 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001199 /*
1200 * This function is called when we are launching for the first time. We
1201 * are waiting for the login credentials before loading Google home
1202 * pages. This way the user will be logged in straight away.
1203 */
1204 private void waitForCredentials() {
1205 // Show a toast
1206 mCredsDlg = new ProgressDialog(this);
1207 mCredsDlg.setIndeterminate(true);
1208 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1209 // If the user cancels the operation, then cancel the Google
1210 // Credentials request.
1211 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1212 mCredsDlg.show();
1213
1214 // We set a timeout for the retrieval of credentials in onResume()
1215 // as that is when we have freed up some CPU time to get
1216 // the login credentials.
1217 }
1218
1219 /*
1220 * If we have received the credentials or we have timed out and we are
1221 * showing the credentials dialog, then it is time to move on.
1222 */
1223 private void resumeAfterCredentials() {
1224 if (mCredsDlg == null) {
1225 return;
1226 }
1227
1228 // Clear the toast
1229 if (mCredsDlg.isShowing()) {
1230 mCredsDlg.dismiss();
1231 }
1232 mCredsDlg = null;
1233
1234 // Clear any pending timeout
1235 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1236
1237 // Load the page
1238 WebView w = mTabControl.getCurrentWebView();
1239 if (w != null) {
Leon Scroggins92472e82010-02-17 16:32:28 -05001240 loadUrl(w, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001241 }
1242
1243 // Update the settings, need to do this last as it can take a moment
1244 // to persist the settings. In the mean time we could be loading
1245 // content.
1246 mSettings.setLoginInitialized(this);
1247 }
1248
1249 // Open the icon database and retain all the icons for visited sites.
1250 private void retainIconsOnStartup() {
1251 final WebIconDatabase db = WebIconDatabase.getInstance();
1252 db.open(getDir("icons", 0).getPath());
1253 try {
1254 Cursor c = Browser.getAllBookmarks(mResolver);
1255 if (!c.moveToFirst()) {
1256 c.deactivate();
1257 return;
1258 }
1259 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1260 do {
1261 String url = c.getString(urlIndex);
1262 db.retainIconForPageUrl(url);
1263 } while (c.moveToNext());
1264 c.deactivate();
1265 } catch (IllegalStateException e) {
1266 Log.e(LOGTAG, "retainIconsOnStartup", e);
1267 }
1268 }
1269
1270 // Helper method for getting the top window.
1271 WebView getTopWindow() {
1272 return mTabControl.getCurrentTopWebView();
1273 }
1274
Grace Kloba22ac16e2009-10-07 18:00:23 -07001275 TabControl getTabControl() {
1276 return mTabControl;
1277 }
1278
The Android Open Source Project0c908882009-03-03 19:32:16 -08001279 @Override
1280 public boolean onCreateOptionsMenu(Menu menu) {
1281 super.onCreateOptionsMenu(menu);
1282
1283 MenuInflater inflater = getMenuInflater();
1284 inflater.inflate(R.menu.browser, menu);
1285 mMenu = menu;
1286 updateInLoadMenuItems();
1287 return true;
1288 }
1289
1290 /**
1291 * As the menu can be open when loading state changes
1292 * we must manually update the state of the stop/reload menu
1293 * item
1294 */
1295 private void updateInLoadMenuItems() {
1296 if (mMenu == null) {
1297 return;
1298 }
1299 MenuItem src = mInLoad ?
1300 mMenu.findItem(R.id.stop_menu_id):
1301 mMenu.findItem(R.id.reload_menu_id);
1302 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1303 dest.setIcon(src.getIcon());
1304 dest.setTitle(src.getTitle());
1305 }
1306
1307 @Override
1308 public boolean onContextItemSelected(MenuItem item) {
1309 // chording is not an issue with context menus, but we use the same
1310 // options selector, so set mCanChord to true so we can access them.
1311 mCanChord = true;
1312 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001313 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001315 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001316 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001317 Tab currentTab = mTabControl.getCurrentTab();
1318 if (null == currentTab) {
1319 result = false;
1320 break;
1321 }
1322 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001323 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001324 result = false;
1325 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001326 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001327 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001328 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001329 // -- Browser context menu
1330 case R.id.open_context_menu_id:
1331 case R.id.open_newtab_context_menu_id:
1332 case R.id.bookmark_context_menu_id:
1333 case R.id.save_link_context_menu_id:
1334 case R.id.share_link_context_menu_id:
1335 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001336 final WebView webView = getTopWindow();
1337 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001338 result = false;
1339 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001340 }
1341 final HashMap hrefMap = new HashMap();
1342 hrefMap.put("webview", webView);
1343 final Message msg = mHandler.obtainMessage(
1344 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 webView.requestFocusNodeHref(msg);
1346 break;
1347
1348 default:
1349 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001350 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 }
1352 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001353 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 }
1355
1356 private Bundle createGoogleSearchSourceBundle(String source) {
1357 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001358 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001359 return bundle;
1360 }
1361
Leon Scroggins8ad29922010-02-16 12:33:55 -05001362 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001363 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001364 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001365 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001366 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001367 }
1368
Leon Scroggins8ad29922010-02-16 12:33:55 -05001369 /**
1370 * Overriding this to insert a local information bundle
1371 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001372 @Override
1373 public void startSearch(String initialQuery, boolean selectInitialQuery,
1374 Bundle appSearchData, boolean globalSearch) {
1375 if (appSearchData == null) {
1376 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1377 }
1378 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1379 }
1380
Leon Scroggins1f005d32009-08-10 17:36:42 -04001381 /**
1382 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1383 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001384 * @param index Index of the tab to change to, as defined by
1385 * mTabControl.getTabIndex(Tab t).
1386 * @return boolean True if we successfully switched to a different tab. If
1387 * the indexth tab is null, or if that tab is the same as
1388 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001389 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001390 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001391 Tab tab = mTabControl.getTab(index);
1392 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001394 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 }
1396 if (currentTab != null) {
1397 // currentTab may be null if it was just removed. In that case,
1398 // we do not need to remove it
1399 removeTabFromContentView(currentTab);
1400 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001401 mTabControl.setCurrentTab(tab);
1402 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001403 resetTitleIconAndProgress();
1404 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001406 }
1407
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001409 return openTabAndShow(mSettings.getHomePage(), false, null);
1410 }
1411
Leon Scroggins1f005d32009-08-10 17:36:42 -04001412 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001413 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001414 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001415 // This is the last tab. Open a new one, with the home
1416 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001417 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001418 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001419 return;
1420 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001421 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001422 int indexToShow = -1;
1423 if (parent != null) {
1424 indexToShow = mTabControl.getTabIndex(parent);
1425 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001426 final int currentIndex = mTabControl.getCurrentIndex();
1427 // Try to move to the tab to the right
1428 indexToShow = currentIndex + 1;
1429 if (indexToShow > mTabControl.getTabCount() - 1) {
1430 // Try to move to the tab to the left
1431 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001432 }
1433 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001434 if (switchToTab(indexToShow)) {
1435 // Close window
1436 closeTab(current);
1437 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001438 }
1439
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001440 private ActiveTabsPage mActiveTabsPage;
1441
1442 /**
1443 * Remove the active tabs page.
1444 * @param needToAttach If true, the active tabs page did not attach a tab
1445 * to the content view, so we need to do that here.
1446 */
1447 /* package */ void removeActiveTabPage(boolean needToAttach) {
1448 mContentView.removeView(mActiveTabsPage);
1449 mActiveTabsPage = null;
1450 mMenuState = R.id.MAIN_MENU;
1451 if (needToAttach) {
1452 attachTabToContentView(mTabControl.getCurrentTab());
1453 }
1454 getTopWindow().requestFocus();
1455 }
1456
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 @Override
1458 public boolean onOptionsItemSelected(MenuItem item) {
1459 if (!mCanChord) {
1460 // The user has already fired a shortcut with this hold down of the
1461 // menu key.
1462 return false;
1463 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001464 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001465 return false;
1466 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001467 if (mMenuIsDown) {
1468 // The shortcut action consumes the MENU. Even if it is still down,
1469 // it won't trigger the next shortcut action. In the case of the
1470 // shortcut action triggering a new activity, like Bookmarks, we
1471 // won't get onKeyUp for MENU. So it is important to reset it here.
1472 mMenuIsDown = false;
1473 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001474 switch (item.getItemId()) {
1475 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001476 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001477 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001478 break;
1479
Leon Scroggins64b80f32009-08-07 12:03:34 -04001480 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001481 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001482 break;
1483
1484 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001485 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 break;
1487
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001488 case R.id.active_tabs_menu_id:
1489 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1490 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001491 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001492 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1493 mActiveTabsPage.requestFocus();
1494 mMenuState = EMPTY_MENU;
1495 break;
1496
Leon Scroggins1f005d32009-08-10 17:36:42 -04001497 case R.id.add_bookmark_menu_id:
1498 Intent i = new Intent(BrowserActivity.this,
1499 AddBookmarkPage.class);
1500 WebView w = getTopWindow();
1501 i.putExtra("url", w.getUrl());
1502 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001503 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001504 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001505 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001506 break;
1507
1508 case R.id.stop_reload_menu_id:
1509 if (mInLoad) {
1510 stopLoading();
1511 } else {
1512 getTopWindow().reload();
1513 }
1514 break;
1515
1516 case R.id.back_menu_id:
1517 getTopWindow().goBack();
1518 break;
1519
1520 case R.id.forward_menu_id:
1521 getTopWindow().goForward();
1522 break;
1523
1524 case R.id.close_menu_id:
1525 // Close the subwindow if it exists.
1526 if (mTabControl.getCurrentSubWindow() != null) {
1527 dismissSubWindow(mTabControl.getCurrentTab());
1528 break;
1529 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001530 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 break;
1532
1533 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001534 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 if (current != null) {
1536 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001537 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001538 }
1539 break;
1540
1541 case R.id.preferences_menu_id:
1542 Intent intent = new Intent(this,
1543 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001544 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1545 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001546 startActivityForResult(intent, PREFERENCES_PAGE);
1547 break;
1548
1549 case R.id.find_menu_id:
1550 if (null == mFindDialog) {
1551 mFindDialog = new FindDialog(this);
1552 }
1553 mFindDialog.setWebView(getTopWindow());
1554 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001555 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001556 mMenuState = EMPTY_MENU;
1557 break;
1558
1559 case R.id.select_text_id:
1560 getTopWindow().emulateShiftHeld();
1561 break;
1562 case R.id.page_info_menu_id:
1563 showPageInfo(mTabControl.getCurrentTab(), false);
1564 break;
1565
1566 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001567 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001568 break;
1569
Leon Scroggins96afcb12009-12-10 12:35:56 -05001570 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001572 Tab currentTab = mTabControl.getCurrentTab();
1573 if (null == currentTab) {
1574 mCanChord = false;
1575 return false;
1576 }
1577 currentTab.populatePickerData();
1578 sharePage(this, currentTab.getTitle(),
1579 currentTab.getUrl(), currentTab.getFavicon(),
1580 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 break;
1582
1583 case R.id.dump_nav_menu_id:
1584 getTopWindow().debugDump();
1585 break;
1586
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001587 case R.id.dump_counters_menu_id:
1588 getTopWindow().dumpV8Counters();
1589 break;
1590
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 case R.id.zoom_in_menu_id:
1592 getTopWindow().zoomIn();
1593 break;
1594
1595 case R.id.zoom_out_menu_id:
1596 getTopWindow().zoomOut();
1597 break;
1598
1599 case R.id.view_downloads_menu_id:
1600 viewDownloads(null);
1601 break;
1602
The Android Open Source Project0c908882009-03-03 19:32:16 -08001603 case R.id.window_one_menu_id:
1604 case R.id.window_two_menu_id:
1605 case R.id.window_three_menu_id:
1606 case R.id.window_four_menu_id:
1607 case R.id.window_five_menu_id:
1608 case R.id.window_six_menu_id:
1609 case R.id.window_seven_menu_id:
1610 case R.id.window_eight_menu_id:
1611 {
1612 int menuid = item.getItemId();
1613 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1614 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001615 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001616 if (desiredTab != null &&
1617 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001618 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001619 }
1620 break;
1621 }
1622 }
1623 }
1624 break;
1625
1626 default:
1627 if (!super.onOptionsItemSelected(item)) {
1628 return false;
1629 }
1630 // Otherwise fall through.
1631 }
1632 mCanChord = false;
1633 return true;
1634 }
1635
1636 public void closeFind() {
1637 mMenuState = R.id.MAIN_MENU;
1638 }
1639
Grace Kloba22ac16e2009-10-07 18:00:23 -07001640 @Override
1641 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 // This happens when the user begins to hold down the menu key, so
1643 // allow them to chord to get a shortcut.
1644 mCanChord = true;
1645 // Note: setVisible will decide whether an item is visible; while
1646 // setEnabled() will decide whether an item is enabled, which also means
1647 // whether the matching shortcut key will function.
1648 super.onPrepareOptionsMenu(menu);
1649 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 case EMPTY_MENU:
1651 if (mCurrentMenuState != mMenuState) {
1652 menu.setGroupVisible(R.id.MAIN_MENU, false);
1653 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1654 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001655 }
1656 break;
1657 default:
1658 if (mCurrentMenuState != mMenuState) {
1659 menu.setGroupVisible(R.id.MAIN_MENU, true);
1660 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1661 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001662 }
1663 final WebView w = getTopWindow();
1664 boolean canGoBack = false;
1665 boolean canGoForward = false;
1666 boolean isHome = false;
1667 if (w != null) {
1668 canGoBack = w.canGoBack();
1669 canGoForward = w.canGoForward();
1670 isHome = mSettings.getHomePage().equals(w.getUrl());
1671 }
1672 final MenuItem back = menu.findItem(R.id.back_menu_id);
1673 back.setEnabled(canGoBack);
1674
1675 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1676 home.setEnabled(!isHome);
1677
1678 menu.findItem(R.id.forward_menu_id)
1679 .setEnabled(canGoForward);
1680
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001681 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001682 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001683
The Android Open Source Project0c908882009-03-03 19:32:16 -08001684 // decide whether to show the share link option
1685 PackageManager pm = getPackageManager();
1686 Intent send = new Intent(Intent.ACTION_SEND);
1687 send.setType("text/plain");
1688 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1689 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1690
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 boolean isNavDump = mSettings.isNavDump();
1692 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1693 nav.setVisible(isNavDump);
1694 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001695
1696 boolean showDebugSettings = mSettings.showDebugSettings();
1697 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1698 counter.setVisible(showDebugSettings);
1699 counter.setEnabled(showDebugSettings);
1700
The Android Open Source Project0c908882009-03-03 19:32:16 -08001701 break;
1702 }
1703 mCurrentMenuState = mMenuState;
1704 return true;
1705 }
1706
1707 @Override
1708 public void onCreateContextMenu(ContextMenu menu, View v,
1709 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001710 if (v instanceof TitleBar) {
1711 return;
1712 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 WebView webview = (WebView) v;
1714 WebView.HitTestResult result = webview.getHitTestResult();
1715 if (result == null) {
1716 return;
1717 }
1718
1719 int type = result.getType();
1720 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1721 Log.w(LOGTAG,
1722 "We should not show context menu when nothing is touched");
1723 return;
1724 }
1725 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1726 // let TextView handles context menu
1727 return;
1728 }
1729
1730 // Note, http://b/issue?id=1106666 is requesting that
1731 // an inflated menu can be used again. This is not available
1732 // yet, so inflate each time (yuk!)
1733 MenuInflater inflater = getMenuInflater();
1734 inflater.inflate(R.menu.browsercontext, menu);
1735
1736 // Show the correct menu group
1737 String extra = result.getExtra();
1738 menu.setGroupVisible(R.id.PHONE_MENU,
1739 type == WebView.HitTestResult.PHONE_TYPE);
1740 menu.setGroupVisible(R.id.EMAIL_MENU,
1741 type == WebView.HitTestResult.EMAIL_TYPE);
1742 menu.setGroupVisible(R.id.GEO_MENU,
1743 type == WebView.HitTestResult.GEO_TYPE);
1744 menu.setGroupVisible(R.id.IMAGE_MENU,
1745 type == WebView.HitTestResult.IMAGE_TYPE
1746 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1747 menu.setGroupVisible(R.id.ANCHOR_MENU,
1748 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1749 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1750
1751 // Setup custom handling depending on the type
1752 switch (type) {
1753 case WebView.HitTestResult.PHONE_TYPE:
1754 menu.setHeaderTitle(Uri.decode(extra));
1755 menu.findItem(R.id.dial_context_menu_id).setIntent(
1756 new Intent(Intent.ACTION_VIEW, Uri
1757 .parse(WebView.SCHEME_TEL + extra)));
1758 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1759 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001760 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001761 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1762 addIntent);
1763 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1764 new Copy(extra));
1765 break;
1766
1767 case WebView.HitTestResult.EMAIL_TYPE:
1768 menu.setHeaderTitle(extra);
1769 menu.findItem(R.id.email_context_menu_id).setIntent(
1770 new Intent(Intent.ACTION_VIEW, Uri
1771 .parse(WebView.SCHEME_MAILTO + extra)));
1772 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1773 new Copy(extra));
1774 break;
1775
1776 case WebView.HitTestResult.GEO_TYPE:
1777 menu.setHeaderTitle(extra);
1778 menu.findItem(R.id.map_context_menu_id).setIntent(
1779 new Intent(Intent.ACTION_VIEW, Uri
1780 .parse(WebView.SCHEME_GEO
1781 + URLEncoder.encode(extra))));
1782 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1783 new Copy(extra));
1784 break;
1785
1786 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1787 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1788 TextView titleView = (TextView) LayoutInflater.from(this)
1789 .inflate(android.R.layout.browser_link_context_header,
1790 null);
1791 titleView.setText(extra);
1792 menu.setHeaderView(titleView);
1793 // decide whether to show the open link in new tab option
1794 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001795 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001796 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1797 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001798 PackageManager pm = getPackageManager();
1799 Intent send = new Intent(Intent.ACTION_SEND);
1800 send.setType("text/plain");
1801 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1802 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1803 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1804 break;
1805 }
1806 // otherwise fall through to handle image part
1807 case WebView.HitTestResult.IMAGE_TYPE:
1808 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1809 menu.setHeaderTitle(extra);
1810 }
1811 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1812 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1813 menu.findItem(R.id.download_context_menu_id).
1814 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001815 menu.findItem(R.id.set_wallpaper_context_menu_id).
1816 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001817 break;
1818
1819 default:
1820 Log.w(LOGTAG, "We should not get here.");
1821 break;
1822 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001823 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001827 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001829 // Attach the container that contains the main WebView and any other UI
1830 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001831 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001832
1833 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001835 if (errorConsole.numberOfErrors() == 0) {
1836 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1837 } else {
1838 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1839 }
1840
1841 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001842 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001843 ViewGroup.LayoutParams.WRAP_CONTENT));
1844 }
1845
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001846 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001847 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001848 if (t.isInVoiceSearchMode()) {
1849 showVoiceTitleBar(t.getVoiceDisplayTitle());
1850 } else {
1851 revertVoiceTitleBar();
1852 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001853 // Request focus on the top window.
1854 t.getTopWindow().requestFocus();
1855 }
1856
1857 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001858 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001859 t.attachSubWindow(mContentView);
1860 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 }
1862
1863 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001864 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001865 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001866 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001867
Grace Kloba22ac16e2009-10-07 18:00:23 -07001868 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1869 if (errorConsole != null) {
1870 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001871 }
1872
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001873 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001874 if (view != null) {
1875 view.setEmbeddedTitleBar(null);
1876 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 }
1878
1879 // Remove the sub window if it exists. Also called by TabControl when the
1880 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001881 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001882 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001883 // dismiss the subwindow. This will destroy the WebView.
1884 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001885 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001886 }
1887
Leon Scroggins1f005d32009-08-10 17:36:42 -04001888 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001889 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001890 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001891 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001892 }
1893
1894 // This method does a ton of stuff. It will attempt to create a new tab
1895 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001896 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001897 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1898 String appId) {
1899 final Tab currentTab = mTabControl.getCurrentTab();
1900 if (mTabControl.canCreateNewTab()) {
1901 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1902 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001903 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001904 // If the last tab was removed from the active tabs page, currentTab
1905 // will be null.
1906 if (currentTab != null) {
1907 removeTabFromContentView(currentTab);
1908 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001909 // We must set the new tab as the current tab to reflect the old
1910 // animation behavior.
1911 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001912 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001913 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001914 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001915 }
1916 return tab;
1917 } else {
1918 // Get rid of the subwindow if it exists
1919 dismissSubWindow(currentTab);
1920 if (!urlData.isEmpty()) {
1921 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001922 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001923 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001924 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 }
1926 }
1927
Grace Kloba22ac16e2009-10-07 18:00:23 -07001928 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001929 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001930 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001931 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001932 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001933 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001934 }
Grace Klobac9181842009-04-14 08:53:22 -07001935 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001937 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 }
1939 }
1940
1941 private class Copy implements OnMenuItemClickListener {
1942 private CharSequence mText;
1943
1944 public boolean onMenuItemClick(MenuItem item) {
1945 copy(mText);
1946 return true;
1947 }
1948
1949 public Copy(CharSequence toCopy) {
1950 mText = toCopy;
1951 }
1952 }
1953
1954 private class Download implements OnMenuItemClickListener {
1955 private String mText;
1956
1957 public boolean onMenuItemClick(MenuItem item) {
1958 onDownloadStartNoStream(mText, null, null, null, -1);
1959 return true;
1960 }
1961
1962 public Download(String toDownload) {
1963 mText = toDownload;
1964 }
1965 }
1966
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001967 private class SetAsWallpaper extends Thread implements
1968 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1969 private URL mUrl;
1970 private ProgressDialog mWallpaperProgress;
1971 private boolean mCanceled = false;
1972
1973 public SetAsWallpaper(String url) {
1974 try {
1975 mUrl = new URL(url);
1976 } catch (MalformedURLException e) {
1977 mUrl = null;
1978 }
1979 }
1980
1981 public void onCancel(DialogInterface dialog) {
1982 mCanceled = true;
1983 }
1984
1985 public boolean onMenuItemClick(MenuItem item) {
1986 if (mUrl != null) {
1987 // The user may have tried to set a image with a large file size as their
1988 // background so it may take a few moments to perform the operation. Display
1989 // a progress spinner while it is working.
1990 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1991 mWallpaperProgress.setIndeterminate(true);
1992 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1993 mWallpaperProgress.setCancelable(true);
1994 mWallpaperProgress.setOnCancelListener(this);
1995 mWallpaperProgress.show();
1996 start();
1997 }
1998 return true;
1999 }
2000
2001 public void run() {
2002 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2003 try {
2004 // TODO: This will cause the resource to be downloaded again, when we
2005 // should in most cases be able to grab it from the cache. To fix this
2006 // we should query WebCore to see if we can access a cached version and
2007 // instead open an input stream on that. This pattern could also be used
2008 // in the download manager where the same problem exists.
2009 InputStream inputstream = mUrl.openStream();
2010 if (inputstream != null) {
2011 setWallpaper(inputstream);
2012 }
2013 } catch (IOException e) {
2014 Log.e(LOGTAG, "Unable to set new wallpaper");
2015 // Act as though the user canceled the operation so we try to
2016 // restore the old wallpaper.
2017 mCanceled = true;
2018 }
2019
2020 if (mCanceled) {
2021 // Restore the old wallpaper if the user cancelled whilst we were setting
2022 // the new wallpaper.
2023 int width = oldWallpaper.getIntrinsicWidth();
2024 int height = oldWallpaper.getIntrinsicHeight();
2025 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2026 Canvas canvas = new Canvas(bm);
2027 oldWallpaper.setBounds(0, 0, width, height);
2028 oldWallpaper.draw(canvas);
2029 try {
2030 setWallpaper(bm);
2031 } catch (IOException e) {
2032 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2033 }
2034 mCanceled = false;
2035 }
2036
2037 if (mWallpaperProgress.isShowing()) {
2038 mWallpaperProgress.dismiss();
2039 }
2040 }
2041 }
2042
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 private void copy(CharSequence text) {
2044 try {
2045 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2046 if (clip != null) {
2047 clip.setClipboardText(text);
2048 }
2049 } catch (android.os.RemoteException e) {
2050 Log.e(LOGTAG, "Copy failed", e);
2051 }
2052 }
2053
2054 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 * Resets the browser title-view to whatever it must be
2056 * (for example, if we had a loading error)
2057 * When we have a new page, we call resetTitle, when we
2058 * have to reset the titlebar to whatever it used to be
2059 * (for example, if the user chose to stop loading), we
2060 * call resetTitleAndRevertLockIcon.
2061 */
2062 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002063 mTabControl.getCurrentTab().revertLockIcon();
2064 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 resetTitleIconAndProgress();
2066 }
2067
2068 /**
2069 * Reset the title, favicon, and progress.
2070 */
2071 private void resetTitleIconAndProgress() {
2072 WebView current = mTabControl.getCurrentWebView();
2073 if (current == null) {
2074 return;
2075 }
2076 resetTitleAndIcon(current);
2077 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002078 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 }
2080
2081 // Reset the title and the icon based on the given item.
2082 private void resetTitleAndIcon(WebView view) {
2083 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2084 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002085 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002086 setFavicon(item.getFavicon());
2087 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002088 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 setFavicon(null);
2090 }
2091 }
2092
2093 /**
2094 * Sets a title composed of the URL and the title string.
2095 * @param url The URL of the site being loaded.
2096 * @param title The title of the site being loaded.
2097 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002098 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 mUrl = url;
2100 mTitle = title;
2101
Leon Scroggins58d56c62010-01-28 15:12:40 -05002102 // If we are in voice search mode, the title has already been set.
2103 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2104 mTitleBar.setDisplayTitle(url);
2105 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 }
2107
2108 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002109 * @param url The URL to build a title version of the URL from.
2110 * @return The title version of the URL or null if fails.
2111 * The title version of the URL can be either the URL hostname,
2112 * or the hostname with an "https://" prefix (for secure URLs),
2113 * or an empty string if, for example, the URL in question is a
2114 * file:// URL with no hostname.
2115 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002116 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002117 String titleUrl = null;
2118
2119 if (url != null) {
2120 try {
2121 // parse the url string
2122 URL urlObj = new URL(url);
2123 if (urlObj != null) {
2124 titleUrl = "";
2125
2126 String protocol = urlObj.getProtocol();
2127 String host = urlObj.getHost();
2128
2129 if (host != null && 0 < host.length()) {
2130 titleUrl = host;
2131 if (protocol != null) {
2132 // if a secure site, add an "https://" prefix!
2133 if (protocol.equalsIgnoreCase("https")) {
2134 titleUrl = protocol + "://" + host;
2135 }
2136 }
2137 }
2138 }
2139 } catch (MalformedURLException e) {}
2140 }
2141
2142 return titleUrl;
2143 }
2144
2145 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002146 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002147 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002148 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002149 }
2150
2151 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002152 * Close the tab, remove its associated title bar, and adjust mTabControl's
2153 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002154 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002155 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002156 int currentIndex = mTabControl.getCurrentIndex();
2157 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002158 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002159 if (currentIndex >= removeIndex && currentIndex != 0) {
2160 currentIndex--;
2161 }
2162 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002163 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 }
2165
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002166 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002167 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 if (current == null) {
2169 /*
2170 * Instead of finishing the activity, simply push this to the back
2171 * of the stack and let ActivityManager to choose the foreground
2172 * activity. As BrowserActivity is singleTask, it will be always the
2173 * root of the task. So we can use either true or false for
2174 * moveTaskToBack().
2175 */
2176 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002177 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
2179 WebView w = current.getWebView();
2180 if (w.canGoBack()) {
2181 w.goBack();
2182 } else {
2183 // Check to see if we are closing a window that was created by
2184 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002185 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002187 switchToTab(mTabControl.getTabIndex(parent));
2188 // Now we close the other tab
2189 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 } else {
2191 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002192 // force the tab's inLoad() to be false as we are going to
2193 // either finish the activity or remove the tab. This will
2194 // ensure pauseWebViewTimers() taking action.
2195 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002196 if (mTabControl.getTabCount() == 1) {
2197 finish();
2198 return;
2199 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002200 // call pauseWebViewTimers() now, we won't be able to call
2201 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002202 // Temporarily change mActivityInPause to be true as
2203 // pauseWebViewTimers() will do nothing if mActivityInPause
2204 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002205 boolean savedState = mActivityInPause;
2206 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002207 Log.e(LOGTAG, "BrowserActivity is already paused "
2208 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002209 }
2210 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002211 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002212 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002213 removeTabFromContentView(current);
2214 mTabControl.removeTab(current);
2215 }
2216 /*
2217 * Instead of finishing the activity, simply push this to the back
2218 * of the stack and let ActivityManager to choose the foreground
2219 * activity. As BrowserActivity is singleTask, it will be always the
2220 * root of the task. So we can use either true or false for
2221 * moveTaskToBack().
2222 */
2223 moveTaskToBack(true);
2224 }
2225 }
2226 }
2227
Grace Kloba22ac16e2009-10-07 18:00:23 -07002228 boolean isMenuDown() {
2229 return mMenuIsDown;
2230 }
2231
Grace Kloba5942df02009-09-18 11:48:29 -07002232 @Override
2233 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002234 // Even if MENU is already held down, we need to call to super to open
2235 // the IME on long press.
2236 if (KeyEvent.KEYCODE_MENU == keyCode) {
2237 mMenuIsDown = true;
2238 return super.onKeyDown(keyCode, event);
2239 }
Grace Kloba5942df02009-09-18 11:48:29 -07002240 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2241 // still down, we don't want to trigger the search. Pretend to consume
2242 // the key and do nothing.
2243 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244
Grace Kloba5942df02009-09-18 11:48:29 -07002245 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002246 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002247 // WebView/WebTextView handle the keys in the KeyDown. As
2248 // the Activity's shortcut keys are only handled when WebView
2249 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2250 if (event.isShiftPressed()) {
2251 getTopWindow().pageUp(false);
2252 } else {
2253 getTopWindow().pageDown(false);
2254 }
Grace Kloba5942df02009-09-18 11:48:29 -07002255 return true;
2256 case KeyEvent.KEYCODE_BACK:
2257 if (event.getRepeatCount() == 0) {
2258 event.startTracking();
2259 return true;
2260 } else if (mCustomView == null && mActiveTabsPage == null
2261 && event.isLongPress()) {
2262 bookmarksOrHistoryPicker(true);
2263 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 }
Grace Kloba5942df02009-09-18 11:48:29 -07002265 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 }
Grace Kloba5942df02009-09-18 11:48:29 -07002267 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268 }
2269
Grace Kloba5942df02009-09-18 11:48:29 -07002270 @Override
2271 public boolean onKeyUp(int keyCode, KeyEvent event) {
2272 switch(keyCode) {
2273 case KeyEvent.KEYCODE_MENU:
2274 mMenuIsDown = false;
2275 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002276 case KeyEvent.KEYCODE_BACK:
2277 if (event.isTracking() && !event.isCanceled()) {
2278 if (mCustomView != null) {
2279 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002280 mTabControl.getCurrentWebView().getWebChromeClient()
2281 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002282 } else if (mActiveTabsPage != null) {
2283 // if tab page is showing, hide it
2284 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002285 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002286 WebView subwindow = mTabControl.getCurrentSubWindow();
2287 if (subwindow != null) {
2288 if (subwindow.canGoBack()) {
2289 subwindow.goBack();
2290 } else {
2291 dismissSubWindow(mTabControl.getCurrentTab());
2292 }
2293 } else {
2294 goBackOnePageOrQuit();
2295 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 }
Grace Kloba5942df02009-09-18 11:48:29 -07002297 return true;
2298 }
2299 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002300 }
Grace Kloba5942df02009-09-18 11:48:29 -07002301 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302 }
2303
Leon Scroggins68579392009-09-15 15:31:54 -04002304 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002305 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306 resetTitleAndRevertLockIcon();
2307 WebView w = getTopWindow();
2308 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002309 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2310 // same logic here. But for subwindow case, should we call into the main
2311 // WebView's onPageFinished as we never call its onPageStarted and if
2312 // the page finishes itself, we don't call onPageFinished.
2313 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2314 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002315
2316 cancelStopToast();
2317 mStopToast = Toast
2318 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2319 mStopToast.show();
2320 }
2321
Grace Kloba22ac16e2009-10-07 18:00:23 -07002322 boolean didUserStopLoading() {
2323 return mDidStopLoad;
2324 }
2325
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 private void cancelStopToast() {
2327 if (mStopToast != null) {
2328 mStopToast.cancel();
2329 mStopToast = null;
2330 }
2331 }
2332
Grace Kloba22ac16e2009-10-07 18:00:23 -07002333 // called by a UI or non-UI thread to post the message
2334 public void postMessage(int what, int arg1, int arg2, Object obj,
2335 long delayMillis) {
2336 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2337 obj), delayMillis);
2338 }
2339
2340 // called by a UI or non-UI thread to remove the message
2341 void removeMessages(int what, Object object) {
2342 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343 }
2344
2345 // public message ids
2346 public final static int LOAD_URL = 1001;
2347 public final static int STOP_LOAD = 1002;
2348
2349 // Message Ids
2350 private static final int FOCUS_NODE_HREF = 102;
2351 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002352 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353
Grace Kloba22ac16e2009-10-07 18:00:23 -07002354 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002355
The Android Open Source Project0c908882009-03-03 19:32:16 -08002356 // Private handler for handling javascript and saving passwords
2357 private Handler mHandler = new Handler() {
2358
2359 public void handleMessage(Message msg) {
2360 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002361 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002362 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002363 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002364 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002365 if (url == null || url.length() == 0) {
2366 break;
2367 }
2368 HashMap focusNodeMap = (HashMap) msg.obj;
2369 WebView view = (WebView) focusNodeMap.get("webview");
2370 // Only apply the action if the top window did not change.
2371 if (getTopWindow() != view) {
2372 break;
2373 }
2374 switch (msg.arg1) {
2375 case R.id.open_context_menu_id:
2376 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002377 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378 break;
2379 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002380 final Tab parent = mTabControl.getCurrentTab();
2381 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002382 if (newTab != parent) {
2383 parent.addChildTab(newTab);
2384 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002385 break;
2386 case R.id.bookmark_context_menu_id:
2387 Intent intent = new Intent(BrowserActivity.this,
2388 AddBookmarkPage.class);
2389 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002390 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 startActivity(intent);
2392 break;
2393 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002394 // See if this site has been visited before
2395 StringBuilder sb = new StringBuilder(
2396 Browser.BookmarkColumns.URL + " = ");
2397 DatabaseUtils.appendEscapedSQLString(sb, url);
2398 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2399 Browser.HISTORY_PROJECTION,
2400 sb.toString(),
2401 null,
2402 null);
2403 if (c.moveToFirst()) {
2404 // The site has been visited before, so grab the
2405 // info from the database.
2406 Bitmap favicon = null;
2407 Bitmap thumbnail = null;
2408 String linkTitle = c.getString(Browser.
2409 HISTORY_PROJECTION_TITLE_INDEX);
2410 byte[] data = c.getBlob(Browser.
2411 HISTORY_PROJECTION_FAVICON_INDEX);
2412 if (data != null) {
2413 favicon = BitmapFactory.decodeByteArray(
2414 data, 0, data.length);
2415 }
2416 data = c.getBlob(Browser.
2417 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2418 if (data != null) {
2419 thumbnail = BitmapFactory.decodeByteArray(
2420 data, 0, data.length);
2421 }
2422 sharePage(BrowserActivity.this,
2423 linkTitle, url, favicon, thumbnail);
2424 } else {
2425 Browser.sendString(BrowserActivity.this, url,
2426 getString(
2427 R.string.choosertitle_sharevia));
2428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 break;
2430 case R.id.copy_link_context_menu_id:
2431 copy(url);
2432 break;
2433 case R.id.save_link_context_menu_id:
2434 case R.id.download_context_menu_id:
2435 onDownloadStartNoStream(url, null, null, null, -1);
2436 break;
2437 }
2438 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002439 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440
2441 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002442 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002443 break;
2444
2445 case STOP_LOAD:
2446 stopLoading();
2447 break;
2448
2449 case CANCEL_CREDS_REQUEST:
2450 resumeAfterCredentials();
2451 break;
2452
The Android Open Source Project0c908882009-03-03 19:32:16 -08002453 case RELEASE_WAKELOCK:
2454 if (mWakeLock.isHeld()) {
2455 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002456 // if we reach here, Browser should be still in the
2457 // background loading after WAKELOCK_TIMEOUT (5-min).
2458 // To avoid burning the battery, stop loading.
2459 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002460 }
2461 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002462
2463 case UPDATE_BOOKMARK_THUMBNAIL:
2464 WebView view = (WebView) msg.obj;
2465 if (view != null) {
2466 updateScreenshot(view);
2467 }
2468 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002469 }
2470 }
2471 };
2472
Leon Scroggins96afcb12009-12-10 12:35:56 -05002473 /**
2474 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2475 * an {@link Intent} to launch the Activity chooser.
2476 * @param c Context used to launch a new Activity.
2477 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002478 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002479 * @param url URL of the page. Stored in the Intent with
2480 * {@link Intent#EXTRA_TEXT}
2481 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2482 * with {@link Browser#EXTRA_SHARE_FAVICON}
2483 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2484 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2485 */
2486 public static final void sharePage(Context c, String title, String url,
2487 Bitmap favicon, Bitmap screenshot) {
2488 Intent send = new Intent(Intent.ACTION_SEND);
2489 send.setType("text/plain");
2490 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002491 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002492 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2493 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2494 try {
2495 c.startActivity(Intent.createChooser(send, c.getString(
2496 R.string.choosertitle_sharevia)));
2497 } catch(android.content.ActivityNotFoundException ex) {
2498 // if no app handles it, do nothing
2499 }
2500 }
2501
Leon Scroggins89c6d362009-07-15 16:54:37 -04002502 private void updateScreenshot(WebView view) {
2503 // If this is a bookmarked site, add a screenshot to the database.
2504 // FIXME: When should we update? Every time?
2505 // FIXME: Would like to make sure there is actually something to
2506 // draw, but the API for that (WebViewCore.pictureReady()) is not
2507 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002508
Patrick Scott3918d442009-08-04 13:22:29 -04002509 ContentResolver cr = getContentResolver();
2510 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002511 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002512 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002513 boolean succeed = c.moveToFirst();
2514 ContentValues values = null;
2515 while (succeed) {
2516 if (values == null) {
2517 final ByteArrayOutputStream os
2518 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002519 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002520 if (bm == null) {
2521 c.close();
2522 return;
2523 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002524 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2525 values = new ContentValues();
2526 values.put(Browser.BookmarkColumns.THUMBNAIL,
2527 os.toByteArray());
2528 }
2529 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2530 c.getInt(0)), values, null, null);
2531 succeed = c.moveToNext();
2532 }
2533 c.close();
2534 }
2535 }
2536
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002537 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002538 * Values for the size of the thumbnail created when taking a screenshot.
2539 * Lazily initialized. Instead of using these directly, use
2540 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002541 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002542 private static int THUMBNAIL_WIDTH = 0;
2543 private static int THUMBNAIL_HEIGHT = 0;
2544
2545 /**
2546 * Return the desired width for thumbnail screenshots, which are stored in
2547 * the database, and used on the bookmarks screen.
2548 * @param context Context for finding out the density of the screen.
2549 * @return int desired width for thumbnail screenshot.
2550 */
2551 /* package */ static int getDesiredThumbnailWidth(Context context) {
2552 if (THUMBNAIL_WIDTH == 0) {
2553 float density = context.getResources().getDisplayMetrics().density;
2554 THUMBNAIL_WIDTH = (int) (90 * density);
2555 THUMBNAIL_HEIGHT = (int) (80 * density);
2556 }
2557 return THUMBNAIL_WIDTH;
2558 }
2559
2560 /**
2561 * Return the desired height for thumbnail screenshots, which are stored in
2562 * the database, and used on the bookmarks screen.
2563 * @param context Context for finding out the density of the screen.
2564 * @return int desired height for thumbnail screenshot.
2565 */
2566 /* package */ static int getDesiredThumbnailHeight(Context context) {
2567 // To ensure that they are both initialized.
2568 getDesiredThumbnailWidth(context);
2569 return THUMBNAIL_HEIGHT;
2570 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002571
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002572 private Bitmap createScreenshot(WebView view) {
2573 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002574 if (thumbnail == null) {
2575 return null;
2576 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002577 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2578 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002579 Canvas canvas = new Canvas(bm);
2580 // May need to tweak these values to determine what is the
2581 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002582 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002583 int thumbnailHeight = thumbnail.getHeight();
2584 float scaleFactorX = 1.0f;
2585 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002586 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002587 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002588 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002589 } else {
2590 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002591 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002592
2593 if (view.getWidth() > view.getHeight() &&
2594 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2595 // If the device is in landscape and the page is shorter
2596 // than the height of the view, stretch the thumbnail to fill the
2597 // space.
2598 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2599 (float)thumbnailHeight;
2600 } else {
2601 // In the portrait case, this looks nice.
2602 scaleFactorY = scaleFactorX;
2603 }
2604
2605 canvas.scale(scaleFactorX, scaleFactorY);
2606
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002607 thumbnail.draw(canvas);
2608 return bm;
2609 }
2610
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 //-------------------------------------------------------------------------
2614
2615 // Use in overrideUrlLoading
2616 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2617 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2618 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2619 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2620
Leon Scroggins92472e82010-02-17 16:32:28 -05002621 // Keep this initial progress in sync with initialProgressValue (* 100)
2622 // in ProgressTracker.cpp
2623 private final static int INITIAL_PROGRESS = 10;
2624
Grace Kloba22ac16e2009-10-07 18:00:23 -07002625 void onPageStarted(WebView view, String url, Bitmap favicon) {
2626 // when BrowserActivity just starts, onPageStarted may be called before
2627 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2628 // to start the timer. As we won't switch tabs while an activity is in
2629 // pause state, we can ensure calling resume and pause in pair.
2630 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002631
Grace Kloba22ac16e2009-10-07 18:00:23 -07002632 resetLockIcon(url);
2633 setUrlTitle(url, null);
2634 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002635 // Show some progress so that the user knows the page is beginning to
2636 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002637 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002640
Grace Kloba22ac16e2009-10-07 18:00:23 -07002641 if (mSettings.isTracing()) {
2642 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 WebAddress uri = new WebAddress(url);
2645 host = uri.mHost;
2646 } catch (android.net.ParseException ex) {
2647 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 host = host.replace('.', '_');
2650 host += ".trace";
2651 mInTrace = true;
2652 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2653 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002654
Grace Kloba22ac16e2009-10-07 18:00:23 -07002655 // Performance probe
2656 if (false) {
2657 mStart = SystemClock.uptimeMillis();
2658 mProcessStart = Process.getElapsedCpuTime();
2659 long[] sysCpu = new long[7];
2660 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2661 sysCpu, null)) {
2662 mUserStart = sysCpu[0] + sysCpu[1];
2663 mSystemStart = sysCpu[2];
2664 mIdleStart = sysCpu[3];
2665 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2666 }
2667 mUiStart = SystemClock.currentThreadTimeMillis();
2668 }
2669 }
2670
2671 void onPageFinished(WebView view, String url) {
2672 // Reset the title and icon in case we stopped a provisional load.
2673 resetTitleAndIcon(view);
2674 // Update the lock icon image only once we are done loading
2675 updateLockIconToLatest();
2676 // pause the WebView timer and release the wake lock if it is finished
2677 // while BrowserActivity is in pause state.
2678 if (mActivityInPause && pauseWebViewTimers()) {
2679 if (mWakeLock.isHeld()) {
2680 mHandler.removeMessages(RELEASE_WAKELOCK);
2681 mWakeLock.release();
2682 }
2683 }
2684
2685 // Performance probe
2686 if (false) {
2687 long[] sysCpu = new long[7];
2688 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2689 sysCpu, null)) {
2690 String uiInfo = "UI thread used "
2691 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2692 + " ms";
2693 if (LOGD_ENABLED) {
2694 Log.d(LOGTAG, uiInfo);
2695 }
2696 //The string that gets written to the log
2697 String performanceString = "It took total "
2698 + (SystemClock.uptimeMillis() - mStart)
2699 + " ms clock time to load the page."
2700 + "\nbrowser process used "
2701 + (Process.getElapsedCpuTime() - mProcessStart)
2702 + " ms, user processes used "
2703 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2704 + " ms, kernel used "
2705 + (sysCpu[2] - mSystemStart) * 10
2706 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2707 + " ms and irq took "
2708 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2709 * 10 + " ms, " + uiInfo;
2710 if (LOGD_ENABLED) {
2711 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2712 }
2713 if (url != null) {
2714 // strip the url to maintain consistency
2715 String newUrl = new String(url);
2716 if (newUrl.startsWith("http://www.")) {
2717 newUrl = newUrl.substring(11);
2718 } else if (newUrl.startsWith("http://")) {
2719 newUrl = newUrl.substring(7);
2720 } else if (newUrl.startsWith("https://www.")) {
2721 newUrl = newUrl.substring(12);
2722 } else if (newUrl.startsWith("https://")) {
2723 newUrl = newUrl.substring(8);
2724 }
2725 if (LOGD_ENABLED) {
2726 Log.d(LOGTAG, newUrl + " loaded");
2727 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002728 }
2729 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 if (mInTrace) {
2733 mInTrace = false;
2734 Debug.stopMethodTracing();
2735 }
2736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 boolean shouldOverrideUrlLoading(WebView view, String url) {
2739 if (url.startsWith(SCHEME_WTAI)) {
2740 // wtai://wp/mc;number
2741 // number=string(phone-number)
2742 if (url.startsWith(SCHEME_WTAI_MC)) {
2743 Intent intent = new Intent(Intent.ACTION_VIEW,
2744 Uri.parse(WebView.SCHEME_TEL +
2745 url.substring(SCHEME_WTAI_MC.length())));
2746 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 return true;
2748 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002749 // wtai://wp/sd;dtmf
2750 // dtmf=string(dialstring)
2751 if (url.startsWith(SCHEME_WTAI_SD)) {
2752 // TODO: only send when there is active voice connection
2753 return false;
2754 }
2755 // wtai://wp/ap;number;name
2756 // number=string(phone-number)
2757 // name=string
2758 if (url.startsWith(SCHEME_WTAI_AP)) {
2759 // TODO
2760 return false;
2761 }
2762 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763
Grace Kloba22ac16e2009-10-07 18:00:23 -07002764 // The "about:" schemes are internal to the browser; don't want these to
2765 // be dispatched to other apps.
2766 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 return false;
2768 }
2769
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 Intent intent;
2771 // perform generic parsing of the URI to turn it into an Intent.
2772 try {
2773 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2774 } catch (URISyntaxException ex) {
2775 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2776 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 }
2778
Grace Kloba22ac16e2009-10-07 18:00:23 -07002779 // check whether the intent can be resolved. If not, we will see
2780 // whether we can download it from the Market.
2781 if (getPackageManager().resolveActivity(intent, 0) == null) {
2782 String packagename = intent.getPackage();
2783 if (packagename != null) {
2784 intent = new Intent(Intent.ACTION_VIEW, Uri
2785 .parse("market://search?q=pname:" + packagename));
2786 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2787 startActivity(intent);
2788 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002789 } else {
2790 return false;
2791 }
2792 }
2793
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 // sanitize the Intent, ensuring web pages can not bypass browser
2795 // security (only access to BROWSABLE activities).
2796 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2797 intent.setComponent(null);
2798 try {
2799 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800 return true;
2801 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002802 } catch (ActivityNotFoundException ex) {
2803 // ignore the error. If no application can handle the URL,
2804 // eg about:blank, assume the browser can handle it.
2805 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807 if (mMenuIsDown) {
2808 openTab(url);
2809 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002810 return true;
2811 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002812 return false;
2813 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002814
Grace Kloba22ac16e2009-10-07 18:00:23 -07002815 // -------------------------------------------------------------------------
2816 // Helper function for WebChromeClient
2817 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002818
Grace Kloba22ac16e2009-10-07 18:00:23 -07002819 void onProgressChanged(WebView view, int newProgress) {
2820 mTitleBar.setProgress(newProgress);
2821 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002822
Grace Kloba22ac16e2009-10-07 18:00:23 -07002823 if (newProgress == 100) {
2824 // onProgressChanged() may continue to be called after the main
2825 // frame has finished loading, as any remaining sub frames continue
2826 // to load. We'll only get called once though with newProgress as
2827 // 100 when everything is loaded. (onPageFinished is called once
2828 // when the main frame completes loading regardless of the state of
2829 // any sub frames so calls to onProgressChanges may continue after
2830 // onPageFinished has executed)
2831 if (mInLoad) {
2832 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002833 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002834 // If the options menu is open, leave the title bar
2835 if (!mOptionsMenuOpen || !mIconView) {
2836 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002837 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002838 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002839 } else {
2840 if (!mInLoad) {
2841 // onPageFinished may have already been called but a subframe is
2842 // still loading and updating the progress. Reset mInLoad and
2843 // update the menu items.
2844 mInLoad = true;
2845 updateInLoadMenuItems();
2846 }
2847 // When the page first begins to load, the Activity may still be
2848 // paused, in which case showFakeTitleBar will do nothing. Call
2849 // again as the page continues to load so that it will be shown.
2850 // (Calling it will the fake title bar is already showing will also
2851 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002852 if (!mOptionsMenuOpen || mIconView) {
2853 // This page has begun to load, so show the title bar
2854 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002855 }
2856 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002858
Grace Kloba22ac16e2009-10-07 18:00:23 -07002859 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002860 // if a view already exists then immediately terminate the new one
2861 if (mCustomView != null) {
2862 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002863 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002864 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865
2866 // Add the custom view to its container.
2867 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2868 mCustomView = view;
2869 mCustomViewCallback = callback;
2870 // Save the menu state and set it to empty while the custom
2871 // view is showing.
2872 mOldMenuState = mMenuState;
2873 mMenuState = EMPTY_MENU;
2874 // Hide the content view.
2875 mContentView.setVisibility(View.GONE);
2876 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002877 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002878 mCustomViewContainer.setVisibility(View.VISIBLE);
2879 mCustomViewContainer.bringToFront();
2880 }
2881
2882 void onHideCustomView() {
2883 if (mCustomView == null)
2884 return;
2885
2886 // Hide the custom view.
2887 mCustomView.setVisibility(View.GONE);
2888 // Remove the custom view from its container.
2889 mCustomViewContainer.removeView(mCustomView);
2890 mCustomView = null;
2891 // Reset the old menu state.
2892 mMenuState = mOldMenuState;
2893 mOldMenuState = EMPTY_MENU;
2894 mCustomViewContainer.setVisibility(View.GONE);
2895 mCustomViewCallback.onCustomViewHidden();
2896 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002897 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 mContentView.setVisibility(View.VISIBLE);
2899 }
2900
2901 Bitmap getDefaultVideoPoster() {
2902 if (mDefaultVideoPoster == null) {
2903 mDefaultVideoPoster = BitmapFactory.decodeResource(
2904 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002905 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002906 return mDefaultVideoPoster;
2907 }
Patrick Scott3918d442009-08-04 13:22:29 -04002908
Grace Kloba22ac16e2009-10-07 18:00:23 -07002909 View getVideoLoadingProgressView() {
2910 if (mVideoProgressView == null) {
2911 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2912 mVideoProgressView = inflater.inflate(
2913 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002914 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002915 return mVideoProgressView;
2916 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002917
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002918 /*
2919 * The Object used to inform the WebView of the file to upload.
2920 */
2921 private ValueCallback<Uri> mUploadMessage;
2922
Grace Kloba22ac16e2009-10-07 18:00:23 -07002923 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2924 if (mUploadMessage != null) return;
2925 mUploadMessage = uploadMsg;
2926 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2927 i.addCategory(Intent.CATEGORY_OPENABLE);
2928 i.setType("*/*");
2929 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2930 getString(R.string.choose_upload)), FILE_SELECTED);
2931 }
2932
2933 // -------------------------------------------------------------------------
2934 // Implement functions for DownloadListener
2935 // -------------------------------------------------------------------------
2936
The Android Open Source Project0c908882009-03-03 19:32:16 -08002937 /**
2938 * Notify the host application a download should be done, or that
2939 * the data should be streamed if a streaming viewer is available.
2940 * @param url The full url to the content that should be downloaded
2941 * @param contentDisposition Content-disposition http header, if
2942 * present.
2943 * @param mimetype The mimetype of the content reported by the server
2944 * @param contentLength The file size reported by the server
2945 */
2946 public void onDownloadStart(String url, String userAgent,
2947 String contentDisposition, String mimetype, long contentLength) {
2948 // if we're dealing wih A/V content that's not explicitly marked
2949 // for download, check if it's streamable.
2950 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002951 || !contentDisposition.regionMatches(
2952 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002953 // query the package manager to see if there's a registered handler
2954 // that matches.
2955 Intent intent = new Intent(Intent.ACTION_VIEW);
2956 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002957 ResolveInfo info = getPackageManager().resolveActivity(intent,
2958 PackageManager.MATCH_DEFAULT_ONLY);
2959 if (info != null) {
2960 ComponentName myName = getComponentName();
2961 // If we resolved to ourselves, we don't want to attempt to
2962 // load the url only to try and download it again.
2963 if (!myName.getPackageName().equals(
2964 info.activityInfo.packageName)
2965 || !myName.getClassName().equals(
2966 info.activityInfo.name)) {
2967 // someone (other than us) knows how to handle this mime
2968 // type with this scheme, don't download.
2969 try {
2970 startActivity(intent);
2971 return;
2972 } catch (ActivityNotFoundException ex) {
2973 if (LOGD_ENABLED) {
2974 Log.d(LOGTAG, "activity not found for " + mimetype
2975 + " over " + Uri.parse(url).getScheme(),
2976 ex);
2977 }
2978 // Best behavior is to fall back to a download in this
2979 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002981 }
2982 }
2983 }
2984 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2985 }
2986
2987 /**
2988 * Notify the host application a download should be done, even if there
2989 * is a streaming viewer available for thise type.
2990 * @param url The full url to the content that should be downloaded
2991 * @param contentDisposition Content-disposition http header, if
2992 * present.
2993 * @param mimetype The mimetype of the content reported by the server
2994 * @param contentLength The file size reported by the server
2995 */
2996 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2997 String contentDisposition, String mimetype, long contentLength) {
2998
2999 String filename = URLUtil.guessFileName(url,
3000 contentDisposition, mimetype);
3001
3002 // Check to see if we have an SDCard
3003 String status = Environment.getExternalStorageState();
3004 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3005 int title;
3006 String msg;
3007
3008 // Check to see if the SDCard is busy, same as the music app
3009 if (status.equals(Environment.MEDIA_SHARED)) {
3010 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3011 title = R.string.download_sdcard_busy_dlg_title;
3012 } else {
3013 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3014 title = R.string.download_no_sdcard_dlg_title;
3015 }
3016
3017 new AlertDialog.Builder(this)
3018 .setTitle(title)
3019 .setIcon(android.R.drawable.ic_dialog_alert)
3020 .setMessage(msg)
3021 .setPositiveButton(R.string.ok, null)
3022 .show();
3023 return;
3024 }
3025
3026 // java.net.URI is a lot stricter than KURL so we have to undo
3027 // KURL's percent-encoding and redo the encoding using java.net.URI.
3028 URI uri = null;
3029 try {
3030 // Undo the percent-encoding that KURL may have done.
3031 String newUrl = new String(URLUtil.decode(url.getBytes()));
3032 // Parse the url into pieces
3033 WebAddress w = new WebAddress(newUrl);
3034 String frag = null;
3035 String query = null;
3036 String path = w.mPath;
3037 // Break the path into path, query, and fragment
3038 if (path.length() > 0) {
3039 // Strip the fragment
3040 int idx = path.lastIndexOf('#');
3041 if (idx != -1) {
3042 frag = path.substring(idx + 1);
3043 path = path.substring(0, idx);
3044 }
3045 idx = path.lastIndexOf('?');
3046 if (idx != -1) {
3047 query = path.substring(idx + 1);
3048 path = path.substring(0, idx);
3049 }
3050 }
3051 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3052 query, frag);
3053 } catch (Exception e) {
3054 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3055 return;
3056 }
3057
3058 // XXX: Have to use the old url since the cookies were stored using the
3059 // old percent-encoded url.
3060 String cookies = CookieManager.getInstance().getCookie(url);
3061
3062 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003063 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3064 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3065 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3066 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003068 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003069 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003070 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3071 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3072 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3073 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3074 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003075 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003076 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003077 }
3078 if (mimetype == null) {
3079 // We must have long pressed on a link or image to download it. We
3080 // are not sure of the mimetype in this case, so do a head request
3081 new FetchUrlMimeType(this).execute(values);
3082 } else {
3083 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003084 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003085 }
3086
3087 }
3088
Grace Kloba22ac16e2009-10-07 18:00:23 -07003089 // -------------------------------------------------------------------------
3090
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091 /**
3092 * Resets the lock icon. This method is called when we start a new load and
3093 * know the url to be loaded.
3094 */
3095 private void resetLockIcon(String url) {
3096 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003097 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098 updateLockIconImage(LOCK_ICON_UNSECURE);
3099 }
3100
The Android Open Source Project0c908882009-03-03 19:32:16 -08003101 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003102 * Update the lock icon to correspond to our latest state.
3103 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003104 private void updateLockIconToLatest() {
3105 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003106 }
3107
3108 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003109 * Updates the lock-icon image in the title-bar.
3110 */
3111 private void updateLockIconImage(int lockIconType) {
3112 Drawable d = null;
3113 if (lockIconType == LOCK_ICON_SECURE) {
3114 d = mSecLockIcon;
3115 } else if (lockIconType == LOCK_ICON_MIXED) {
3116 d = mMixLockIcon;
3117 }
Leon Scroggins68579392009-09-15 15:31:54 -04003118 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003119 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003120 }
3121
3122 /**
3123 * Displays a page-info dialog.
3124 * @param tab The tab to show info about
3125 * @param fromShowSSLCertificateOnError The flag that indicates whether
3126 * this dialog was opened from the SSL-certificate-on-error dialog or
3127 * not. This is important, since we need to know whether to return to
3128 * the parent dialog or simply dismiss.
3129 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003130 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003131 final boolean fromShowSSLCertificateOnError) {
3132 final LayoutInflater factory = LayoutInflater
3133 .from(this);
3134
3135 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3136
3137 final WebView view = tab.getWebView();
3138
3139 String url = null;
3140 String title = null;
3141
3142 if (view == null) {
3143 url = tab.getUrl();
3144 title = tab.getTitle();
3145 } else if (view == mTabControl.getCurrentWebView()) {
3146 // Use the cached title and url if this is the current WebView
3147 url = mUrl;
3148 title = mTitle;
3149 } else {
3150 url = view.getUrl();
3151 title = view.getTitle();
3152 }
3153
3154 if (url == null) {
3155 url = "";
3156 }
3157 if (title == null) {
3158 title = "";
3159 }
3160
3161 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3162 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3163
3164 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003165 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003166
3167 AlertDialog.Builder alertDialogBuilder =
3168 new AlertDialog.Builder(this)
3169 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3170 .setView(pageInfoView)
3171 .setPositiveButton(
3172 R.string.ok,
3173 new DialogInterface.OnClickListener() {
3174 public void onClick(DialogInterface dialog,
3175 int whichButton) {
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 .setOnCancelListener(
3190 new DialogInterface.OnCancelListener() {
3191 public void onCancel(DialogInterface dialog) {
3192 mPageInfoDialog = null;
3193 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003194
3195 // if we came here from the SSL error dialog
3196 if (fromShowSSLCertificateOnError) {
3197 // go back to the SSL error dialog
3198 showSSLCertificateOnError(
3199 mSSLCertificateOnErrorView,
3200 mSSLCertificateOnErrorHandler,
3201 mSSLCertificateOnErrorError);
3202 }
3203 }
3204 });
3205
3206 // if we have a main top-level page SSL certificate set or a certificate
3207 // error
3208 if (fromShowSSLCertificateOnError ||
3209 (view != null && view.getCertificate() != null)) {
3210 // add a 'View Certificate' button
3211 alertDialogBuilder.setNeutralButton(
3212 R.string.view_certificate,
3213 new DialogInterface.OnClickListener() {
3214 public void onClick(DialogInterface dialog,
3215 int whichButton) {
3216 mPageInfoDialog = null;
3217 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218
3219 // if we came here from the SSL error dialog
3220 if (fromShowSSLCertificateOnError) {
3221 // go back to the SSL error dialog
3222 showSSLCertificateOnError(
3223 mSSLCertificateOnErrorView,
3224 mSSLCertificateOnErrorHandler,
3225 mSSLCertificateOnErrorError);
3226 } else {
3227 // otherwise, display the top-most certificate from
3228 // the chain
3229 if (view.getCertificate() != null) {
3230 showSSLCertificate(tab);
3231 }
3232 }
3233 }
3234 });
3235 }
3236
3237 mPageInfoDialog = alertDialogBuilder.show();
3238 }
3239
3240 /**
3241 * Displays the main top-level page SSL certificate dialog
3242 * (accessible from the Page-Info dialog).
3243 * @param tab The tab to show certificate for.
3244 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003245 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003246 final View certificateView =
3247 inflateCertificateView(tab.getWebView().getCertificate());
3248 if (certificateView == null) {
3249 return;
3250 }
3251
3252 LayoutInflater factory = LayoutInflater.from(this);
3253
3254 final LinearLayout placeholder =
3255 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3256
3257 LinearLayout ll = (LinearLayout) factory.inflate(
3258 R.layout.ssl_success, placeholder);
3259 ((TextView)ll.findViewById(R.id.success))
3260 .setText(R.string.ssl_certificate_is_valid);
3261
3262 mSSLCertificateView = tab;
3263 mSSLCertificateDialog =
3264 new AlertDialog.Builder(this)
3265 .setTitle(R.string.ssl_certificate).setIcon(
3266 R.drawable.ic_dialog_browser_certificate_secure)
3267 .setView(certificateView)
3268 .setPositiveButton(R.string.ok,
3269 new DialogInterface.OnClickListener() {
3270 public void onClick(DialogInterface dialog,
3271 int whichButton) {
3272 mSSLCertificateDialog = null;
3273 mSSLCertificateView = null;
3274
3275 showPageInfo(tab, false);
3276 }
3277 })
3278 .setOnCancelListener(
3279 new DialogInterface.OnCancelListener() {
3280 public void onCancel(DialogInterface dialog) {
3281 mSSLCertificateDialog = null;
3282 mSSLCertificateView = null;
3283
3284 showPageInfo(tab, false);
3285 }
3286 })
3287 .show();
3288 }
3289
3290 /**
3291 * Displays the SSL error certificate dialog.
3292 * @param view The target web-view.
3293 * @param handler The SSL error handler responsible for cancelling the
3294 * connection that resulted in an SSL error or proceeding per user request.
3295 * @param error The SSL error object.
3296 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003297 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 final WebView view, final SslErrorHandler handler, final SslError error) {
3299
3300 final View certificateView =
3301 inflateCertificateView(error.getCertificate());
3302 if (certificateView == null) {
3303 return;
3304 }
3305
3306 LayoutInflater factory = LayoutInflater.from(this);
3307
3308 final LinearLayout placeholder =
3309 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3310
3311 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3312 LinearLayout ll = (LinearLayout)factory
3313 .inflate(R.layout.ssl_warning, placeholder);
3314 ((TextView)ll.findViewById(R.id.warning))
3315 .setText(R.string.ssl_untrusted);
3316 }
3317
3318 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3319 LinearLayout ll = (LinearLayout)factory
3320 .inflate(R.layout.ssl_warning, placeholder);
3321 ((TextView)ll.findViewById(R.id.warning))
3322 .setText(R.string.ssl_mismatch);
3323 }
3324
3325 if (error.hasError(SslError.SSL_EXPIRED)) {
3326 LinearLayout ll = (LinearLayout)factory
3327 .inflate(R.layout.ssl_warning, placeholder);
3328 ((TextView)ll.findViewById(R.id.warning))
3329 .setText(R.string.ssl_expired);
3330 }
3331
3332 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3333 LinearLayout ll = (LinearLayout)factory
3334 .inflate(R.layout.ssl_warning, placeholder);
3335 ((TextView)ll.findViewById(R.id.warning))
3336 .setText(R.string.ssl_not_yet_valid);
3337 }
3338
3339 mSSLCertificateOnErrorHandler = handler;
3340 mSSLCertificateOnErrorView = view;
3341 mSSLCertificateOnErrorError = error;
3342 mSSLCertificateOnErrorDialog =
3343 new AlertDialog.Builder(this)
3344 .setTitle(R.string.ssl_certificate).setIcon(
3345 R.drawable.ic_dialog_browser_certificate_partially_secure)
3346 .setView(certificateView)
3347 .setPositiveButton(R.string.ok,
3348 new DialogInterface.OnClickListener() {
3349 public void onClick(DialogInterface dialog,
3350 int whichButton) {
3351 mSSLCertificateOnErrorDialog = null;
3352 mSSLCertificateOnErrorView = null;
3353 mSSLCertificateOnErrorHandler = null;
3354 mSSLCertificateOnErrorError = null;
3355
Grace Kloba22ac16e2009-10-07 18:00:23 -07003356 view.getWebViewClient().onReceivedSslError(
3357 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003358 }
3359 })
3360 .setNeutralButton(R.string.page_info_view,
3361 new DialogInterface.OnClickListener() {
3362 public void onClick(DialogInterface dialog,
3363 int whichButton) {
3364 mSSLCertificateOnErrorDialog = null;
3365
3366 // do not clear the dialog state: we will
3367 // need to show the dialog again once the
3368 // user is done exploring the page-info details
3369
3370 showPageInfo(mTabControl.getTabFromView(view),
3371 true);
3372 }
3373 })
3374 .setOnCancelListener(
3375 new DialogInterface.OnCancelListener() {
3376 public void onCancel(DialogInterface dialog) {
3377 mSSLCertificateOnErrorDialog = null;
3378 mSSLCertificateOnErrorView = null;
3379 mSSLCertificateOnErrorHandler = null;
3380 mSSLCertificateOnErrorError = null;
3381
Grace Kloba22ac16e2009-10-07 18:00:23 -07003382 view.getWebViewClient().onReceivedSslError(
3383 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003384 }
3385 })
3386 .show();
3387 }
3388
3389 /**
3390 * Inflates the SSL certificate view (helper method).
3391 * @param certificate The SSL certificate.
3392 * @return The resultant certificate view with issued-to, issued-by,
3393 * issued-on, expires-on, and possibly other fields set.
3394 * If the input certificate is null, returns null.
3395 */
3396 private View inflateCertificateView(SslCertificate certificate) {
3397 if (certificate == null) {
3398 return null;
3399 }
3400
3401 LayoutInflater factory = LayoutInflater.from(this);
3402
3403 View certificateView = factory.inflate(
3404 R.layout.ssl_certificate, null);
3405
3406 // issued to:
3407 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3408 if (issuedTo != null) {
3409 ((TextView) certificateView.findViewById(R.id.to_common))
3410 .setText(issuedTo.getCName());
3411 ((TextView) certificateView.findViewById(R.id.to_org))
3412 .setText(issuedTo.getOName());
3413 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3414 .setText(issuedTo.getUName());
3415 }
3416
3417 // issued by:
3418 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3419 if (issuedBy != null) {
3420 ((TextView) certificateView.findViewById(R.id.by_common))
3421 .setText(issuedBy.getCName());
3422 ((TextView) certificateView.findViewById(R.id.by_org))
3423 .setText(issuedBy.getOName());
3424 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3425 .setText(issuedBy.getUName());
3426 }
3427
3428 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003429 String issuedOn = formatCertificateDate(
3430 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 ((TextView) certificateView.findViewById(R.id.issued_on))
3432 .setText(issuedOn);
3433
3434 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003435 String expiresOn = formatCertificateDate(
3436 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003437 ((TextView) certificateView.findViewById(R.id.expires_on))
3438 .setText(expiresOn);
3439
3440 return certificateView;
3441 }
3442
3443 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003444 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003445 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003446 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003447 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003448 private String formatCertificateDate(Date certificateDate) {
3449 if (certificateDate == null) {
3450 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003451 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003452 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3453 if (formattedDate == null) {
3454 return "";
3455 }
3456 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003457 }
3458
3459 /**
3460 * Displays an http-authentication dialog.
3461 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003462 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003463 final String host, final String realm, final String title,
3464 final String name, final String password, int focusId) {
3465 LayoutInflater factory = LayoutInflater.from(this);
3466 final View v = factory
3467 .inflate(R.layout.http_authentication, null);
3468 if (name != null) {
3469 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3470 }
3471 if (password != null) {
3472 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3473 }
3474
3475 String titleText = title;
3476 if (titleText == null) {
3477 titleText = getText(R.string.sign_in_to).toString().replace(
3478 "%s1", host).replace("%s2", realm);
3479 }
3480
3481 mHttpAuthHandler = handler;
3482 AlertDialog dialog = new AlertDialog.Builder(this)
3483 .setTitle(titleText)
3484 .setIcon(android.R.drawable.ic_dialog_alert)
3485 .setView(v)
3486 .setPositiveButton(R.string.action,
3487 new DialogInterface.OnClickListener() {
3488 public void onClick(DialogInterface dialog,
3489 int whichButton) {
3490 String nm = ((EditText) v
3491 .findViewById(R.id.username_edit))
3492 .getText().toString();
3493 String pw = ((EditText) v
3494 .findViewById(R.id.password_edit))
3495 .getText().toString();
3496 BrowserActivity.this.setHttpAuthUsernamePassword
3497 (host, realm, nm, pw);
3498 handler.proceed(nm, pw);
3499 mHttpAuthenticationDialog = null;
3500 mHttpAuthHandler = null;
3501 }})
3502 .setNegativeButton(R.string.cancel,
3503 new DialogInterface.OnClickListener() {
3504 public void onClick(DialogInterface dialog,
3505 int whichButton) {
3506 handler.cancel();
3507 BrowserActivity.this.resetTitleAndRevertLockIcon();
3508 mHttpAuthenticationDialog = null;
3509 mHttpAuthHandler = null;
3510 }})
3511 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3512 public void onCancel(DialogInterface dialog) {
3513 handler.cancel();
3514 BrowserActivity.this.resetTitleAndRevertLockIcon();
3515 mHttpAuthenticationDialog = null;
3516 mHttpAuthHandler = null;
3517 }})
3518 .create();
3519 // Make the IME appear when the dialog is displayed if applicable.
3520 dialog.getWindow().setSoftInputMode(
3521 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3522 dialog.show();
3523 if (focusId != 0) {
3524 dialog.findViewById(focusId).requestFocus();
3525 } else {
3526 v.findViewById(R.id.username_edit).requestFocus();
3527 }
3528 mHttpAuthenticationDialog = dialog;
3529 }
3530
3531 public int getProgress() {
3532 WebView w = mTabControl.getCurrentWebView();
3533 if (w != null) {
3534 return w.getProgress();
3535 } else {
3536 return 100;
3537 }
3538 }
3539
3540 /**
3541 * Set HTTP authentication password.
3542 *
3543 * @param host The host for the password
3544 * @param realm The realm for the password
3545 * @param username The username for the password. If it is null, it means
3546 * password can't be saved.
3547 * @param password The password
3548 */
3549 public void setHttpAuthUsernamePassword(String host, String realm,
3550 String username,
3551 String password) {
3552 WebView w = mTabControl.getCurrentWebView();
3553 if (w != null) {
3554 w.setHttpAuthUsernamePassword(host, realm, username, password);
3555 }
3556 }
3557
3558 /**
3559 * connectivity manager says net has come or gone... inform the user
3560 * @param up true if net has come up, false if net has gone down
3561 */
3562 public void onNetworkToggle(boolean up) {
3563 if (up == mIsNetworkUp) {
3564 return;
3565 } else if (up) {
3566 mIsNetworkUp = true;
3567 if (mAlertDialog != null) {
3568 mAlertDialog.cancel();
3569 mAlertDialog = null;
3570 }
3571 } else {
3572 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003573 if (mInLoad) {
3574 createAndShowNetworkDialog();
3575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 }
3577 WebView w = mTabControl.getCurrentWebView();
3578 if (w != null) {
3579 w.setNetworkAvailable(up);
3580 }
3581 }
3582
Grace Kloba22ac16e2009-10-07 18:00:23 -07003583 boolean isNetworkUp() {
3584 return mIsNetworkUp;
3585 }
3586
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003587 // This method shows the network dialog alerting the user that the net is
3588 // down. It will only show the dialog if mAlertDialog is null.
3589 private void createAndShowNetworkDialog() {
3590 if (mAlertDialog == null) {
3591 mAlertDialog = new AlertDialog.Builder(this)
3592 .setTitle(R.string.loadSuspendedTitle)
3593 .setMessage(R.string.loadSuspended)
3594 .setPositiveButton(R.string.ok, null)
3595 .show();
3596 }
3597 }
3598
The Android Open Source Project0c908882009-03-03 19:32:16 -08003599 @Override
3600 protected void onActivityResult(int requestCode, int resultCode,
3601 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003602 if (getTopWindow() == null) return;
3603
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 switch (requestCode) {
3605 case COMBO_PAGE:
3606 if (resultCode == RESULT_OK && intent != null) {
3607 String data = intent.getAction();
3608 Bundle extras = intent.getExtras();
3609 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003610 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003612 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003614 dismissSubWindow(currentTab);
3615 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003616 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 }
3618 }
3619 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003620 // Deliberately fall through to PREFERENCES_PAGE, since the
3621 // same extra may be attached to the COMBO_PAGE
3622 case PREFERENCES_PAGE:
3623 if (resultCode == RESULT_OK && intent != null) {
3624 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3625 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3626 mTabControl.removeParentChildRelationShips();
3627 }
3628 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003629 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003630 // Choose a file from the file picker.
3631 case FILE_SELECTED:
3632 if (null == mUploadMessage) break;
3633 Uri result = intent == null || resultCode != RESULT_OK ? null
3634 : intent.getData();
3635 mUploadMessage.onReceiveValue(result);
3636 mUploadMessage = null;
3637 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 default:
3639 break;
3640 }
Leon Scroggins30444232009-09-04 18:36:20 -04003641 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 }
3643
3644 /*
3645 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003646 * menu to see the download window. It shows the download window on top of
3647 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003648 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003649 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650 Intent intent = new Intent(this,
3651 BrowserDownloadPage.class);
3652 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003653 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003654
3655 }
3656
Leon Scroggins160a7e72009-08-14 18:28:01 -04003657 /**
3658 * Open the Go page.
3659 * @param startWithHistory If true, open starting on the history tab.
3660 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003661 */
Leon Scroggins30444232009-09-04 18:36:20 -04003662 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003663 WebView current = mTabControl.getCurrentWebView();
3664 if (current == null) {
3665 return;
3666 }
3667 Intent intent = new Intent(this,
3668 CombinedBookmarkHistoryActivity.class);
3669 String title = current.getTitle();
3670 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003671 Bitmap thumbnail = createScreenshot(current);
3672
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673 // Just in case the user opens bookmarks before a page finishes loading
3674 // so the current history item, and therefore the page, is null.
3675 if (null == url) {
3676 url = mLastEnteredUrl;
3677 // This can happen.
3678 if (null == url) {
3679 url = mSettings.getHomePage();
3680 }
3681 }
3682 // In case the web page has not yet received its associated title.
3683 if (title == null) {
3684 title = url;
3685 }
3686 intent.putExtra("title", title);
3687 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003688 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003689 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003690 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003691 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003692 if (startWithHistory) {
3693 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3694 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3695 }
3696 startActivityForResult(intent, COMBO_PAGE);
3697 }
3698
3699 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003700 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701 // In case the user enters nothing.
3702 if (url != null && url.length() != 0 && view != null) {
3703 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003704 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003705 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003706 }
3707 }
3708 }
3709
Leon Scroggins92472e82010-02-17 16:32:28 -05003710 /**
3711 * Load the URL into the given WebView and update the title bar
3712 * to reflect the new load. Call this instead of WebView.loadUrl
3713 * directly.
3714 * @param view The WebView used to load url.
3715 * @param url The URL to load.
3716 */
3717 private void loadUrl(WebView view, String url) {
3718 updateTitleBarForNewLoad(view, url);
3719 view.loadUrl(url);
3720 }
3721
3722 /**
3723 * Load UrlData into a Tab and update the title bar to reflect the new
3724 * load. Call this instead of UrlData.loadIn directly.
3725 * @param t The Tab used to load.
3726 * @param data The UrlData being loaded.
3727 */
3728 private void loadUrlDataIn(Tab t, UrlData data) {
3729 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3730 data.loadIn(t);
3731 }
3732
3733 /**
3734 * If the WebView is the top window, update the title bar to reflect
3735 * loading the new URL. i.e. set its text, clear the favicon (which
3736 * will be set once the page begins loading), and set the progress to
3737 * INITIAL_PROGRESS to show that the page has begun to load. Called
3738 * by loadUrl and loadUrlDataIn.
3739 * @param view The WebView that is starting a load.
3740 * @param url The URL that is being loaded.
3741 */
3742 private void updateTitleBarForNewLoad(WebView view, String url) {
3743 if (view == getTopWindow()) {
3744 setUrlTitle(url, null);
3745 setFavicon(null);
3746 onProgressChanged(view, INITIAL_PROGRESS);
3747 }
3748 }
3749
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750 private String smartUrlFilter(Uri inUri) {
3751 if (inUri != null) {
3752 return smartUrlFilter(inUri.toString());
3753 }
3754 return null;
3755 }
3756
Feng Qianb34f87a2009-03-24 21:27:26 -07003757 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003758 "(?i)" + // switch on case insensitive matching
3759 "(" + // begin group for schema
3760 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003761 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762 ")" +
3763 "(.*)" );
3764
3765 /**
3766 * Attempts to determine whether user input is a URL or search
3767 * terms. Anything with a space is passed to search.
3768 *
3769 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3770 * "Http://" converts to "http://"
3771 *
3772 * @return Original or modified URL
3773 *
3774 */
3775 String smartUrlFilter(String url) {
3776
3777 String inUrl = url.trim();
3778 boolean hasSpace = inUrl.indexOf(' ') != -1;
3779
3780 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3781 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003782 // force scheme to lowercase
3783 String scheme = matcher.group(1);
3784 String lcScheme = scheme.toLowerCase();
3785 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003786 inUrl = lcScheme + matcher.group(2);
3787 }
3788 if (hasSpace) {
3789 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003790 }
3791 return inUrl;
3792 }
3793 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003794 // FIXME: Is this the correct place to add to searches?
3795 // what if someone else calls this function?
3796 int shortcut = parseUrlShortcut(inUrl);
3797 if (shortcut != SHORTCUT_INVALID) {
3798 Browser.addSearchUrl(mResolver, inUrl);
3799 String query = inUrl.substring(2);
3800 switch (shortcut) {
3801 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003802 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003803 case SHORTCUT_WIKIPEDIA_SEARCH:
3804 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3805 case SHORTCUT_DICTIONARY_SEARCH:
3806 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3807 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003808 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003809 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810 }
3811 }
3812 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003813 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003814 return URLUtil.guessUrl(inUrl);
3815 }
3816 }
3817
3818 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003819 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 }
3821
Ben Murdochbff2d602009-07-01 20:19:05 +01003822 /* package */ void setShouldShowErrorConsole(boolean flag) {
3823 if (flag == mShouldShowErrorConsole) {
3824 // Nothing to do.
3825 return;
3826 }
3827
3828 mShouldShowErrorConsole = flag;
3829
Grace Kloba22ac16e2009-10-07 18:00:23 -07003830 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3831 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003832
3833 if (flag) {
3834 // Setting the show state of the console will cause it's the layout to be inflated.
3835 if (errorConsole.numberOfErrors() > 0) {
3836 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3837 } else {
3838 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3839 }
3840
3841 // Now we can add it to the main view.
3842 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003843 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003844 ViewGroup.LayoutParams.WRAP_CONTENT));
3845 } else {
3846 mErrorConsoleContainer.removeView(errorConsole);
3847 }
3848
3849 }
3850
Grace Kloba22ac16e2009-10-07 18:00:23 -07003851 boolean shouldShowErrorConsole() {
3852 return mShouldShowErrorConsole;
3853 }
3854
Andrei Popescu163ab742009-10-20 17:58:23 +01003855 private void setStatusBarVisibility(boolean visible) {
3856 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3857 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3858 }
3859
Andrei Popescu56199cc2010-01-12 22:39:16 +00003860
3861 private void sendNetworkType(String type, String subtype) {
3862 WebView w = mTabControl.getCurrentWebView();
3863 if (w != null) {
3864 w.setNetworkType(type, subtype);
3865 }
3866 }
3867
Andrei Popescu30995e72010-02-09 16:59:58 +00003868 private void packageChanged(String packageName, boolean wasAdded) {
3869 WebView w = mTabControl.getCurrentWebView();
3870 if (w == null) {
3871 return;
3872 }
3873
3874 if (wasAdded) {
3875 w.addPackageName(packageName);
3876 } else {
3877 w.removePackageName(packageName);
3878 }
3879 }
3880
3881 private void addPackageNames(Set<String> packageNames) {
3882 WebView w = mTabControl.getCurrentWebView();
3883 if (w == null) {
3884 return;
3885 }
3886
3887 w.addPackageNames(packageNames);
3888 }
3889
3890 private void getInstalledPackages() {
3891 AsyncTask<Void, Void, Set<String> > task =
3892 new AsyncTask<Void, Void, Set<String> >() {
3893 protected Set<String> doInBackground(Void... unused) {
3894 Set<String> installedPackages = new HashSet<String>();
3895 PackageManager pm = BrowserActivity.this.getPackageManager();
3896 if (pm != null) {
3897 List<PackageInfo> packages = pm.getInstalledPackages(0);
3898 for (PackageInfo p : packages) {
3899 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3900 installedPackages.add(p.packageName);
3901 }
3902 }
3903 }
3904
3905 return installedPackages;
3906 }
3907
3908 // Executes on the UI thread
3909 protected void onPostExecute(Set<String> installedPackages) {
3910 addPackageNames(installedPackages);
3911 }
3912 };
3913 task.execute();
3914 }
3915
Grace Klobaeb6eef42009-09-15 17:56:32 -07003916 final static int LOCK_ICON_UNSECURE = 0;
3917 final static int LOCK_ICON_SECURE = 1;
3918 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003919
The Android Open Source Project0c908882009-03-03 19:32:16 -08003920 private BrowserSettings mSettings;
3921 private TabControl mTabControl;
3922 private ContentResolver mResolver;
3923 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003924 private View mCustomView;
3925 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003926 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003927
3928 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3929 // view, we should rewrite this.
3930 private int mCurrentMenuState = 0;
3931 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003932 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 private static final int EMPTY_MENU = -1;
3934 private Menu mMenu;
3935
3936 private FindDialog mFindDialog;
3937 // Used to prevent chording to result in firing two shortcuts immediately
3938 // one after another. Fixes bug 1211714.
3939 boolean mCanChord;
3940
3941 private boolean mInLoad;
3942 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003943 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944
The Android Open Source Project0c908882009-03-03 19:32:16 -08003945 private boolean mActivityInPause = true;
3946
3947 private boolean mMenuIsDown;
3948
The Android Open Source Project0c908882009-03-03 19:32:16 -08003949 private static boolean mInTrace;
3950
3951 // Performance probe
3952 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3953 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3956 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3957 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3958 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3959 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3960 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3961 };
3962
3963 private long mStart;
3964 private long mProcessStart;
3965 private long mUserStart;
3966 private long mSystemStart;
3967 private long mIdleStart;
3968 private long mIrqStart;
3969
3970 private long mUiStart;
3971
3972 private Drawable mMixLockIcon;
3973 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003974
3975 /* hold a ref so we can auto-cancel if necessary */
3976 private AlertDialog mAlertDialog;
3977
3978 // Wait for credentials before loading google.com
3979 private ProgressDialog mCredsDlg;
3980
3981 // The up-to-date URL and title (these can be different from those stored
3982 // in WebView, since it takes some time for the information in WebView to
3983 // get updated)
3984 private String mUrl;
3985 private String mTitle;
3986
3987 // As PageInfo has different style for landscape / portrait, we have
3988 // to re-open it when configuration changed
3989 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003990 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3992 // dialog, we should not just dismiss it, but should get back to the
3993 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003994 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003995
3996 // as SSLCertificateOnError has different style for landscape / portrait,
3997 // we have to re-open it when configuration changed
3998 private AlertDialog mSSLCertificateOnErrorDialog;
3999 private WebView mSSLCertificateOnErrorView;
4000 private SslErrorHandler mSSLCertificateOnErrorHandler;
4001 private SslError mSSLCertificateOnErrorError;
4002
4003 // as SSLCertificate has different style for landscape / portrait, we
4004 // have to re-open it when configuration changed
4005 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004006 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004007
4008 // as HttpAuthentication has different style for landscape / portrait, we
4009 // have to re-open it when configuration changed
4010 private AlertDialog mHttpAuthenticationDialog;
4011 private HttpAuthHandler mHttpAuthHandler;
4012
4013 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4014 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004015 ViewGroup.LayoutParams.MATCH_PARENT,
4016 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004017 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4018 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004019 ViewGroup.LayoutParams.MATCH_PARENT,
4020 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004021 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004022 // Google search
4023 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004024 // Wikipedia search
4025 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4026 // Dictionary search
4027 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4028 // Google Mobile Local search
4029 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4030
4031 final static String QUERY_PLACE_HOLDER = "%s";
4032
4033 // "source" parameter for Google search through search key
4034 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4035 // "source" parameter for Google search through goto menu
4036 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4037 // "source" parameter for Google search through simplily type
4038 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4039 // "source" parameter for Google search suggested by the browser
4040 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4041 // "source" parameter for Google search from unknown source
4042 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4043
4044 private final static String LOGTAG = "browser";
4045
The Android Open Source Project0c908882009-03-03 19:32:16 -08004046 private String mLastEnteredUrl;
4047
4048 private PowerManager.WakeLock mWakeLock;
4049 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4050
4051 private Toast mStopToast;
4052
Leon Scroggins68579392009-09-15 15:31:54 -04004053 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004054
Ben Murdochbff2d602009-07-01 20:19:05 +01004055 private LinearLayout mErrorConsoleContainer = null;
4056 private boolean mShouldShowErrorConsole = false;
4057
The Android Open Source Project0c908882009-03-03 19:32:16 -08004058 // As the ids are dynamically created, we can't guarantee that they will
4059 // be in sequence, so this static array maps ids to a window number.
4060 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4061 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4062 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4063 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4064
4065 // monitor platform changes
4066 private IntentFilter mNetworkStateChangedFilter;
4067 private BroadcastReceiver mNetworkStateIntentReceiver;
4068
Grace Klobab4da0ad2009-05-14 14:45:40 -07004069 private BroadcastReceiver mPackageInstallationReceiver;
4070
The Android Open Source Project0c908882009-03-03 19:32:16 -08004071 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004072 final static int COMBO_PAGE = 1;
4073 final static int DOWNLOAD_PAGE = 2;
4074 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004075 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004076
Andrei Popescu540035d2009-09-18 18:59:20 +01004077 // the default <video> poster
4078 private Bitmap mDefaultVideoPoster;
4079 // the video progress view
4080 private View mVideoProgressView;
4081
Andrei Popescu30995e72010-02-09 16:59:58 +00004082 // The Google packages we monitor for the navigator.isApplicationInstalled()
4083 // API. Add as needed.
4084 private static Set<String> sGoogleApps;
4085 static {
4086 sGoogleApps = new HashSet<String>();
4087 sGoogleApps.add("com.google.android.youtube");
4088 }
4089
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004090 /**
4091 * A UrlData class to abstract how the content will be set to WebView.
4092 * This base class uses loadUrl to show the content.
4093 */
4094 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004095 final String mUrl;
4096 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004097 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004098
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004099 UrlData(String url) {
4100 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004101 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004102 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004103 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004104
Leon Scroggins58d56c62010-01-28 15:12:40 -05004105 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004106 this.mUrl = url;
4107 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004108 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4109 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004110 this.mVoiceIntent = intent;
4111 } else {
4112 this.mVoiceIntent = null;
4113 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004114 }
4115
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004116 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004117 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004118 }
4119
Leon Scroggins92472e82010-02-17 16:32:28 -05004120 /**
4121 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4122 * the title bar as well.
4123 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004124 public void loadIn(Tab t) {
4125 if (mVoiceIntent != null) {
4126 t.activateVoiceSearchMode(mVoiceIntent);
4127 } else {
4128 t.getWebView().loadUrl(mUrl, mHeaders);
4129 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004130 }
4131 };
4132
Leon Scroggins1f005d32009-08-10 17:36:42 -04004133 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004134}