blob: 24694082dcf310dd9ade370d92eaca90acfda97c [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
470 startSearch(result, false,
471 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
472 false);
473 }
474
The Android Open Source Project0c908882009-03-03 19:32:16 -0800475 @Override
476 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700477 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800478 // When a tab is closed on exit, the current tab index is set to -1.
479 // Reset before proceed as Browser requires the current tab to be set.
480 if (current == null) {
481 // Try to reset the tab in case the index was incorrect.
482 current = mTabControl.getTab(0);
483 if (current == null) {
484 // No tabs at all so just ignore this intent.
485 return;
486 }
487 mTabControl.setCurrentTab(current);
488 attachTabToContentView(current);
489 resetTitleAndIcon(current.getWebView());
490 }
491 final String action = intent.getAction();
492 final int flags = intent.getFlags();
493 if (Intent.ACTION_MAIN.equals(action) ||
494 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
495 // just resume the browser
496 return;
497 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500498 boolean activateVoiceSearch = RecognizerResultsIntent
499 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800500 if (Intent.ACTION_VIEW.equals(action)
501 || Intent.ACTION_SEARCH.equals(action)
502 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500503 || Intent.ACTION_WEB_SEARCH.equals(action)
504 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500505 if (current.isInVoiceSearchMode()) {
506 String title = current.getVoiceDisplayTitle();
507 if (title != null && title.equals(intent.getStringExtra(
508 SearchManager.QUERY))) {
509 // The user submitted the same search as the last voice
510 // search, so do nothing.
511 return;
512 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500513 if (Intent.ACTION_SEARCH.equals(action)
514 && current.voiceSearchSourceIsGoogle()) {
515 Intent logIntent = new Intent(
516 LoggingEvents.ACTION_LOG_EVENT);
517 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
518 LoggingEvents.VoiceSearch.QUERY_UPDATED);
519 logIntent.putExtra(
520 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
521 intent.getDataString());
522 sendBroadcast(logIntent);
523 // Note, onPageStarted will revert the voice title bar
524 // When http://b/issue?id=2379215 is fixed, we should update
525 // the title bar here.
526 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500527 }
Satish Sampath565505b2009-05-29 15:37:27 +0100528 // If this was a search request (e.g. search query directly typed into the address bar),
529 // pass it on to the default web search provider.
530 if (handleWebSearchIntent(intent)) {
531 return;
532 }
533
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700534 UrlData urlData = getUrlDataFromIntent(intent);
535 if (urlData.isEmpty()) {
536 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800537 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700538
Grace Klobacc634032009-07-28 15:58:19 -0700539 final String appId = intent
540 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500541 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700542 && !getPackageName().equals(appId)
543 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700544 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700545 if (appTab != null) {
546 Log.i(LOGTAG, "Reusing tab for " + appId);
547 // Dismiss the subwindow if applicable.
548 dismissSubWindow(appTab);
549 // Since we might kill the WebView, remove it from the
550 // content view first.
551 removeTabFromContentView(appTab);
552 // Recreate the main WebView after destroying the old one.
553 // If the WebView has the same original url and is on that
554 // page, it can be reused.
555 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700556 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100557
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700558 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400559 switchToTab(mTabControl.getTabIndex(appTab));
560 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500561 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400562 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700563 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400564 // If the tab was the current tab, we have to attach
565 // it to the view system again.
566 attachTabToContentView(appTab);
567 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500568 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700569 }
570 }
571 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400572 } else {
573 // No matching application tab, try to find a regular tab
574 // with a matching url.
575 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400576 if (appTab != null) {
577 if (current != appTab) {
578 switchToTab(mTabControl.getTabIndex(appTab));
579 }
580 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400581 } else {
582 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
583 // will be opened in a new tab unless we have reached
584 // MAX_TABS. Then the url will be opened in the current
585 // tab. If a new tab is created, it will have "true" for
586 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400587 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400588 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700589 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800590 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800591 if (!urlData.isEmpty()
592 && urlData.mUrl.startsWith("about:debug")) {
593 if ("about:debug.dom".equals(urlData.mUrl)) {
594 current.getWebView().dumpDomTree(false);
595 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
596 current.getWebView().dumpDomTree(true);
597 } else if ("about:debug.render".equals(urlData.mUrl)) {
598 current.getWebView().dumpRenderTree(false);
599 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
600 current.getWebView().dumpRenderTree(true);
601 } else if ("about:debug.display".equals(urlData.mUrl)) {
602 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800603 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
604 int index = urlData.mUrl.codePointAt(16) - '0';
605 if (index <= 0 || index > 9) {
606 current.getWebView().setDragTracker(null);
607 } else {
608 current.getWebView().setDragTracker(new MeshTracker(index));
609 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800610 } else {
611 mSettings.toggleDebugSettings();
612 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800613 return;
614 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400615 // Get rid of the subwindow if it exists
616 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500617 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800618 }
619 }
620 }
621
Satish Sampath565505b2009-05-29 15:37:27 +0100622 private int parseUrlShortcut(String url) {
623 if (url == null) return SHORTCUT_INVALID;
624
625 // FIXME: quick search, need to be customized by setting
626 if (url.length() > 2 && url.charAt(1) == ' ') {
627 switch (url.charAt(0)) {
628 case 'g': return SHORTCUT_GOOGLE_SEARCH;
629 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
630 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
631 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
632 }
633 }
634 return SHORTCUT_INVALID;
635 }
636
637 /**
638 * Launches the default web search activity with the query parameters if the given intent's data
639 * are identified as plain search terms and not URLs/shortcuts.
640 * @return true if the intent was handled and web search activity was launched, false if not.
641 */
642 private boolean handleWebSearchIntent(Intent intent) {
643 if (intent == null) return false;
644
645 String url = null;
646 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500647 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
648 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500649 return false;
650 }
Satish Sampath565505b2009-05-29 15:37:27 +0100651 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700652 Uri data = intent.getData();
653 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100654 } else if (Intent.ACTION_SEARCH.equals(action)
655 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
656 || Intent.ACTION_WEB_SEARCH.equals(action)) {
657 url = intent.getStringExtra(SearchManager.QUERY);
658 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100659 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
660 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100661 }
662
663 /**
664 * Launches the default web search activity with the query parameters if the given url string
665 * was identified as plain search terms and not URL/shortcut.
666 * @return true if the request was handled and web search activity was launched, false if not.
667 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100668 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100669 if (inUrl == null) return false;
670
671 // In general, we shouldn't modify URL from Intent.
672 // But currently, we get the user-typed URL from search box as well.
673 String url = fixUrl(inUrl).trim();
674
675 // URLs and site specific search shortcuts are handled by the regular flow of control, so
676 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800677 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100678 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100679 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
680 return false;
681 }
682
683 Browser.updateVisitedHistory(mResolver, url, false);
684 Browser.addSearchUrl(mResolver, url);
685
686 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
687 intent.addCategory(Intent.CATEGORY_DEFAULT);
688 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100689 if (appData != null) {
690 intent.putExtra(SearchManager.APP_DATA, appData);
691 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100692 if (extraData != null) {
693 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
694 }
Grace Klobacc634032009-07-28 15:58:19 -0700695 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100696 startActivity(intent);
697
698 return true;
699 }
700
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700701 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500702 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800703 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 if (intent != null) {
705 final String action = intent.getAction();
706 if (Intent.ACTION_VIEW.equals(action)) {
707 url = smartUrlFilter(intent.getData());
708 if (url != null && url.startsWith("content:")) {
709 /* Append mimetype so webview knows how to display */
710 String mimeType = intent.resolveType(getContentResolver());
711 if (mimeType != null) {
712 url += "?" + mimeType;
713 }
714 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800715 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800716 final Bundle pairs = intent
717 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800718 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800719 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800720 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800721 while (iter.hasNext()) {
722 String key = iter.next();
723 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800724 }
725 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700726 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800727 } else if (Intent.ACTION_SEARCH.equals(action)
728 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
729 || Intent.ACTION_WEB_SEARCH.equals(action)) {
730 url = intent.getStringExtra(SearchManager.QUERY);
731 if (url != null) {
732 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800733 // In general, we shouldn't modify URL from Intent.
734 // But currently, we get the user-typed URL from search box as well.
735 url = fixUrl(url);
736 url = smartUrlFilter(url);
Leon Scrogginsda3e0302010-03-02 16:01:49 -0500737 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
739 if (url.contains(searchSource)) {
740 String source = null;
741 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
742 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000743 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800744 }
745 if (TextUtils.isEmpty(source)) {
746 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
747 }
748 url = url.replace(searchSource, "&source=android-"+source+"&");
749 }
750 }
751 }
752 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500753 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800754 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500755 /* package */ void showVoiceTitleBar(String title) {
756 mTitleBar.setInVoiceMode(true);
757 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800758
Leon Scroggins58d56c62010-01-28 15:12:40 -0500759 mTitleBar.setDisplayTitle(title);
760 mFakeTitleBar.setDisplayTitle(title);
761 }
762 /* package */ void revertVoiceTitleBar() {
763 mTitleBar.setInVoiceMode(false);
764 mFakeTitleBar.setInVoiceMode(false);
765
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500766 mTitleBar.setDisplayTitle(mUrl);
767 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500768 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800769 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400770 // FIXME: Converting the url to lower case
771 // duplicates functionality in smartUrlFilter().
772 // However, changing all current callers of fixUrl to
773 // call smartUrlFilter in addition may have unwanted
774 // consequences, and is deferred for now.
775 int colon = inUrl.indexOf(':');
776 boolean allLower = true;
777 for (int index = 0; index < colon; index++) {
778 char ch = inUrl.charAt(index);
779 if (!Character.isLetter(ch)) {
780 break;
781 }
782 allLower &= Character.isLowerCase(ch);
783 if (index == colon - 1 && !allLower) {
784 inUrl = inUrl.substring(0, colon).toLowerCase()
785 + inUrl.substring(colon);
786 }
787 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800788 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
789 return inUrl;
790 if (inUrl.startsWith("http:") ||
791 inUrl.startsWith("https:")) {
792 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
793 inUrl = inUrl.replaceFirst("/", "//");
794 } else inUrl = inUrl.replaceFirst(":", "://");
795 }
796 return inUrl;
797 }
798
Grace Kloba22ac16e2009-10-07 18:00:23 -0700799 @Override
800 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800801 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700802 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800803 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
804 }
805
806 if (!mActivityInPause) {
807 Log.e(LOGTAG, "BrowserActivity is already resumed.");
808 return;
809 }
810
Mike Reed7bfa63b2009-05-28 11:08:32 -0400811 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800812 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400813 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800814
815 if (mWakeLock.isHeld()) {
816 mHandler.removeMessages(RELEASE_WAKELOCK);
817 mWakeLock.release();
818 }
819
820 if (mCredsDlg != null) {
821 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
822 // In case credential request never comes back
823 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
824 }
825 }
826
827 registerReceiver(mNetworkStateIntentReceiver,
828 mNetworkStateChangedFilter);
829 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800830 }
831
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400832 /**
833 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400834 * would change its appearance, use a different TitleBar to show overlayed
835 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400836 */
837 private TitleBar mFakeTitleBar;
838
839 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400840 * Holder for the fake title bar. It will have a foreground shadow, as well
841 * as a white background, so the fake title bar looks like the real one.
842 */
843 private ViewGroup mFakeTitleBarHolder;
844
845 /**
846 * Layout parameters for the fake title bar within mFakeTitleBarHolder
847 */
848 private FrameLayout.LayoutParams mFakeTitleBarParams
849 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800850 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400851 ViewGroup.LayoutParams.WRAP_CONTENT);
852 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 * Keeps track of whether the options menu is open. This is important in
854 * determining whether to show or hide the title bar overlay.
855 */
856 private boolean mOptionsMenuOpen;
857
858 /**
859 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
860 * of whether the configuration has changed. The first onMenuOpened call
861 * after a configuration change is simply a reopening of the same menu
862 * (i.e. mIconView did not change).
863 */
864 private boolean mConfigChanged;
865
866 /**
867 * Whether or not the options menu is in its smaller, icon menu form. When
868 * true, we want the title bar overlay to be up. When false, we do not.
869 * Only meaningful if mOptionsMenuOpen is true.
870 */
871 private boolean mIconView;
872
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400873 @Override
874 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400875 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
876 if (mOptionsMenuOpen) {
877 if (mConfigChanged) {
878 // We do not need to make any changes to the state of the
879 // title bar, since the only thing that happened was a
880 // change in orientation
881 mConfigChanged = false;
882 } else {
883 if (mIconView) {
884 // Switching the menu to expanded view, so hide the
885 // title bar.
886 hideFakeTitleBar();
887 mIconView = false;
888 } else {
889 // Switching the menu back to icon view, so show the
890 // title bar once again.
891 showFakeTitleBar();
892 mIconView = true;
893 }
894 }
895 } else {
896 // The options menu is closed, so open it, and show the title
897 showFakeTitleBar();
898 mOptionsMenuOpen = true;
899 mConfigChanged = false;
900 mIconView = true;
901 }
902 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400903 return true;
904 }
905
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400906 /**
907 * Special class used exclusively for the shadow drawn underneath the fake
908 * title bar. The shadow does not need to be drawn if the WebView
909 * underneath is scrolled to the top, because it will draw directly on top
910 * of the embedded shadow.
911 */
912 private static class Shadow extends View {
913 private WebView mWebView;
914
915 public Shadow(Context context, AttributeSet attrs) {
916 super(context, attrs);
917 }
918
919 public void setWebView(WebView view) {
920 mWebView = view;
921 }
922
923 @Override
924 public void draw(Canvas canvas) {
925 // In general onDraw is the method to override, but we care about
926 // whether or not the background gets drawn, which happens in draw()
927 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
928 super.draw(canvas);
929 }
930 // Need to invalidate so that if the scroll position changes, we
931 // still draw as appropriate.
932 invalidate();
933 }
934 }
935
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400936 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400937 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400938 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400939 && !mActivityInPause && decor != null
940 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400941 Rect visRect = new Rect();
942 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
943 if (LOGD_ENABLED) {
944 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
945 }
946 return;
947 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400948
949 WindowManager manager
950 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
951
952 // Add the title bar to the window manager so it can receive touches
953 // while the menu is up
954 WindowManager.LayoutParams params
955 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800956 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 ViewGroup.LayoutParams.WRAP_CONTENT,
958 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
959 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400960 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400961 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400962 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400963 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400964 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400965 // XXX : Without providing an offset, the fake title bar will be
966 // placed underneath the status bar. Use the global visible rect
967 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400968 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400969 // Add a holder for the title bar. It also holds a shadow to show
970 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400971 if (mFakeTitleBarHolder == null) {
972 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
973 .inflate(R.layout.title_bar_bg, null);
974 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400975 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
976 R.id.shadow);
977 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400978 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400979 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400980 }
981 }
982
983 @Override
984 public void onOptionsMenuClosed(Menu menu) {
985 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400986 if (!mInLoad) {
987 hideFakeTitleBar();
988 } else if (!mIconView) {
989 // The page is currently loading, and we are in expanded mode, so
990 // we were not showing the menu. Show it once again. It will be
991 // removed when the page finishes.
992 showFakeTitleBar();
993 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400994 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700995
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400996 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400997 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400998 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
999 mFakeTitleBarHolder.getLayoutParams();
1000 WebView mainView = mTabControl.getCurrentWebView();
1001 // Although we decided whether or not to animate based on the current
1002 // scroll position, the scroll position may have changed since the
1003 // fake title bar was displayed. Make sure it has the appropriate
1004 // animation/lack thereof before removing.
1005 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -04001006 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001007 WindowManager manager
1008 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001009 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001010 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1011 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001012 }
1013
The Android Open Source Project0c908882009-03-03 19:32:16 -08001014 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001015 * Special method for the fake title bar to call when displaying its context
1016 * menu, since it is in its own Window, and its parent does not show a
1017 * context menu.
1018 */
1019 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001020 if (null == mTitleBar.getParent()) {
1021 return;
1022 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001023 openContextMenu(mTitleBar);
1024 }
1025
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001026 @Override
1027 public void onContextMenuClosed(Menu menu) {
1028 super.onContextMenuClosed(menu);
1029 if (mInLoad) {
1030 showFakeTitleBar();
1031 }
1032 }
1033
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001034 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001035 * onSaveInstanceState(Bundle map)
1036 * onSaveInstanceState is called right before onStop(). The map contains
1037 * the saved state.
1038 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001039 @Override
1040 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001041 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001042 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1043 }
1044 // the default implementation requires each view to have an id. As the
1045 // browser handles the state itself and it doesn't use id for the views,
1046 // don't call the default implementation. Otherwise it will trigger the
1047 // warning like this, "couldn't save which view has focus because the
1048 // focused view XXX has no id".
1049
1050 // Save all the tabs
1051 mTabControl.saveState(outState);
1052 }
1053
Grace Kloba22ac16e2009-10-07 18:00:23 -07001054 @Override
1055 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 super.onPause();
1057
1058 if (mActivityInPause) {
1059 Log.e(LOGTAG, "BrowserActivity is already paused.");
1060 return;
1061 }
1062
Mike Reed7bfa63b2009-05-28 11:08:32 -04001063 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001065 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 mWakeLock.acquire();
1067 mHandler.sendMessageDelayed(mHandler
1068 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1069 }
1070
1071 // Clear the credentials toast if it is up
1072 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1073 mCredsDlg.dismiss();
1074 }
1075 mCredsDlg = null;
1076
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001077 // FIXME: This removes the active tabs page and resets the menu to
1078 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1079 // but then we would need to save it in onSaveInstanceState and restore
1080 // it in onCreate/onRestoreInstanceState
1081 if (mActiveTabsPage != null) {
1082 removeActiveTabPage(true);
1083 }
1084
The Android Open Source Project0c908882009-03-03 19:32:16 -08001085 cancelStopToast();
1086
1087 // unregister network state listener
1088 unregisterReceiver(mNetworkStateIntentReceiver);
1089 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 }
1091
Grace Kloba22ac16e2009-10-07 18:00:23 -07001092 @Override
1093 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001094 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1096 }
1097 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001098
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001099 if (mUploadMessage != null) {
1100 mUploadMessage.onReceiveValue(null);
1101 mUploadMessage = null;
1102 }
1103
Grace Kloba0923d692009-09-23 21:37:25 -07001104 if (mTabControl == null) return;
1105
Grace Kloba1fc98a32009-10-21 13:23:08 -07001106 // Remove the fake title bar if it is there
1107 hideFakeTitleBar();
1108
The Android Open Source Project0c908882009-03-03 19:32:16 -08001109 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001110 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001111 if (t != null) {
1112 dismissSubWindow(t);
1113 removeTabFromContentView(t);
1114 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001115 // Destroy all the tabs
1116 mTabControl.destroy();
1117 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001118
Grace Klobab4da0ad2009-05-14 14:45:40 -07001119 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001120 }
1121
1122 @Override
1123 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001124 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 super.onConfigurationChanged(newConfig);
1126
1127 if (mPageInfoDialog != null) {
1128 mPageInfoDialog.dismiss();
1129 showPageInfo(
1130 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001131 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001132 }
1133 if (mSSLCertificateDialog != null) {
1134 mSSLCertificateDialog.dismiss();
1135 showSSLCertificate(
1136 mSSLCertificateView);
1137 }
1138 if (mSSLCertificateOnErrorDialog != null) {
1139 mSSLCertificateOnErrorDialog.dismiss();
1140 showSSLCertificateOnError(
1141 mSSLCertificateOnErrorView,
1142 mSSLCertificateOnErrorHandler,
1143 mSSLCertificateOnErrorError);
1144 }
1145 if (mHttpAuthenticationDialog != null) {
1146 String title = ((TextView) mHttpAuthenticationDialog
1147 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1148 .toString();
1149 String name = ((TextView) mHttpAuthenticationDialog
1150 .findViewById(R.id.username_edit)).getText().toString();
1151 String password = ((TextView) mHttpAuthenticationDialog
1152 .findViewById(R.id.password_edit)).getText().toString();
1153 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1154 .getId();
1155 mHttpAuthenticationDialog.dismiss();
1156 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1157 name, password, focusId);
1158 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001159 }
1160
Grace Kloba22ac16e2009-10-07 18:00:23 -07001161 @Override
1162 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 super.onLowMemory();
1164 mTabControl.freeMemory();
1165 }
1166
Mike Reed7bfa63b2009-05-28 11:08:32 -04001167 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001168 Tab tab = mTabControl.getCurrentTab();
1169 boolean inLoad = tab.inLoad();
1170 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001171 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001172 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001173 if (w != null) {
1174 w.resumeTimers();
1175 }
1176 return true;
1177 } else {
1178 return false;
1179 }
1180 }
1181
Mike Reed7bfa63b2009-05-28 11:08:32 -04001182 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001183 Tab tab = mTabControl.getCurrentTab();
1184 boolean inLoad = tab.inLoad();
1185 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 CookieSyncManager.getInstance().stopSync();
1187 WebView w = mTabControl.getCurrentWebView();
1188 if (w != null) {
1189 w.pauseTimers();
1190 }
1191 return true;
1192 } else {
1193 return false;
1194 }
1195 }
1196
Leon Scroggins1f005d32009-08-10 17:36:42 -04001197 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001198 /*
1199 * This function is called when we are launching for the first time. We
1200 * are waiting for the login credentials before loading Google home
1201 * pages. This way the user will be logged in straight away.
1202 */
1203 private void waitForCredentials() {
1204 // Show a toast
1205 mCredsDlg = new ProgressDialog(this);
1206 mCredsDlg.setIndeterminate(true);
1207 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1208 // If the user cancels the operation, then cancel the Google
1209 // Credentials request.
1210 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1211 mCredsDlg.show();
1212
1213 // We set a timeout for the retrieval of credentials in onResume()
1214 // as that is when we have freed up some CPU time to get
1215 // the login credentials.
1216 }
1217
1218 /*
1219 * If we have received the credentials or we have timed out and we are
1220 * showing the credentials dialog, then it is time to move on.
1221 */
1222 private void resumeAfterCredentials() {
1223 if (mCredsDlg == null) {
1224 return;
1225 }
1226
1227 // Clear the toast
1228 if (mCredsDlg.isShowing()) {
1229 mCredsDlg.dismiss();
1230 }
1231 mCredsDlg = null;
1232
1233 // Clear any pending timeout
1234 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1235
1236 // Load the page
1237 WebView w = mTabControl.getCurrentWebView();
1238 if (w != null) {
Leon Scroggins92472e82010-02-17 16:32:28 -05001239 loadUrl(w, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001240 }
1241
1242 // Update the settings, need to do this last as it can take a moment
1243 // to persist the settings. In the mean time we could be loading
1244 // content.
1245 mSettings.setLoginInitialized(this);
1246 }
1247
1248 // Open the icon database and retain all the icons for visited sites.
1249 private void retainIconsOnStartup() {
1250 final WebIconDatabase db = WebIconDatabase.getInstance();
1251 db.open(getDir("icons", 0).getPath());
1252 try {
1253 Cursor c = Browser.getAllBookmarks(mResolver);
1254 if (!c.moveToFirst()) {
1255 c.deactivate();
1256 return;
1257 }
1258 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1259 do {
1260 String url = c.getString(urlIndex);
1261 db.retainIconForPageUrl(url);
1262 } while (c.moveToNext());
1263 c.deactivate();
1264 } catch (IllegalStateException e) {
1265 Log.e(LOGTAG, "retainIconsOnStartup", e);
1266 }
1267 }
1268
1269 // Helper method for getting the top window.
1270 WebView getTopWindow() {
1271 return mTabControl.getCurrentTopWebView();
1272 }
1273
Grace Kloba22ac16e2009-10-07 18:00:23 -07001274 TabControl getTabControl() {
1275 return mTabControl;
1276 }
1277
The Android Open Source Project0c908882009-03-03 19:32:16 -08001278 @Override
1279 public boolean onCreateOptionsMenu(Menu menu) {
1280 super.onCreateOptionsMenu(menu);
1281
1282 MenuInflater inflater = getMenuInflater();
1283 inflater.inflate(R.menu.browser, menu);
1284 mMenu = menu;
1285 updateInLoadMenuItems();
1286 return true;
1287 }
1288
1289 /**
1290 * As the menu can be open when loading state changes
1291 * we must manually update the state of the stop/reload menu
1292 * item
1293 */
1294 private void updateInLoadMenuItems() {
1295 if (mMenu == null) {
1296 return;
1297 }
1298 MenuItem src = mInLoad ?
1299 mMenu.findItem(R.id.stop_menu_id):
1300 mMenu.findItem(R.id.reload_menu_id);
1301 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1302 dest.setIcon(src.getIcon());
1303 dest.setTitle(src.getTitle());
1304 }
1305
1306 @Override
1307 public boolean onContextItemSelected(MenuItem item) {
1308 // chording is not an issue with context menus, but we use the same
1309 // options selector, so set mCanChord to true so we can access them.
1310 mCanChord = true;
1311 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001312 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001314 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001315 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001316 Tab currentTab = mTabControl.getCurrentTab();
1317 if (null == currentTab) {
1318 result = false;
1319 break;
1320 }
1321 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001322 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001323 result = false;
1324 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001325 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001326 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001327 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001328 // -- Browser context menu
1329 case R.id.open_context_menu_id:
1330 case R.id.open_newtab_context_menu_id:
1331 case R.id.bookmark_context_menu_id:
1332 case R.id.save_link_context_menu_id:
1333 case R.id.share_link_context_menu_id:
1334 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001335 final WebView webView = getTopWindow();
1336 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001337 result = false;
1338 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001339 }
1340 final HashMap hrefMap = new HashMap();
1341 hrefMap.put("webview", webView);
1342 final Message msg = mHandler.obtainMessage(
1343 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 webView.requestFocusNodeHref(msg);
1345 break;
1346
1347 default:
1348 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001349 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001350 }
1351 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001352 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001353 }
1354
1355 private Bundle createGoogleSearchSourceBundle(String source) {
1356 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001357 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 return bundle;
1359 }
1360
Leon Scroggins8ad29922010-02-16 12:33:55 -05001361 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001362 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001363 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001364 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001365 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 }
1367
Leon Scroggins8ad29922010-02-16 12:33:55 -05001368 /**
1369 * Overriding this to insert a local information bundle
1370 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001371 @Override
1372 public void startSearch(String initialQuery, boolean selectInitialQuery,
1373 Bundle appSearchData, boolean globalSearch) {
1374 if (appSearchData == null) {
1375 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1376 }
1377 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1378 }
1379
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 /**
1381 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1382 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001383 * @param index Index of the tab to change to, as defined by
1384 * mTabControl.getTabIndex(Tab t).
1385 * @return boolean True if we successfully switched to a different tab. If
1386 * the indexth tab is null, or if that tab is the same as
1387 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001389 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001390 Tab tab = mTabControl.getTab(index);
1391 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001393 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001394 }
1395 if (currentTab != null) {
1396 // currentTab may be null if it was just removed. In that case,
1397 // we do not need to remove it
1398 removeTabFromContentView(currentTab);
1399 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 mTabControl.setCurrentTab(tab);
1401 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001402 resetTitleIconAndProgress();
1403 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001404 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001405 }
1406
Grace Kloba22ac16e2009-10-07 18:00:23 -07001407 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001408 return openTabAndShow(mSettings.getHomePage(), false, null);
1409 }
1410
Leon Scroggins1f005d32009-08-10 17:36:42 -04001411 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001412 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001413 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001414 // This is the last tab. Open a new one, with the home
1415 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001416 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001417 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001418 return;
1419 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001420 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001421 int indexToShow = -1;
1422 if (parent != null) {
1423 indexToShow = mTabControl.getTabIndex(parent);
1424 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001425 final int currentIndex = mTabControl.getCurrentIndex();
1426 // Try to move to the tab to the right
1427 indexToShow = currentIndex + 1;
1428 if (indexToShow > mTabControl.getTabCount() - 1) {
1429 // Try to move to the tab to the left
1430 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001431 }
1432 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001433 if (switchToTab(indexToShow)) {
1434 // Close window
1435 closeTab(current);
1436 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001437 }
1438
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001439 private ActiveTabsPage mActiveTabsPage;
1440
1441 /**
1442 * Remove the active tabs page.
1443 * @param needToAttach If true, the active tabs page did not attach a tab
1444 * to the content view, so we need to do that here.
1445 */
1446 /* package */ void removeActiveTabPage(boolean needToAttach) {
1447 mContentView.removeView(mActiveTabsPage);
1448 mActiveTabsPage = null;
1449 mMenuState = R.id.MAIN_MENU;
1450 if (needToAttach) {
1451 attachTabToContentView(mTabControl.getCurrentTab());
1452 }
1453 getTopWindow().requestFocus();
1454 }
1455
The Android Open Source Project0c908882009-03-03 19:32:16 -08001456 @Override
1457 public boolean onOptionsItemSelected(MenuItem item) {
1458 if (!mCanChord) {
1459 // The user has already fired a shortcut with this hold down of the
1460 // menu key.
1461 return false;
1462 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001463 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001464 return false;
1465 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001466 if (mMenuIsDown) {
1467 // The shortcut action consumes the MENU. Even if it is still down,
1468 // it won't trigger the next shortcut action. In the case of the
1469 // shortcut action triggering a new activity, like Bookmarks, we
1470 // won't get onKeyUp for MENU. So it is important to reset it here.
1471 mMenuIsDown = false;
1472 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 switch (item.getItemId()) {
1474 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001475 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001476 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001477 break;
1478
Leon Scroggins64b80f32009-08-07 12:03:34 -04001479 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001480 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001481 break;
1482
1483 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001484 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001485 break;
1486
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001487 case R.id.active_tabs_menu_id:
1488 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1489 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001490 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001491 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1492 mActiveTabsPage.requestFocus();
1493 mMenuState = EMPTY_MENU;
1494 break;
1495
Leon Scroggins1f005d32009-08-10 17:36:42 -04001496 case R.id.add_bookmark_menu_id:
1497 Intent i = new Intent(BrowserActivity.this,
1498 AddBookmarkPage.class);
1499 WebView w = getTopWindow();
1500 i.putExtra("url", w.getUrl());
1501 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001502 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001503 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001504 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001505 break;
1506
1507 case R.id.stop_reload_menu_id:
1508 if (mInLoad) {
1509 stopLoading();
1510 } else {
1511 getTopWindow().reload();
1512 }
1513 break;
1514
1515 case R.id.back_menu_id:
1516 getTopWindow().goBack();
1517 break;
1518
1519 case R.id.forward_menu_id:
1520 getTopWindow().goForward();
1521 break;
1522
1523 case R.id.close_menu_id:
1524 // Close the subwindow if it exists.
1525 if (mTabControl.getCurrentSubWindow() != null) {
1526 dismissSubWindow(mTabControl.getCurrentTab());
1527 break;
1528 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001529 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001530 break;
1531
1532 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001533 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 if (current != null) {
1535 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001536 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 }
1538 break;
1539
1540 case R.id.preferences_menu_id:
1541 Intent intent = new Intent(this,
1542 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001543 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1544 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 startActivityForResult(intent, PREFERENCES_PAGE);
1546 break;
1547
1548 case R.id.find_menu_id:
1549 if (null == mFindDialog) {
1550 mFindDialog = new FindDialog(this);
1551 }
1552 mFindDialog.setWebView(getTopWindow());
1553 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001554 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001555 mMenuState = EMPTY_MENU;
1556 break;
1557
1558 case R.id.select_text_id:
1559 getTopWindow().emulateShiftHeld();
1560 break;
1561 case R.id.page_info_menu_id:
1562 showPageInfo(mTabControl.getCurrentTab(), false);
1563 break;
1564
1565 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001566 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001567 break;
1568
Leon Scroggins96afcb12009-12-10 12:35:56 -05001569 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001571 Tab currentTab = mTabControl.getCurrentTab();
1572 if (null == currentTab) {
1573 mCanChord = false;
1574 return false;
1575 }
1576 currentTab.populatePickerData();
1577 sharePage(this, currentTab.getTitle(),
1578 currentTab.getUrl(), currentTab.getFavicon(),
1579 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001580 break;
1581
1582 case R.id.dump_nav_menu_id:
1583 getTopWindow().debugDump();
1584 break;
1585
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001586 case R.id.dump_counters_menu_id:
1587 getTopWindow().dumpV8Counters();
1588 break;
1589
The Android Open Source Project0c908882009-03-03 19:32:16 -08001590 case R.id.zoom_in_menu_id:
1591 getTopWindow().zoomIn();
1592 break;
1593
1594 case R.id.zoom_out_menu_id:
1595 getTopWindow().zoomOut();
1596 break;
1597
1598 case R.id.view_downloads_menu_id:
1599 viewDownloads(null);
1600 break;
1601
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 case R.id.window_one_menu_id:
1603 case R.id.window_two_menu_id:
1604 case R.id.window_three_menu_id:
1605 case R.id.window_four_menu_id:
1606 case R.id.window_five_menu_id:
1607 case R.id.window_six_menu_id:
1608 case R.id.window_seven_menu_id:
1609 case R.id.window_eight_menu_id:
1610 {
1611 int menuid = item.getItemId();
1612 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1613 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001614 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001615 if (desiredTab != null &&
1616 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001617 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 }
1619 break;
1620 }
1621 }
1622 }
1623 break;
1624
1625 default:
1626 if (!super.onOptionsItemSelected(item)) {
1627 return false;
1628 }
1629 // Otherwise fall through.
1630 }
1631 mCanChord = false;
1632 return true;
1633 }
1634
1635 public void closeFind() {
1636 mMenuState = R.id.MAIN_MENU;
1637 }
1638
Grace Kloba22ac16e2009-10-07 18:00:23 -07001639 @Override
1640 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 // This happens when the user begins to hold down the menu key, so
1642 // allow them to chord to get a shortcut.
1643 mCanChord = true;
1644 // Note: setVisible will decide whether an item is visible; while
1645 // setEnabled() will decide whether an item is enabled, which also means
1646 // whether the matching shortcut key will function.
1647 super.onPrepareOptionsMenu(menu);
1648 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001649 case EMPTY_MENU:
1650 if (mCurrentMenuState != mMenuState) {
1651 menu.setGroupVisible(R.id.MAIN_MENU, false);
1652 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1653 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001654 }
1655 break;
1656 default:
1657 if (mCurrentMenuState != mMenuState) {
1658 menu.setGroupVisible(R.id.MAIN_MENU, true);
1659 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1660 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001661 }
1662 final WebView w = getTopWindow();
1663 boolean canGoBack = false;
1664 boolean canGoForward = false;
1665 boolean isHome = false;
1666 if (w != null) {
1667 canGoBack = w.canGoBack();
1668 canGoForward = w.canGoForward();
1669 isHome = mSettings.getHomePage().equals(w.getUrl());
1670 }
1671 final MenuItem back = menu.findItem(R.id.back_menu_id);
1672 back.setEnabled(canGoBack);
1673
1674 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1675 home.setEnabled(!isHome);
1676
1677 menu.findItem(R.id.forward_menu_id)
1678 .setEnabled(canGoForward);
1679
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001680 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001681 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001682
The Android Open Source Project0c908882009-03-03 19:32:16 -08001683 // decide whether to show the share link option
1684 PackageManager pm = getPackageManager();
1685 Intent send = new Intent(Intent.ACTION_SEND);
1686 send.setType("text/plain");
1687 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1688 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1689
The Android Open Source Project0c908882009-03-03 19:32:16 -08001690 boolean isNavDump = mSettings.isNavDump();
1691 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1692 nav.setVisible(isNavDump);
1693 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001694
1695 boolean showDebugSettings = mSettings.showDebugSettings();
1696 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1697 counter.setVisible(showDebugSettings);
1698 counter.setEnabled(showDebugSettings);
1699
The Android Open Source Project0c908882009-03-03 19:32:16 -08001700 break;
1701 }
1702 mCurrentMenuState = mMenuState;
1703 return true;
1704 }
1705
1706 @Override
1707 public void onCreateContextMenu(ContextMenu menu, View v,
1708 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001709 if (v instanceof TitleBar) {
1710 return;
1711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 WebView webview = (WebView) v;
1713 WebView.HitTestResult result = webview.getHitTestResult();
1714 if (result == null) {
1715 return;
1716 }
1717
1718 int type = result.getType();
1719 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1720 Log.w(LOGTAG,
1721 "We should not show context menu when nothing is touched");
1722 return;
1723 }
1724 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1725 // let TextView handles context menu
1726 return;
1727 }
1728
1729 // Note, http://b/issue?id=1106666 is requesting that
1730 // an inflated menu can be used again. This is not available
1731 // yet, so inflate each time (yuk!)
1732 MenuInflater inflater = getMenuInflater();
1733 inflater.inflate(R.menu.browsercontext, menu);
1734
1735 // Show the correct menu group
1736 String extra = result.getExtra();
1737 menu.setGroupVisible(R.id.PHONE_MENU,
1738 type == WebView.HitTestResult.PHONE_TYPE);
1739 menu.setGroupVisible(R.id.EMAIL_MENU,
1740 type == WebView.HitTestResult.EMAIL_TYPE);
1741 menu.setGroupVisible(R.id.GEO_MENU,
1742 type == WebView.HitTestResult.GEO_TYPE);
1743 menu.setGroupVisible(R.id.IMAGE_MENU,
1744 type == WebView.HitTestResult.IMAGE_TYPE
1745 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1746 menu.setGroupVisible(R.id.ANCHOR_MENU,
1747 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1748 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1749
1750 // Setup custom handling depending on the type
1751 switch (type) {
1752 case WebView.HitTestResult.PHONE_TYPE:
1753 menu.setHeaderTitle(Uri.decode(extra));
1754 menu.findItem(R.id.dial_context_menu_id).setIntent(
1755 new Intent(Intent.ACTION_VIEW, Uri
1756 .parse(WebView.SCHEME_TEL + extra)));
1757 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1758 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001759 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001760 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1761 addIntent);
1762 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1763 new Copy(extra));
1764 break;
1765
1766 case WebView.HitTestResult.EMAIL_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.email_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_MAILTO + extra)));
1771 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1772 new Copy(extra));
1773 break;
1774
1775 case WebView.HitTestResult.GEO_TYPE:
1776 menu.setHeaderTitle(extra);
1777 menu.findItem(R.id.map_context_menu_id).setIntent(
1778 new Intent(Intent.ACTION_VIEW, Uri
1779 .parse(WebView.SCHEME_GEO
1780 + URLEncoder.encode(extra))));
1781 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1782 new Copy(extra));
1783 break;
1784
1785 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1786 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1787 TextView titleView = (TextView) LayoutInflater.from(this)
1788 .inflate(android.R.layout.browser_link_context_header,
1789 null);
1790 titleView.setText(extra);
1791 menu.setHeaderView(titleView);
1792 // decide whether to show the open link in new tab option
1793 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001794 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001795 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1796 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 PackageManager pm = getPackageManager();
1798 Intent send = new Intent(Intent.ACTION_SEND);
1799 send.setType("text/plain");
1800 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1801 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1802 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1803 break;
1804 }
1805 // otherwise fall through to handle image part
1806 case WebView.HitTestResult.IMAGE_TYPE:
1807 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1808 menu.setHeaderTitle(extra);
1809 }
1810 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1811 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1812 menu.findItem(R.id.download_context_menu_id).
1813 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001814 menu.findItem(R.id.set_wallpaper_context_menu_id).
1815 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 break;
1817
1818 default:
1819 Log.w(LOGTAG, "We should not get here.");
1820 break;
1821 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001822 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001823 }
1824
The Android Open Source Project0c908882009-03-03 19:32:16 -08001825 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001826 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001827 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001828 // Attach the container that contains the main WebView and any other UI
1829 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001830 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001831
1832 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001833 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001834 if (errorConsole.numberOfErrors() == 0) {
1835 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1836 } else {
1837 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1838 }
1839
1840 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001841 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001842 ViewGroup.LayoutParams.WRAP_CONTENT));
1843 }
1844
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001845 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001846 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001847 if (t.isInVoiceSearchMode()) {
1848 showVoiceTitleBar(t.getVoiceDisplayTitle());
1849 } else {
1850 revertVoiceTitleBar();
1851 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 // Request focus on the top window.
1853 t.getTopWindow().requestFocus();
1854 }
1855
1856 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001857 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001858 t.attachSubWindow(mContentView);
1859 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001860 }
1861
1862 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001863 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001864 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001865 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001866
Grace Kloba22ac16e2009-10-07 18:00:23 -07001867 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1868 if (errorConsole != null) {
1869 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001870 }
1871
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001872 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001873 if (view != null) {
1874 view.setEmbeddedTitleBar(null);
1875 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877
1878 // Remove the sub window if it exists. Also called by TabControl when the
1879 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001880 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001881 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001882 // dismiss the subwindow. This will destroy the WebView.
1883 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001884 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
1886
Leon Scroggins1f005d32009-08-10 17:36:42 -04001887 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001888 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001889 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001890 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 }
1892
1893 // This method does a ton of stuff. It will attempt to create a new tab
1894 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001895 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001896 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1897 String appId) {
1898 final Tab currentTab = mTabControl.getCurrentTab();
1899 if (mTabControl.canCreateNewTab()) {
1900 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1901 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001902 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001903 // If the last tab was removed from the active tabs page, currentTab
1904 // will be null.
1905 if (currentTab != null) {
1906 removeTabFromContentView(currentTab);
1907 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001908 // We must set the new tab as the current tab to reflect the old
1909 // animation behavior.
1910 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001911 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001912 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001913 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001914 }
1915 return tab;
1916 } else {
1917 // Get rid of the subwindow if it exists
1918 dismissSubWindow(currentTab);
1919 if (!urlData.isEmpty()) {
1920 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001921 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001923 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 }
1925 }
1926
Grace Kloba22ac16e2009-10-07 18:00:23 -07001927 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001928 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001929 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001930 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001931 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001932 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 }
Grace Klobac9181842009-04-14 08:53:22 -07001934 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001936 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001937 }
1938 }
1939
1940 private class Copy implements OnMenuItemClickListener {
1941 private CharSequence mText;
1942
1943 public boolean onMenuItemClick(MenuItem item) {
1944 copy(mText);
1945 return true;
1946 }
1947
1948 public Copy(CharSequence toCopy) {
1949 mText = toCopy;
1950 }
1951 }
1952
1953 private class Download implements OnMenuItemClickListener {
1954 private String mText;
1955
1956 public boolean onMenuItemClick(MenuItem item) {
1957 onDownloadStartNoStream(mText, null, null, null, -1);
1958 return true;
1959 }
1960
1961 public Download(String toDownload) {
1962 mText = toDownload;
1963 }
1964 }
1965
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001966 private class SetAsWallpaper extends Thread implements
1967 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1968 private URL mUrl;
1969 private ProgressDialog mWallpaperProgress;
1970 private boolean mCanceled = false;
1971
1972 public SetAsWallpaper(String url) {
1973 try {
1974 mUrl = new URL(url);
1975 } catch (MalformedURLException e) {
1976 mUrl = null;
1977 }
1978 }
1979
1980 public void onCancel(DialogInterface dialog) {
1981 mCanceled = true;
1982 }
1983
1984 public boolean onMenuItemClick(MenuItem item) {
1985 if (mUrl != null) {
1986 // The user may have tried to set a image with a large file size as their
1987 // background so it may take a few moments to perform the operation. Display
1988 // a progress spinner while it is working.
1989 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1990 mWallpaperProgress.setIndeterminate(true);
1991 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1992 mWallpaperProgress.setCancelable(true);
1993 mWallpaperProgress.setOnCancelListener(this);
1994 mWallpaperProgress.show();
1995 start();
1996 }
1997 return true;
1998 }
1999
2000 public void run() {
2001 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2002 try {
2003 // TODO: This will cause the resource to be downloaded again, when we
2004 // should in most cases be able to grab it from the cache. To fix this
2005 // we should query WebCore to see if we can access a cached version and
2006 // instead open an input stream on that. This pattern could also be used
2007 // in the download manager where the same problem exists.
2008 InputStream inputstream = mUrl.openStream();
2009 if (inputstream != null) {
2010 setWallpaper(inputstream);
2011 }
2012 } catch (IOException e) {
2013 Log.e(LOGTAG, "Unable to set new wallpaper");
2014 // Act as though the user canceled the operation so we try to
2015 // restore the old wallpaper.
2016 mCanceled = true;
2017 }
2018
2019 if (mCanceled) {
2020 // Restore the old wallpaper if the user cancelled whilst we were setting
2021 // the new wallpaper.
2022 int width = oldWallpaper.getIntrinsicWidth();
2023 int height = oldWallpaper.getIntrinsicHeight();
2024 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2025 Canvas canvas = new Canvas(bm);
2026 oldWallpaper.setBounds(0, 0, width, height);
2027 oldWallpaper.draw(canvas);
2028 try {
2029 setWallpaper(bm);
2030 } catch (IOException e) {
2031 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2032 }
2033 mCanceled = false;
2034 }
2035
2036 if (mWallpaperProgress.isShowing()) {
2037 mWallpaperProgress.dismiss();
2038 }
2039 }
2040 }
2041
The Android Open Source Project0c908882009-03-03 19:32:16 -08002042 private void copy(CharSequence text) {
2043 try {
2044 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2045 if (clip != null) {
2046 clip.setClipboardText(text);
2047 }
2048 } catch (android.os.RemoteException e) {
2049 Log.e(LOGTAG, "Copy failed", e);
2050 }
2051 }
2052
2053 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002054 * Resets the browser title-view to whatever it must be
2055 * (for example, if we had a loading error)
2056 * When we have a new page, we call resetTitle, when we
2057 * have to reset the titlebar to whatever it used to be
2058 * (for example, if the user chose to stop loading), we
2059 * call resetTitleAndRevertLockIcon.
2060 */
2061 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002062 mTabControl.getCurrentTab().revertLockIcon();
2063 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002064 resetTitleIconAndProgress();
2065 }
2066
2067 /**
2068 * Reset the title, favicon, and progress.
2069 */
2070 private void resetTitleIconAndProgress() {
2071 WebView current = mTabControl.getCurrentWebView();
2072 if (current == null) {
2073 return;
2074 }
2075 resetTitleAndIcon(current);
2076 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002077 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 }
2079
2080 // Reset the title and the icon based on the given item.
2081 private void resetTitleAndIcon(WebView view) {
2082 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2083 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002084 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002085 setFavicon(item.getFavicon());
2086 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002087 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 setFavicon(null);
2089 }
2090 }
2091
2092 /**
2093 * Sets a title composed of the URL and the title string.
2094 * @param url The URL of the site being loaded.
2095 * @param title The title of the site being loaded.
2096 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002097 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002098 mUrl = url;
2099 mTitle = title;
2100
Leon Scroggins58d56c62010-01-28 15:12:40 -05002101 // If we are in voice search mode, the title has already been set.
2102 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2103 mTitleBar.setDisplayTitle(url);
2104 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 }
2106
2107 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 * @param url The URL to build a title version of the URL from.
2109 * @return The title version of the URL or null if fails.
2110 * The title version of the URL can be either the URL hostname,
2111 * or the hostname with an "https://" prefix (for secure URLs),
2112 * or an empty string if, for example, the URL in question is a
2113 * file:// URL with no hostname.
2114 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002115 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 String titleUrl = null;
2117
2118 if (url != null) {
2119 try {
2120 // parse the url string
2121 URL urlObj = new URL(url);
2122 if (urlObj != null) {
2123 titleUrl = "";
2124
2125 String protocol = urlObj.getProtocol();
2126 String host = urlObj.getHost();
2127
2128 if (host != null && 0 < host.length()) {
2129 titleUrl = host;
2130 if (protocol != null) {
2131 // if a secure site, add an "https://" prefix!
2132 if (protocol.equalsIgnoreCase("https")) {
2133 titleUrl = protocol + "://" + host;
2134 }
2135 }
2136 }
2137 }
2138 } catch (MalformedURLException e) {}
2139 }
2140
2141 return titleUrl;
2142 }
2143
2144 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002146 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002147 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 }
2149
2150 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002151 * Close the tab, remove its associated title bar, and adjust mTabControl's
2152 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002153 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002154 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002155 int currentIndex = mTabControl.getCurrentIndex();
2156 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002157 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002158 if (currentIndex >= removeIndex && currentIndex != 0) {
2159 currentIndex--;
2160 }
2161 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002162 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 }
2164
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002165 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002166 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 if (current == null) {
2168 /*
2169 * Instead of finishing the activity, simply push this to the back
2170 * of the stack and let ActivityManager to choose the foreground
2171 * activity. As BrowserActivity is singleTask, it will be always the
2172 * root of the task. So we can use either true or false for
2173 * moveTaskToBack().
2174 */
2175 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002176 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002177 }
2178 WebView w = current.getWebView();
2179 if (w.canGoBack()) {
2180 w.goBack();
2181 } else {
2182 // Check to see if we are closing a window that was created by
2183 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002184 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002186 switchToTab(mTabControl.getTabIndex(parent));
2187 // Now we close the other tab
2188 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002189 } else {
2190 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002191 // force the tab's inLoad() to be false as we are going to
2192 // either finish the activity or remove the tab. This will
2193 // ensure pauseWebViewTimers() taking action.
2194 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195 if (mTabControl.getTabCount() == 1) {
2196 finish();
2197 return;
2198 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002199 // call pauseWebViewTimers() now, we won't be able to call
2200 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002201 // Temporarily change mActivityInPause to be true as
2202 // pauseWebViewTimers() will do nothing if mActivityInPause
2203 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002204 boolean savedState = mActivityInPause;
2205 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002206 Log.e(LOGTAG, "BrowserActivity is already paused "
2207 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002208 }
2209 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002210 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002211 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002212 removeTabFromContentView(current);
2213 mTabControl.removeTab(current);
2214 }
2215 /*
2216 * Instead of finishing the activity, simply push this to the back
2217 * of the stack and let ActivityManager to choose the foreground
2218 * activity. As BrowserActivity is singleTask, it will be always the
2219 * root of the task. So we can use either true or false for
2220 * moveTaskToBack().
2221 */
2222 moveTaskToBack(true);
2223 }
2224 }
2225 }
2226
Grace Kloba22ac16e2009-10-07 18:00:23 -07002227 boolean isMenuDown() {
2228 return mMenuIsDown;
2229 }
2230
Grace Kloba5942df02009-09-18 11:48:29 -07002231 @Override
2232 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002233 // Even if MENU is already held down, we need to call to super to open
2234 // the IME on long press.
2235 if (KeyEvent.KEYCODE_MENU == keyCode) {
2236 mMenuIsDown = true;
2237 return super.onKeyDown(keyCode, event);
2238 }
Grace Kloba5942df02009-09-18 11:48:29 -07002239 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2240 // still down, we don't want to trigger the search. Pretend to consume
2241 // the key and do nothing.
2242 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243
Grace Kloba5942df02009-09-18 11:48:29 -07002244 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002245 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002246 // WebView/WebTextView handle the keys in the KeyDown. As
2247 // the Activity's shortcut keys are only handled when WebView
2248 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2249 if (event.isShiftPressed()) {
2250 getTopWindow().pageUp(false);
2251 } else {
2252 getTopWindow().pageDown(false);
2253 }
Grace Kloba5942df02009-09-18 11:48:29 -07002254 return true;
2255 case KeyEvent.KEYCODE_BACK:
2256 if (event.getRepeatCount() == 0) {
2257 event.startTracking();
2258 return true;
2259 } else if (mCustomView == null && mActiveTabsPage == null
2260 && event.isLongPress()) {
2261 bookmarksOrHistoryPicker(true);
2262 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 }
Grace Kloba5942df02009-09-18 11:48:29 -07002264 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002265 }
Grace Kloba5942df02009-09-18 11:48:29 -07002266 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 }
2268
Grace Kloba5942df02009-09-18 11:48:29 -07002269 @Override
2270 public boolean onKeyUp(int keyCode, KeyEvent event) {
2271 switch(keyCode) {
2272 case KeyEvent.KEYCODE_MENU:
2273 mMenuIsDown = false;
2274 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002275 case KeyEvent.KEYCODE_BACK:
2276 if (event.isTracking() && !event.isCanceled()) {
2277 if (mCustomView != null) {
2278 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002279 mTabControl.getCurrentWebView().getWebChromeClient()
2280 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002281 } else if (mActiveTabsPage != null) {
2282 // if tab page is showing, hide it
2283 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002284 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002285 WebView subwindow = mTabControl.getCurrentSubWindow();
2286 if (subwindow != null) {
2287 if (subwindow.canGoBack()) {
2288 subwindow.goBack();
2289 } else {
2290 dismissSubWindow(mTabControl.getCurrentTab());
2291 }
2292 } else {
2293 goBackOnePageOrQuit();
2294 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002295 }
Grace Kloba5942df02009-09-18 11:48:29 -07002296 return true;
2297 }
2298 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 }
Grace Kloba5942df02009-09-18 11:48:29 -07002300 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 }
2302
Leon Scroggins68579392009-09-15 15:31:54 -04002303 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002304 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305 resetTitleAndRevertLockIcon();
2306 WebView w = getTopWindow();
2307 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002308 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2309 // same logic here. But for subwindow case, should we call into the main
2310 // WebView's onPageFinished as we never call its onPageStarted and if
2311 // the page finishes itself, we don't call onPageFinished.
2312 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2313 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314
2315 cancelStopToast();
2316 mStopToast = Toast
2317 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2318 mStopToast.show();
2319 }
2320
Grace Kloba22ac16e2009-10-07 18:00:23 -07002321 boolean didUserStopLoading() {
2322 return mDidStopLoad;
2323 }
2324
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 private void cancelStopToast() {
2326 if (mStopToast != null) {
2327 mStopToast.cancel();
2328 mStopToast = null;
2329 }
2330 }
2331
Grace Kloba22ac16e2009-10-07 18:00:23 -07002332 // called by a UI or non-UI thread to post the message
2333 public void postMessage(int what, int arg1, int arg2, Object obj,
2334 long delayMillis) {
2335 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2336 obj), delayMillis);
2337 }
2338
2339 // called by a UI or non-UI thread to remove the message
2340 void removeMessages(int what, Object object) {
2341 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 }
2343
2344 // public message ids
2345 public final static int LOAD_URL = 1001;
2346 public final static int STOP_LOAD = 1002;
2347
2348 // Message Ids
2349 private static final int FOCUS_NODE_HREF = 102;
2350 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002351 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002352
Grace Kloba22ac16e2009-10-07 18:00:23 -07002353 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002354
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355 // Private handler for handling javascript and saving passwords
2356 private Handler mHandler = new Handler() {
2357
2358 public void handleMessage(Message msg) {
2359 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002361 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002362 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002363 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002364 if (url == null || url.length() == 0) {
2365 break;
2366 }
2367 HashMap focusNodeMap = (HashMap) msg.obj;
2368 WebView view = (WebView) focusNodeMap.get("webview");
2369 // Only apply the action if the top window did not change.
2370 if (getTopWindow() != view) {
2371 break;
2372 }
2373 switch (msg.arg1) {
2374 case R.id.open_context_menu_id:
2375 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002376 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002377 break;
2378 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002379 final Tab parent = mTabControl.getCurrentTab();
2380 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002381 if (newTab != parent) {
2382 parent.addChildTab(newTab);
2383 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002384 break;
2385 case R.id.bookmark_context_menu_id:
2386 Intent intent = new Intent(BrowserActivity.this,
2387 AddBookmarkPage.class);
2388 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002389 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 startActivity(intent);
2391 break;
2392 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002393 // See if this site has been visited before
2394 StringBuilder sb = new StringBuilder(
2395 Browser.BookmarkColumns.URL + " = ");
2396 DatabaseUtils.appendEscapedSQLString(sb, url);
2397 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2398 Browser.HISTORY_PROJECTION,
2399 sb.toString(),
2400 null,
2401 null);
2402 if (c.moveToFirst()) {
2403 // The site has been visited before, so grab the
2404 // info from the database.
2405 Bitmap favicon = null;
2406 Bitmap thumbnail = null;
2407 String linkTitle = c.getString(Browser.
2408 HISTORY_PROJECTION_TITLE_INDEX);
2409 byte[] data = c.getBlob(Browser.
2410 HISTORY_PROJECTION_FAVICON_INDEX);
2411 if (data != null) {
2412 favicon = BitmapFactory.decodeByteArray(
2413 data, 0, data.length);
2414 }
2415 data = c.getBlob(Browser.
2416 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2417 if (data != null) {
2418 thumbnail = BitmapFactory.decodeByteArray(
2419 data, 0, data.length);
2420 }
2421 sharePage(BrowserActivity.this,
2422 linkTitle, url, favicon, thumbnail);
2423 } else {
2424 Browser.sendString(BrowserActivity.this, url,
2425 getString(
2426 R.string.choosertitle_sharevia));
2427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002428 break;
2429 case R.id.copy_link_context_menu_id:
2430 copy(url);
2431 break;
2432 case R.id.save_link_context_menu_id:
2433 case R.id.download_context_menu_id:
2434 onDownloadStartNoStream(url, null, null, null, -1);
2435 break;
2436 }
2437 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002438 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002439
2440 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002441 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002442 break;
2443
2444 case STOP_LOAD:
2445 stopLoading();
2446 break;
2447
2448 case CANCEL_CREDS_REQUEST:
2449 resumeAfterCredentials();
2450 break;
2451
The Android Open Source Project0c908882009-03-03 19:32:16 -08002452 case RELEASE_WAKELOCK:
2453 if (mWakeLock.isHeld()) {
2454 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002455 // if we reach here, Browser should be still in the
2456 // background loading after WAKELOCK_TIMEOUT (5-min).
2457 // To avoid burning the battery, stop loading.
2458 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002459 }
2460 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002461
2462 case UPDATE_BOOKMARK_THUMBNAIL:
2463 WebView view = (WebView) msg.obj;
2464 if (view != null) {
2465 updateScreenshot(view);
2466 }
2467 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468 }
2469 }
2470 };
2471
Leon Scroggins96afcb12009-12-10 12:35:56 -05002472 /**
2473 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2474 * an {@link Intent} to launch the Activity chooser.
2475 * @param c Context used to launch a new Activity.
2476 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002477 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002478 * @param url URL of the page. Stored in the Intent with
2479 * {@link Intent#EXTRA_TEXT}
2480 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2481 * with {@link Browser#EXTRA_SHARE_FAVICON}
2482 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2483 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2484 */
2485 public static final void sharePage(Context c, String title, String url,
2486 Bitmap favicon, Bitmap screenshot) {
2487 Intent send = new Intent(Intent.ACTION_SEND);
2488 send.setType("text/plain");
2489 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002490 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002491 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2492 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2493 try {
2494 c.startActivity(Intent.createChooser(send, c.getString(
2495 R.string.choosertitle_sharevia)));
2496 } catch(android.content.ActivityNotFoundException ex) {
2497 // if no app handles it, do nothing
2498 }
2499 }
2500
Leon Scroggins89c6d362009-07-15 16:54:37 -04002501 private void updateScreenshot(WebView view) {
2502 // If this is a bookmarked site, add a screenshot to the database.
2503 // FIXME: When should we update? Every time?
2504 // FIXME: Would like to make sure there is actually something to
2505 // draw, but the API for that (WebViewCore.pictureReady()) is not
2506 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002507
Patrick Scott3918d442009-08-04 13:22:29 -04002508 ContentResolver cr = getContentResolver();
2509 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002510 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002511 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002512 boolean succeed = c.moveToFirst();
2513 ContentValues values = null;
2514 while (succeed) {
2515 if (values == null) {
2516 final ByteArrayOutputStream os
2517 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002518 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002519 if (bm == null) {
2520 c.close();
2521 return;
2522 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002523 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2524 values = new ContentValues();
2525 values.put(Browser.BookmarkColumns.THUMBNAIL,
2526 os.toByteArray());
2527 }
2528 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2529 c.getInt(0)), values, null, null);
2530 succeed = c.moveToNext();
2531 }
2532 c.close();
2533 }
2534 }
2535
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002536 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002537 * Values for the size of the thumbnail created when taking a screenshot.
2538 * Lazily initialized. Instead of using these directly, use
2539 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002540 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002541 private static int THUMBNAIL_WIDTH = 0;
2542 private static int THUMBNAIL_HEIGHT = 0;
2543
2544 /**
2545 * Return the desired width for thumbnail screenshots, which are stored in
2546 * the database, and used on the bookmarks screen.
2547 * @param context Context for finding out the density of the screen.
2548 * @return int desired width for thumbnail screenshot.
2549 */
2550 /* package */ static int getDesiredThumbnailWidth(Context context) {
2551 if (THUMBNAIL_WIDTH == 0) {
2552 float density = context.getResources().getDisplayMetrics().density;
2553 THUMBNAIL_WIDTH = (int) (90 * density);
2554 THUMBNAIL_HEIGHT = (int) (80 * density);
2555 }
2556 return THUMBNAIL_WIDTH;
2557 }
2558
2559 /**
2560 * Return the desired height for thumbnail screenshots, which are stored in
2561 * the database, and used on the bookmarks screen.
2562 * @param context Context for finding out the density of the screen.
2563 * @return int desired height for thumbnail screenshot.
2564 */
2565 /* package */ static int getDesiredThumbnailHeight(Context context) {
2566 // To ensure that they are both initialized.
2567 getDesiredThumbnailWidth(context);
2568 return THUMBNAIL_HEIGHT;
2569 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002570
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002571 private Bitmap createScreenshot(WebView view) {
2572 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002573 if (thumbnail == null) {
2574 return null;
2575 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002576 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2577 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002578 Canvas canvas = new Canvas(bm);
2579 // May need to tweak these values to determine what is the
2580 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002581 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002582 int thumbnailHeight = thumbnail.getHeight();
2583 float scaleFactorX = 1.0f;
2584 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002585 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002586 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002587 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002588 } else {
2589 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002590 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002591
2592 if (view.getWidth() > view.getHeight() &&
2593 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2594 // If the device is in landscape and the page is shorter
2595 // than the height of the view, stretch the thumbnail to fill the
2596 // space.
2597 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2598 (float)thumbnailHeight;
2599 } else {
2600 // In the portrait case, this looks nice.
2601 scaleFactorY = scaleFactorX;
2602 }
2603
2604 canvas.scale(scaleFactorX, scaleFactorY);
2605
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002606 thumbnail.draw(canvas);
2607 return bm;
2608 }
2609
The Android Open Source Project0c908882009-03-03 19:32:16 -08002610 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002611 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612 //-------------------------------------------------------------------------
2613
2614 // Use in overrideUrlLoading
2615 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2616 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2617 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2618 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2619
Leon Scroggins92472e82010-02-17 16:32:28 -05002620 // Keep this initial progress in sync with initialProgressValue (* 100)
2621 // in ProgressTracker.cpp
2622 private final static int INITIAL_PROGRESS = 10;
2623
Grace Kloba22ac16e2009-10-07 18:00:23 -07002624 void onPageStarted(WebView view, String url, Bitmap favicon) {
2625 // when BrowserActivity just starts, onPageStarted may be called before
2626 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2627 // to start the timer. As we won't switch tabs while an activity is in
2628 // pause state, we can ensure calling resume and pause in pair.
2629 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002630
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 resetLockIcon(url);
2632 setUrlTitle(url, null);
2633 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002634 // Show some progress so that the user knows the page is beginning to
2635 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002636 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002637 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002638 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002639
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 if (mSettings.isTracing()) {
2641 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 WebAddress uri = new WebAddress(url);
2644 host = uri.mHost;
2645 } catch (android.net.ParseException ex) {
2646 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648 host = host.replace('.', '_');
2649 host += ".trace";
2650 mInTrace = true;
2651 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2652 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002653
Grace Kloba22ac16e2009-10-07 18:00:23 -07002654 // Performance probe
2655 if (false) {
2656 mStart = SystemClock.uptimeMillis();
2657 mProcessStart = Process.getElapsedCpuTime();
2658 long[] sysCpu = new long[7];
2659 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2660 sysCpu, null)) {
2661 mUserStart = sysCpu[0] + sysCpu[1];
2662 mSystemStart = sysCpu[2];
2663 mIdleStart = sysCpu[3];
2664 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2665 }
2666 mUiStart = SystemClock.currentThreadTimeMillis();
2667 }
2668 }
2669
2670 void onPageFinished(WebView view, String url) {
2671 // Reset the title and icon in case we stopped a provisional load.
2672 resetTitleAndIcon(view);
2673 // Update the lock icon image only once we are done loading
2674 updateLockIconToLatest();
2675 // pause the WebView timer and release the wake lock if it is finished
2676 // while BrowserActivity is in pause state.
2677 if (mActivityInPause && pauseWebViewTimers()) {
2678 if (mWakeLock.isHeld()) {
2679 mHandler.removeMessages(RELEASE_WAKELOCK);
2680 mWakeLock.release();
2681 }
2682 }
2683
2684 // Performance probe
2685 if (false) {
2686 long[] sysCpu = new long[7];
2687 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2688 sysCpu, null)) {
2689 String uiInfo = "UI thread used "
2690 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2691 + " ms";
2692 if (LOGD_ENABLED) {
2693 Log.d(LOGTAG, uiInfo);
2694 }
2695 //The string that gets written to the log
2696 String performanceString = "It took total "
2697 + (SystemClock.uptimeMillis() - mStart)
2698 + " ms clock time to load the page."
2699 + "\nbrowser process used "
2700 + (Process.getElapsedCpuTime() - mProcessStart)
2701 + " ms, user processes used "
2702 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2703 + " ms, kernel used "
2704 + (sysCpu[2] - mSystemStart) * 10
2705 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2706 + " ms and irq took "
2707 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2708 * 10 + " ms, " + uiInfo;
2709 if (LOGD_ENABLED) {
2710 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2711 }
2712 if (url != null) {
2713 // strip the url to maintain consistency
2714 String newUrl = new String(url);
2715 if (newUrl.startsWith("http://www.")) {
2716 newUrl = newUrl.substring(11);
2717 } else if (newUrl.startsWith("http://")) {
2718 newUrl = newUrl.substring(7);
2719 } else if (newUrl.startsWith("https://www.")) {
2720 newUrl = newUrl.substring(12);
2721 } else if (newUrl.startsWith("https://")) {
2722 newUrl = newUrl.substring(8);
2723 }
2724 if (LOGD_ENABLED) {
2725 Log.d(LOGTAG, newUrl + " loaded");
2726 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002727 }
2728 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002730
Grace Kloba22ac16e2009-10-07 18:00:23 -07002731 if (mInTrace) {
2732 mInTrace = false;
2733 Debug.stopMethodTracing();
2734 }
2735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 boolean shouldOverrideUrlLoading(WebView view, String url) {
2738 if (url.startsWith(SCHEME_WTAI)) {
2739 // wtai://wp/mc;number
2740 // number=string(phone-number)
2741 if (url.startsWith(SCHEME_WTAI_MC)) {
2742 Intent intent = new Intent(Intent.ACTION_VIEW,
2743 Uri.parse(WebView.SCHEME_TEL +
2744 url.substring(SCHEME_WTAI_MC.length())));
2745 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746 return true;
2747 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 // wtai://wp/sd;dtmf
2749 // dtmf=string(dialstring)
2750 if (url.startsWith(SCHEME_WTAI_SD)) {
2751 // TODO: only send when there is active voice connection
2752 return false;
2753 }
2754 // wtai://wp/ap;number;name
2755 // number=string(phone-number)
2756 // name=string
2757 if (url.startsWith(SCHEME_WTAI_AP)) {
2758 // TODO
2759 return false;
2760 }
2761 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002762
Grace Kloba22ac16e2009-10-07 18:00:23 -07002763 // The "about:" schemes are internal to the browser; don't want these to
2764 // be dispatched to other apps.
2765 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002766 return false;
2767 }
2768
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 Intent intent;
2770 // perform generic parsing of the URI to turn it into an Intent.
2771 try {
2772 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2773 } catch (URISyntaxException ex) {
2774 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2775 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 }
2777
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 // check whether the intent can be resolved. If not, we will see
2779 // whether we can download it from the Market.
2780 if (getPackageManager().resolveActivity(intent, 0) == null) {
2781 String packagename = intent.getPackage();
2782 if (packagename != null) {
2783 intent = new Intent(Intent.ACTION_VIEW, Uri
2784 .parse("market://search?q=pname:" + packagename));
2785 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2786 startActivity(intent);
2787 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002788 } else {
2789 return false;
2790 }
2791 }
2792
Grace Kloba22ac16e2009-10-07 18:00:23 -07002793 // sanitize the Intent, ensuring web pages can not bypass browser
2794 // security (only access to BROWSABLE activities).
2795 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2796 intent.setComponent(null);
2797 try {
2798 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002799 return true;
2800 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002801 } catch (ActivityNotFoundException ex) {
2802 // ignore the error. If no application can handle the URL,
2803 // eg about:blank, assume the browser can handle it.
2804 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002805
Grace Kloba22ac16e2009-10-07 18:00:23 -07002806 if (mMenuIsDown) {
2807 openTab(url);
2808 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809 return true;
2810 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002811 return false;
2812 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002813
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 // -------------------------------------------------------------------------
2815 // Helper function for WebChromeClient
2816 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002817
Grace Kloba22ac16e2009-10-07 18:00:23 -07002818 void onProgressChanged(WebView view, int newProgress) {
2819 mTitleBar.setProgress(newProgress);
2820 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002821
Grace Kloba22ac16e2009-10-07 18:00:23 -07002822 if (newProgress == 100) {
2823 // onProgressChanged() may continue to be called after the main
2824 // frame has finished loading, as any remaining sub frames continue
2825 // to load. We'll only get called once though with newProgress as
2826 // 100 when everything is loaded. (onPageFinished is called once
2827 // when the main frame completes loading regardless of the state of
2828 // any sub frames so calls to onProgressChanges may continue after
2829 // onPageFinished has executed)
2830 if (mInLoad) {
2831 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002832 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002833 // If the options menu is open, leave the title bar
2834 if (!mOptionsMenuOpen || !mIconView) {
2835 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002836 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002837 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002838 } else {
2839 if (!mInLoad) {
2840 // onPageFinished may have already been called but a subframe is
2841 // still loading and updating the progress. Reset mInLoad and
2842 // update the menu items.
2843 mInLoad = true;
2844 updateInLoadMenuItems();
2845 }
2846 // When the page first begins to load, the Activity may still be
2847 // paused, in which case showFakeTitleBar will do nothing. Call
2848 // again as the page continues to load so that it will be shown.
2849 // (Calling it will the fake title bar is already showing will also
2850 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 if (!mOptionsMenuOpen || mIconView) {
2852 // This page has begun to load, so show the title bar
2853 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 }
2855 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002856 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857
Grace Kloba22ac16e2009-10-07 18:00:23 -07002858 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002859 // if a view already exists then immediately terminate the new one
2860 if (mCustomView != null) {
2861 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002862 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002863 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002864
2865 // Add the custom view to its container.
2866 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2867 mCustomView = view;
2868 mCustomViewCallback = callback;
2869 // Save the menu state and set it to empty while the custom
2870 // view is showing.
2871 mOldMenuState = mMenuState;
2872 mMenuState = EMPTY_MENU;
2873 // Hide the content view.
2874 mContentView.setVisibility(View.GONE);
2875 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002876 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002877 mCustomViewContainer.setVisibility(View.VISIBLE);
2878 mCustomViewContainer.bringToFront();
2879 }
2880
2881 void onHideCustomView() {
2882 if (mCustomView == null)
2883 return;
2884
2885 // Hide the custom view.
2886 mCustomView.setVisibility(View.GONE);
2887 // Remove the custom view from its container.
2888 mCustomViewContainer.removeView(mCustomView);
2889 mCustomView = null;
2890 // Reset the old menu state.
2891 mMenuState = mOldMenuState;
2892 mOldMenuState = EMPTY_MENU;
2893 mCustomViewContainer.setVisibility(View.GONE);
2894 mCustomViewCallback.onCustomViewHidden();
2895 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002896 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002897 mContentView.setVisibility(View.VISIBLE);
2898 }
2899
2900 Bitmap getDefaultVideoPoster() {
2901 if (mDefaultVideoPoster == null) {
2902 mDefaultVideoPoster = BitmapFactory.decodeResource(
2903 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002904 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002905 return mDefaultVideoPoster;
2906 }
Patrick Scott3918d442009-08-04 13:22:29 -04002907
Grace Kloba22ac16e2009-10-07 18:00:23 -07002908 View getVideoLoadingProgressView() {
2909 if (mVideoProgressView == null) {
2910 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2911 mVideoProgressView = inflater.inflate(
2912 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002913 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002914 return mVideoProgressView;
2915 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002917 /*
2918 * The Object used to inform the WebView of the file to upload.
2919 */
2920 private ValueCallback<Uri> mUploadMessage;
2921
Grace Kloba22ac16e2009-10-07 18:00:23 -07002922 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2923 if (mUploadMessage != null) return;
2924 mUploadMessage = uploadMsg;
2925 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2926 i.addCategory(Intent.CATEGORY_OPENABLE);
2927 i.setType("*/*");
2928 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2929 getString(R.string.choose_upload)), FILE_SELECTED);
2930 }
2931
2932 // -------------------------------------------------------------------------
2933 // Implement functions for DownloadListener
2934 // -------------------------------------------------------------------------
2935
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936 /**
2937 * Notify the host application a download should be done, or that
2938 * the data should be streamed if a streaming viewer is available.
2939 * @param url The full url to the content that should be downloaded
2940 * @param contentDisposition Content-disposition http header, if
2941 * present.
2942 * @param mimetype The mimetype of the content reported by the server
2943 * @param contentLength The file size reported by the server
2944 */
2945 public void onDownloadStart(String url, String userAgent,
2946 String contentDisposition, String mimetype, long contentLength) {
2947 // if we're dealing wih A/V content that's not explicitly marked
2948 // for download, check if it's streamable.
2949 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002950 || !contentDisposition.regionMatches(
2951 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002952 // query the package manager to see if there's a registered handler
2953 // that matches.
2954 Intent intent = new Intent(Intent.ACTION_VIEW);
2955 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002956 ResolveInfo info = getPackageManager().resolveActivity(intent,
2957 PackageManager.MATCH_DEFAULT_ONLY);
2958 if (info != null) {
2959 ComponentName myName = getComponentName();
2960 // If we resolved to ourselves, we don't want to attempt to
2961 // load the url only to try and download it again.
2962 if (!myName.getPackageName().equals(
2963 info.activityInfo.packageName)
2964 || !myName.getClassName().equals(
2965 info.activityInfo.name)) {
2966 // someone (other than us) knows how to handle this mime
2967 // type with this scheme, don't download.
2968 try {
2969 startActivity(intent);
2970 return;
2971 } catch (ActivityNotFoundException ex) {
2972 if (LOGD_ENABLED) {
2973 Log.d(LOGTAG, "activity not found for " + mimetype
2974 + " over " + Uri.parse(url).getScheme(),
2975 ex);
2976 }
2977 // Best behavior is to fall back to a download in this
2978 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002979 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980 }
2981 }
2982 }
2983 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2984 }
2985
2986 /**
2987 * Notify the host application a download should be done, even if there
2988 * is a streaming viewer available for thise type.
2989 * @param url The full url to the content that should be downloaded
2990 * @param contentDisposition Content-disposition http header, if
2991 * present.
2992 * @param mimetype The mimetype of the content reported by the server
2993 * @param contentLength The file size reported by the server
2994 */
2995 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2996 String contentDisposition, String mimetype, long contentLength) {
2997
2998 String filename = URLUtil.guessFileName(url,
2999 contentDisposition, mimetype);
3000
3001 // Check to see if we have an SDCard
3002 String status = Environment.getExternalStorageState();
3003 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3004 int title;
3005 String msg;
3006
3007 // Check to see if the SDCard is busy, same as the music app
3008 if (status.equals(Environment.MEDIA_SHARED)) {
3009 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3010 title = R.string.download_sdcard_busy_dlg_title;
3011 } else {
3012 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3013 title = R.string.download_no_sdcard_dlg_title;
3014 }
3015
3016 new AlertDialog.Builder(this)
3017 .setTitle(title)
3018 .setIcon(android.R.drawable.ic_dialog_alert)
3019 .setMessage(msg)
3020 .setPositiveButton(R.string.ok, null)
3021 .show();
3022 return;
3023 }
3024
3025 // java.net.URI is a lot stricter than KURL so we have to undo
3026 // KURL's percent-encoding and redo the encoding using java.net.URI.
3027 URI uri = null;
3028 try {
3029 // Undo the percent-encoding that KURL may have done.
3030 String newUrl = new String(URLUtil.decode(url.getBytes()));
3031 // Parse the url into pieces
3032 WebAddress w = new WebAddress(newUrl);
3033 String frag = null;
3034 String query = null;
3035 String path = w.mPath;
3036 // Break the path into path, query, and fragment
3037 if (path.length() > 0) {
3038 // Strip the fragment
3039 int idx = path.lastIndexOf('#');
3040 if (idx != -1) {
3041 frag = path.substring(idx + 1);
3042 path = path.substring(0, idx);
3043 }
3044 idx = path.lastIndexOf('?');
3045 if (idx != -1) {
3046 query = path.substring(idx + 1);
3047 path = path.substring(0, idx);
3048 }
3049 }
3050 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3051 query, frag);
3052 } catch (Exception e) {
3053 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3054 return;
3055 }
3056
3057 // XXX: Have to use the old url since the cookies were stored using the
3058 // old percent-encoded url.
3059 String cookies = CookieManager.getInstance().getCookie(url);
3060
3061 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003062 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3063 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3064 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3065 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003066 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003067 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003068 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003069 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3070 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3071 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3072 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3073 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003074 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003075 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 }
3077 if (mimetype == null) {
3078 // We must have long pressed on a link or image to download it. We
3079 // are not sure of the mimetype in this case, so do a head request
3080 new FetchUrlMimeType(this).execute(values);
3081 } else {
3082 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003083 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 }
3085
3086 }
3087
Grace Kloba22ac16e2009-10-07 18:00:23 -07003088 // -------------------------------------------------------------------------
3089
The Android Open Source Project0c908882009-03-03 19:32:16 -08003090 /**
3091 * Resets the lock icon. This method is called when we start a new load and
3092 * know the url to be loaded.
3093 */
3094 private void resetLockIcon(String url) {
3095 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003096 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003097 updateLockIconImage(LOCK_ICON_UNSECURE);
3098 }
3099
The Android Open Source Project0c908882009-03-03 19:32:16 -08003100 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003101 * Update the lock icon to correspond to our latest state.
3102 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003103 private void updateLockIconToLatest() {
3104 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003105 }
3106
3107 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 * Updates the lock-icon image in the title-bar.
3109 */
3110 private void updateLockIconImage(int lockIconType) {
3111 Drawable d = null;
3112 if (lockIconType == LOCK_ICON_SECURE) {
3113 d = mSecLockIcon;
3114 } else if (lockIconType == LOCK_ICON_MIXED) {
3115 d = mMixLockIcon;
3116 }
Leon Scroggins68579392009-09-15 15:31:54 -04003117 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003118 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003119 }
3120
3121 /**
3122 * Displays a page-info dialog.
3123 * @param tab The tab to show info about
3124 * @param fromShowSSLCertificateOnError The flag that indicates whether
3125 * this dialog was opened from the SSL-certificate-on-error dialog or
3126 * not. This is important, since we need to know whether to return to
3127 * the parent dialog or simply dismiss.
3128 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003129 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003130 final boolean fromShowSSLCertificateOnError) {
3131 final LayoutInflater factory = LayoutInflater
3132 .from(this);
3133
3134 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3135
3136 final WebView view = tab.getWebView();
3137
3138 String url = null;
3139 String title = null;
3140
3141 if (view == null) {
3142 url = tab.getUrl();
3143 title = tab.getTitle();
3144 } else if (view == mTabControl.getCurrentWebView()) {
3145 // Use the cached title and url if this is the current WebView
3146 url = mUrl;
3147 title = mTitle;
3148 } else {
3149 url = view.getUrl();
3150 title = view.getTitle();
3151 }
3152
3153 if (url == null) {
3154 url = "";
3155 }
3156 if (title == null) {
3157 title = "";
3158 }
3159
3160 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3161 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3162
3163 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003164 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003165
3166 AlertDialog.Builder alertDialogBuilder =
3167 new AlertDialog.Builder(this)
3168 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3169 .setView(pageInfoView)
3170 .setPositiveButton(
3171 R.string.ok,
3172 new DialogInterface.OnClickListener() {
3173 public void onClick(DialogInterface dialog,
3174 int whichButton) {
3175 mPageInfoDialog = null;
3176 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177
3178 // if we came here from the SSL error dialog
3179 if (fromShowSSLCertificateOnError) {
3180 // go back to the SSL error dialog
3181 showSSLCertificateOnError(
3182 mSSLCertificateOnErrorView,
3183 mSSLCertificateOnErrorHandler,
3184 mSSLCertificateOnErrorError);
3185 }
3186 }
3187 })
3188 .setOnCancelListener(
3189 new DialogInterface.OnCancelListener() {
3190 public void onCancel(DialogInterface dialog) {
3191 mPageInfoDialog = null;
3192 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193
3194 // if we came here from the SSL error dialog
3195 if (fromShowSSLCertificateOnError) {
3196 // go back to the SSL error dialog
3197 showSSLCertificateOnError(
3198 mSSLCertificateOnErrorView,
3199 mSSLCertificateOnErrorHandler,
3200 mSSLCertificateOnErrorError);
3201 }
3202 }
3203 });
3204
3205 // if we have a main top-level page SSL certificate set or a certificate
3206 // error
3207 if (fromShowSSLCertificateOnError ||
3208 (view != null && view.getCertificate() != null)) {
3209 // add a 'View Certificate' button
3210 alertDialogBuilder.setNeutralButton(
3211 R.string.view_certificate,
3212 new DialogInterface.OnClickListener() {
3213 public void onClick(DialogInterface dialog,
3214 int whichButton) {
3215 mPageInfoDialog = null;
3216 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217
3218 // if we came here from the SSL error dialog
3219 if (fromShowSSLCertificateOnError) {
3220 // go back to the SSL error dialog
3221 showSSLCertificateOnError(
3222 mSSLCertificateOnErrorView,
3223 mSSLCertificateOnErrorHandler,
3224 mSSLCertificateOnErrorError);
3225 } else {
3226 // otherwise, display the top-most certificate from
3227 // the chain
3228 if (view.getCertificate() != null) {
3229 showSSLCertificate(tab);
3230 }
3231 }
3232 }
3233 });
3234 }
3235
3236 mPageInfoDialog = alertDialogBuilder.show();
3237 }
3238
3239 /**
3240 * Displays the main top-level page SSL certificate dialog
3241 * (accessible from the Page-Info dialog).
3242 * @param tab The tab to show certificate for.
3243 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003244 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003245 final View certificateView =
3246 inflateCertificateView(tab.getWebView().getCertificate());
3247 if (certificateView == null) {
3248 return;
3249 }
3250
3251 LayoutInflater factory = LayoutInflater.from(this);
3252
3253 final LinearLayout placeholder =
3254 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3255
3256 LinearLayout ll = (LinearLayout) factory.inflate(
3257 R.layout.ssl_success, placeholder);
3258 ((TextView)ll.findViewById(R.id.success))
3259 .setText(R.string.ssl_certificate_is_valid);
3260
3261 mSSLCertificateView = tab;
3262 mSSLCertificateDialog =
3263 new AlertDialog.Builder(this)
3264 .setTitle(R.string.ssl_certificate).setIcon(
3265 R.drawable.ic_dialog_browser_certificate_secure)
3266 .setView(certificateView)
3267 .setPositiveButton(R.string.ok,
3268 new DialogInterface.OnClickListener() {
3269 public void onClick(DialogInterface dialog,
3270 int whichButton) {
3271 mSSLCertificateDialog = null;
3272 mSSLCertificateView = null;
3273
3274 showPageInfo(tab, false);
3275 }
3276 })
3277 .setOnCancelListener(
3278 new DialogInterface.OnCancelListener() {
3279 public void onCancel(DialogInterface dialog) {
3280 mSSLCertificateDialog = null;
3281 mSSLCertificateView = null;
3282
3283 showPageInfo(tab, false);
3284 }
3285 })
3286 .show();
3287 }
3288
3289 /**
3290 * Displays the SSL error certificate dialog.
3291 * @param view The target web-view.
3292 * @param handler The SSL error handler responsible for cancelling the
3293 * connection that resulted in an SSL error or proceeding per user request.
3294 * @param error The SSL error object.
3295 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003296 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003297 final WebView view, final SslErrorHandler handler, final SslError error) {
3298
3299 final View certificateView =
3300 inflateCertificateView(error.getCertificate());
3301 if (certificateView == null) {
3302 return;
3303 }
3304
3305 LayoutInflater factory = LayoutInflater.from(this);
3306
3307 final LinearLayout placeholder =
3308 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3309
3310 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3311 LinearLayout ll = (LinearLayout)factory
3312 .inflate(R.layout.ssl_warning, placeholder);
3313 ((TextView)ll.findViewById(R.id.warning))
3314 .setText(R.string.ssl_untrusted);
3315 }
3316
3317 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3318 LinearLayout ll = (LinearLayout)factory
3319 .inflate(R.layout.ssl_warning, placeholder);
3320 ((TextView)ll.findViewById(R.id.warning))
3321 .setText(R.string.ssl_mismatch);
3322 }
3323
3324 if (error.hasError(SslError.SSL_EXPIRED)) {
3325 LinearLayout ll = (LinearLayout)factory
3326 .inflate(R.layout.ssl_warning, placeholder);
3327 ((TextView)ll.findViewById(R.id.warning))
3328 .setText(R.string.ssl_expired);
3329 }
3330
3331 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3332 LinearLayout ll = (LinearLayout)factory
3333 .inflate(R.layout.ssl_warning, placeholder);
3334 ((TextView)ll.findViewById(R.id.warning))
3335 .setText(R.string.ssl_not_yet_valid);
3336 }
3337
3338 mSSLCertificateOnErrorHandler = handler;
3339 mSSLCertificateOnErrorView = view;
3340 mSSLCertificateOnErrorError = error;
3341 mSSLCertificateOnErrorDialog =
3342 new AlertDialog.Builder(this)
3343 .setTitle(R.string.ssl_certificate).setIcon(
3344 R.drawable.ic_dialog_browser_certificate_partially_secure)
3345 .setView(certificateView)
3346 .setPositiveButton(R.string.ok,
3347 new DialogInterface.OnClickListener() {
3348 public void onClick(DialogInterface dialog,
3349 int whichButton) {
3350 mSSLCertificateOnErrorDialog = null;
3351 mSSLCertificateOnErrorView = null;
3352 mSSLCertificateOnErrorHandler = null;
3353 mSSLCertificateOnErrorError = null;
3354
Grace Kloba22ac16e2009-10-07 18:00:23 -07003355 view.getWebViewClient().onReceivedSslError(
3356 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 }
3358 })
3359 .setNeutralButton(R.string.page_info_view,
3360 new DialogInterface.OnClickListener() {
3361 public void onClick(DialogInterface dialog,
3362 int whichButton) {
3363 mSSLCertificateOnErrorDialog = null;
3364
3365 // do not clear the dialog state: we will
3366 // need to show the dialog again once the
3367 // user is done exploring the page-info details
3368
3369 showPageInfo(mTabControl.getTabFromView(view),
3370 true);
3371 }
3372 })
3373 .setOnCancelListener(
3374 new DialogInterface.OnCancelListener() {
3375 public void onCancel(DialogInterface dialog) {
3376 mSSLCertificateOnErrorDialog = null;
3377 mSSLCertificateOnErrorView = null;
3378 mSSLCertificateOnErrorHandler = null;
3379 mSSLCertificateOnErrorError = null;
3380
Grace Kloba22ac16e2009-10-07 18:00:23 -07003381 view.getWebViewClient().onReceivedSslError(
3382 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003383 }
3384 })
3385 .show();
3386 }
3387
3388 /**
3389 * Inflates the SSL certificate view (helper method).
3390 * @param certificate The SSL certificate.
3391 * @return The resultant certificate view with issued-to, issued-by,
3392 * issued-on, expires-on, and possibly other fields set.
3393 * If the input certificate is null, returns null.
3394 */
3395 private View inflateCertificateView(SslCertificate certificate) {
3396 if (certificate == null) {
3397 return null;
3398 }
3399
3400 LayoutInflater factory = LayoutInflater.from(this);
3401
3402 View certificateView = factory.inflate(
3403 R.layout.ssl_certificate, null);
3404
3405 // issued to:
3406 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3407 if (issuedTo != null) {
3408 ((TextView) certificateView.findViewById(R.id.to_common))
3409 .setText(issuedTo.getCName());
3410 ((TextView) certificateView.findViewById(R.id.to_org))
3411 .setText(issuedTo.getOName());
3412 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3413 .setText(issuedTo.getUName());
3414 }
3415
3416 // issued by:
3417 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3418 if (issuedBy != null) {
3419 ((TextView) certificateView.findViewById(R.id.by_common))
3420 .setText(issuedBy.getCName());
3421 ((TextView) certificateView.findViewById(R.id.by_org))
3422 .setText(issuedBy.getOName());
3423 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3424 .setText(issuedBy.getUName());
3425 }
3426
3427 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003428 String issuedOn = formatCertificateDate(
3429 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003430 ((TextView) certificateView.findViewById(R.id.issued_on))
3431 .setText(issuedOn);
3432
3433 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003434 String expiresOn = formatCertificateDate(
3435 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003436 ((TextView) certificateView.findViewById(R.id.expires_on))
3437 .setText(expiresOn);
3438
3439 return certificateView;
3440 }
3441
3442 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003443 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003445 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003447 private String formatCertificateDate(Date certificateDate) {
3448 if (certificateDate == null) {
3449 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003450 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003451 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3452 if (formattedDate == null) {
3453 return "";
3454 }
3455 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456 }
3457
3458 /**
3459 * Displays an http-authentication dialog.
3460 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003461 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003462 final String host, final String realm, final String title,
3463 final String name, final String password, int focusId) {
3464 LayoutInflater factory = LayoutInflater.from(this);
3465 final View v = factory
3466 .inflate(R.layout.http_authentication, null);
3467 if (name != null) {
3468 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3469 }
3470 if (password != null) {
3471 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3472 }
3473
3474 String titleText = title;
3475 if (titleText == null) {
3476 titleText = getText(R.string.sign_in_to).toString().replace(
3477 "%s1", host).replace("%s2", realm);
3478 }
3479
3480 mHttpAuthHandler = handler;
3481 AlertDialog dialog = new AlertDialog.Builder(this)
3482 .setTitle(titleText)
3483 .setIcon(android.R.drawable.ic_dialog_alert)
3484 .setView(v)
3485 .setPositiveButton(R.string.action,
3486 new DialogInterface.OnClickListener() {
3487 public void onClick(DialogInterface dialog,
3488 int whichButton) {
3489 String nm = ((EditText) v
3490 .findViewById(R.id.username_edit))
3491 .getText().toString();
3492 String pw = ((EditText) v
3493 .findViewById(R.id.password_edit))
3494 .getText().toString();
3495 BrowserActivity.this.setHttpAuthUsernamePassword
3496 (host, realm, nm, pw);
3497 handler.proceed(nm, pw);
3498 mHttpAuthenticationDialog = null;
3499 mHttpAuthHandler = null;
3500 }})
3501 .setNegativeButton(R.string.cancel,
3502 new DialogInterface.OnClickListener() {
3503 public void onClick(DialogInterface dialog,
3504 int whichButton) {
3505 handler.cancel();
3506 BrowserActivity.this.resetTitleAndRevertLockIcon();
3507 mHttpAuthenticationDialog = null;
3508 mHttpAuthHandler = null;
3509 }})
3510 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3511 public void onCancel(DialogInterface dialog) {
3512 handler.cancel();
3513 BrowserActivity.this.resetTitleAndRevertLockIcon();
3514 mHttpAuthenticationDialog = null;
3515 mHttpAuthHandler = null;
3516 }})
3517 .create();
3518 // Make the IME appear when the dialog is displayed if applicable.
3519 dialog.getWindow().setSoftInputMode(
3520 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3521 dialog.show();
3522 if (focusId != 0) {
3523 dialog.findViewById(focusId).requestFocus();
3524 } else {
3525 v.findViewById(R.id.username_edit).requestFocus();
3526 }
3527 mHttpAuthenticationDialog = dialog;
3528 }
3529
3530 public int getProgress() {
3531 WebView w = mTabControl.getCurrentWebView();
3532 if (w != null) {
3533 return w.getProgress();
3534 } else {
3535 return 100;
3536 }
3537 }
3538
3539 /**
3540 * Set HTTP authentication password.
3541 *
3542 * @param host The host for the password
3543 * @param realm The realm for the password
3544 * @param username The username for the password. If it is null, it means
3545 * password can't be saved.
3546 * @param password The password
3547 */
3548 public void setHttpAuthUsernamePassword(String host, String realm,
3549 String username,
3550 String password) {
3551 WebView w = mTabControl.getCurrentWebView();
3552 if (w != null) {
3553 w.setHttpAuthUsernamePassword(host, realm, username, password);
3554 }
3555 }
3556
3557 /**
3558 * connectivity manager says net has come or gone... inform the user
3559 * @param up true if net has come up, false if net has gone down
3560 */
3561 public void onNetworkToggle(boolean up) {
3562 if (up == mIsNetworkUp) {
3563 return;
3564 } else if (up) {
3565 mIsNetworkUp = true;
3566 if (mAlertDialog != null) {
3567 mAlertDialog.cancel();
3568 mAlertDialog = null;
3569 }
3570 } else {
3571 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003572 if (mInLoad) {
3573 createAndShowNetworkDialog();
3574 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003575 }
3576 WebView w = mTabControl.getCurrentWebView();
3577 if (w != null) {
3578 w.setNetworkAvailable(up);
3579 }
3580 }
3581
Grace Kloba22ac16e2009-10-07 18:00:23 -07003582 boolean isNetworkUp() {
3583 return mIsNetworkUp;
3584 }
3585
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003586 // This method shows the network dialog alerting the user that the net is
3587 // down. It will only show the dialog if mAlertDialog is null.
3588 private void createAndShowNetworkDialog() {
3589 if (mAlertDialog == null) {
3590 mAlertDialog = new AlertDialog.Builder(this)
3591 .setTitle(R.string.loadSuspendedTitle)
3592 .setMessage(R.string.loadSuspended)
3593 .setPositiveButton(R.string.ok, null)
3594 .show();
3595 }
3596 }
3597
The Android Open Source Project0c908882009-03-03 19:32:16 -08003598 @Override
3599 protected void onActivityResult(int requestCode, int resultCode,
3600 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003601 if (getTopWindow() == null) return;
3602
The Android Open Source Project0c908882009-03-03 19:32:16 -08003603 switch (requestCode) {
3604 case COMBO_PAGE:
3605 if (resultCode == RESULT_OK && intent != null) {
3606 String data = intent.getAction();
3607 Bundle extras = intent.getExtras();
3608 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003609 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003610 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003611 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003613 dismissSubWindow(currentTab);
3614 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003615 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003616 }
3617 }
3618 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003619 // Deliberately fall through to PREFERENCES_PAGE, since the
3620 // same extra may be attached to the COMBO_PAGE
3621 case PREFERENCES_PAGE:
3622 if (resultCode == RESULT_OK && intent != null) {
3623 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3624 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3625 mTabControl.removeParentChildRelationShips();
3626 }
3627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003628 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003629 // Choose a file from the file picker.
3630 case FILE_SELECTED:
3631 if (null == mUploadMessage) break;
3632 Uri result = intent == null || resultCode != RESULT_OK ? null
3633 : intent.getData();
3634 mUploadMessage.onReceiveValue(result);
3635 mUploadMessage = null;
3636 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 default:
3638 break;
3639 }
Leon Scroggins30444232009-09-04 18:36:20 -04003640 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 }
3642
3643 /*
3644 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003645 * menu to see the download window. It shows the download window on top of
3646 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003647 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003648 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 Intent intent = new Intent(this,
3650 BrowserDownloadPage.class);
3651 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003652 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003653
3654 }
3655
Leon Scroggins160a7e72009-08-14 18:28:01 -04003656 /**
3657 * Open the Go page.
3658 * @param startWithHistory If true, open starting on the history tab.
3659 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003660 */
Leon Scroggins30444232009-09-04 18:36:20 -04003661 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003662 WebView current = mTabControl.getCurrentWebView();
3663 if (current == null) {
3664 return;
3665 }
3666 Intent intent = new Intent(this,
3667 CombinedBookmarkHistoryActivity.class);
3668 String title = current.getTitle();
3669 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003670 Bitmap thumbnail = createScreenshot(current);
3671
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 // Just in case the user opens bookmarks before a page finishes loading
3673 // so the current history item, and therefore the page, is null.
3674 if (null == url) {
3675 url = mLastEnteredUrl;
3676 // This can happen.
3677 if (null == url) {
3678 url = mSettings.getHomePage();
3679 }
3680 }
3681 // In case the web page has not yet received its associated title.
3682 if (title == null) {
3683 title = url;
3684 }
3685 intent.putExtra("title", title);
3686 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003687 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003688 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003689 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003690 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003691 if (startWithHistory) {
3692 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3693 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3694 }
3695 startActivityForResult(intent, COMBO_PAGE);
3696 }
3697
3698 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003699 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700 // In case the user enters nothing.
3701 if (url != null && url.length() != 0 && view != null) {
3702 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003703 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003704 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003705 }
3706 }
3707 }
3708
Leon Scroggins92472e82010-02-17 16:32:28 -05003709 /**
3710 * Load the URL into the given WebView and update the title bar
3711 * to reflect the new load. Call this instead of WebView.loadUrl
3712 * directly.
3713 * @param view The WebView used to load url.
3714 * @param url The URL to load.
3715 */
3716 private void loadUrl(WebView view, String url) {
3717 updateTitleBarForNewLoad(view, url);
3718 view.loadUrl(url);
3719 }
3720
3721 /**
3722 * Load UrlData into a Tab and update the title bar to reflect the new
3723 * load. Call this instead of UrlData.loadIn directly.
3724 * @param t The Tab used to load.
3725 * @param data The UrlData being loaded.
3726 */
3727 private void loadUrlDataIn(Tab t, UrlData data) {
3728 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3729 data.loadIn(t);
3730 }
3731
3732 /**
3733 * If the WebView is the top window, update the title bar to reflect
3734 * loading the new URL. i.e. set its text, clear the favicon (which
3735 * will be set once the page begins loading), and set the progress to
3736 * INITIAL_PROGRESS to show that the page has begun to load. Called
3737 * by loadUrl and loadUrlDataIn.
3738 * @param view The WebView that is starting a load.
3739 * @param url The URL that is being loaded.
3740 */
3741 private void updateTitleBarForNewLoad(WebView view, String url) {
3742 if (view == getTopWindow()) {
3743 setUrlTitle(url, null);
3744 setFavicon(null);
3745 onProgressChanged(view, INITIAL_PROGRESS);
3746 }
3747 }
3748
The Android Open Source Project0c908882009-03-03 19:32:16 -08003749 private String smartUrlFilter(Uri inUri) {
3750 if (inUri != null) {
3751 return smartUrlFilter(inUri.toString());
3752 }
3753 return null;
3754 }
3755
Feng Qianb34f87a2009-03-24 21:27:26 -07003756 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003757 "(?i)" + // switch on case insensitive matching
3758 "(" + // begin group for schema
3759 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003760 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003761 ")" +
3762 "(.*)" );
3763
3764 /**
3765 * Attempts to determine whether user input is a URL or search
3766 * terms. Anything with a space is passed to search.
3767 *
3768 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3769 * "Http://" converts to "http://"
3770 *
3771 * @return Original or modified URL
3772 *
3773 */
3774 String smartUrlFilter(String url) {
3775
3776 String inUrl = url.trim();
3777 boolean hasSpace = inUrl.indexOf(' ') != -1;
3778
3779 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3780 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003781 // force scheme to lowercase
3782 String scheme = matcher.group(1);
3783 String lcScheme = scheme.toLowerCase();
3784 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003785 inUrl = lcScheme + matcher.group(2);
3786 }
3787 if (hasSpace) {
3788 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003789 }
3790 return inUrl;
3791 }
3792 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003793 // FIXME: Is this the correct place to add to searches?
3794 // what if someone else calls this function?
3795 int shortcut = parseUrlShortcut(inUrl);
3796 if (shortcut != SHORTCUT_INVALID) {
3797 Browser.addSearchUrl(mResolver, inUrl);
3798 String query = inUrl.substring(2);
3799 switch (shortcut) {
3800 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003801 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003802 case SHORTCUT_WIKIPEDIA_SEARCH:
3803 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3804 case SHORTCUT_DICTIONARY_SEARCH:
3805 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3806 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003807 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003808 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003809 }
3810 }
3811 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003812 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003813 return URLUtil.guessUrl(inUrl);
3814 }
3815 }
3816
3817 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003818 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819 }
3820
Ben Murdochbff2d602009-07-01 20:19:05 +01003821 /* package */ void setShouldShowErrorConsole(boolean flag) {
3822 if (flag == mShouldShowErrorConsole) {
3823 // Nothing to do.
3824 return;
3825 }
3826
3827 mShouldShowErrorConsole = flag;
3828
Grace Kloba22ac16e2009-10-07 18:00:23 -07003829 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3830 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003831
3832 if (flag) {
3833 // Setting the show state of the console will cause it's the layout to be inflated.
3834 if (errorConsole.numberOfErrors() > 0) {
3835 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3836 } else {
3837 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3838 }
3839
3840 // Now we can add it to the main view.
3841 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003842 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003843 ViewGroup.LayoutParams.WRAP_CONTENT));
3844 } else {
3845 mErrorConsoleContainer.removeView(errorConsole);
3846 }
3847
3848 }
3849
Grace Kloba22ac16e2009-10-07 18:00:23 -07003850 boolean shouldShowErrorConsole() {
3851 return mShouldShowErrorConsole;
3852 }
3853
Andrei Popescu163ab742009-10-20 17:58:23 +01003854 private void setStatusBarVisibility(boolean visible) {
3855 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3856 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3857 }
3858
Andrei Popescu56199cc2010-01-12 22:39:16 +00003859
3860 private void sendNetworkType(String type, String subtype) {
3861 WebView w = mTabControl.getCurrentWebView();
3862 if (w != null) {
3863 w.setNetworkType(type, subtype);
3864 }
3865 }
3866
Andrei Popescu30995e72010-02-09 16:59:58 +00003867 private void packageChanged(String packageName, boolean wasAdded) {
3868 WebView w = mTabControl.getCurrentWebView();
3869 if (w == null) {
3870 return;
3871 }
3872
3873 if (wasAdded) {
3874 w.addPackageName(packageName);
3875 } else {
3876 w.removePackageName(packageName);
3877 }
3878 }
3879
3880 private void addPackageNames(Set<String> packageNames) {
3881 WebView w = mTabControl.getCurrentWebView();
3882 if (w == null) {
3883 return;
3884 }
3885
3886 w.addPackageNames(packageNames);
3887 }
3888
3889 private void getInstalledPackages() {
3890 AsyncTask<Void, Void, Set<String> > task =
3891 new AsyncTask<Void, Void, Set<String> >() {
3892 protected Set<String> doInBackground(Void... unused) {
3893 Set<String> installedPackages = new HashSet<String>();
3894 PackageManager pm = BrowserActivity.this.getPackageManager();
3895 if (pm != null) {
3896 List<PackageInfo> packages = pm.getInstalledPackages(0);
3897 for (PackageInfo p : packages) {
3898 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3899 installedPackages.add(p.packageName);
3900 }
3901 }
3902 }
3903
3904 return installedPackages;
3905 }
3906
3907 // Executes on the UI thread
3908 protected void onPostExecute(Set<String> installedPackages) {
3909 addPackageNames(installedPackages);
3910 }
3911 };
3912 task.execute();
3913 }
3914
Grace Klobaeb6eef42009-09-15 17:56:32 -07003915 final static int LOCK_ICON_UNSECURE = 0;
3916 final static int LOCK_ICON_SECURE = 1;
3917 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003918
The Android Open Source Project0c908882009-03-03 19:32:16 -08003919 private BrowserSettings mSettings;
3920 private TabControl mTabControl;
3921 private ContentResolver mResolver;
3922 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003923 private View mCustomView;
3924 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003925 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926
3927 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3928 // view, we should rewrite this.
3929 private int mCurrentMenuState = 0;
3930 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003931 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003932 private static final int EMPTY_MENU = -1;
3933 private Menu mMenu;
3934
3935 private FindDialog mFindDialog;
3936 // Used to prevent chording to result in firing two shortcuts immediately
3937 // one after another. Fixes bug 1211714.
3938 boolean mCanChord;
3939
3940 private boolean mInLoad;
3941 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003942 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003943
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 private boolean mActivityInPause = true;
3945
3946 private boolean mMenuIsDown;
3947
The Android Open Source Project0c908882009-03-03 19:32:16 -08003948 private static boolean mInTrace;
3949
3950 // Performance probe
3951 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3952 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3953 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3956 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3957 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3958 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3959 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3960 };
3961
3962 private long mStart;
3963 private long mProcessStart;
3964 private long mUserStart;
3965 private long mSystemStart;
3966 private long mIdleStart;
3967 private long mIrqStart;
3968
3969 private long mUiStart;
3970
3971 private Drawable mMixLockIcon;
3972 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003973
3974 /* hold a ref so we can auto-cancel if necessary */
3975 private AlertDialog mAlertDialog;
3976
3977 // Wait for credentials before loading google.com
3978 private ProgressDialog mCredsDlg;
3979
3980 // The up-to-date URL and title (these can be different from those stored
3981 // in WebView, since it takes some time for the information in WebView to
3982 // get updated)
3983 private String mUrl;
3984 private String mTitle;
3985
3986 // As PageInfo has different style for landscape / portrait, we have
3987 // to re-open it when configuration changed
3988 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003989 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003990 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3991 // dialog, we should not just dismiss it, but should get back to the
3992 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003993 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003994
3995 // as SSLCertificateOnError has different style for landscape / portrait,
3996 // we have to re-open it when configuration changed
3997 private AlertDialog mSSLCertificateOnErrorDialog;
3998 private WebView mSSLCertificateOnErrorView;
3999 private SslErrorHandler mSSLCertificateOnErrorHandler;
4000 private SslError mSSLCertificateOnErrorError;
4001
4002 // as SSLCertificate has different style for landscape / portrait, we
4003 // have to re-open it when configuration changed
4004 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004005 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004006
4007 // as HttpAuthentication has different style for landscape / portrait, we
4008 // have to re-open it when configuration changed
4009 private AlertDialog mHttpAuthenticationDialog;
4010 private HttpAuthHandler mHttpAuthHandler;
4011
4012 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4013 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004014 ViewGroup.LayoutParams.MATCH_PARENT,
4015 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004016 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4017 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004018 ViewGroup.LayoutParams.MATCH_PARENT,
4019 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01004020 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004021 // Google search
4022 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004023 // Wikipedia search
4024 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4025 // Dictionary search
4026 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4027 // Google Mobile Local search
4028 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4029
4030 final static String QUERY_PLACE_HOLDER = "%s";
4031
4032 // "source" parameter for Google search through search key
4033 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4034 // "source" parameter for Google search through goto menu
4035 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4036 // "source" parameter for Google search through simplily type
4037 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4038 // "source" parameter for Google search suggested by the browser
4039 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4040 // "source" parameter for Google search from unknown source
4041 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4042
4043 private final static String LOGTAG = "browser";
4044
The Android Open Source Project0c908882009-03-03 19:32:16 -08004045 private String mLastEnteredUrl;
4046
4047 private PowerManager.WakeLock mWakeLock;
4048 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4049
4050 private Toast mStopToast;
4051
Leon Scroggins68579392009-09-15 15:31:54 -04004052 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004053
Ben Murdochbff2d602009-07-01 20:19:05 +01004054 private LinearLayout mErrorConsoleContainer = null;
4055 private boolean mShouldShowErrorConsole = false;
4056
The Android Open Source Project0c908882009-03-03 19:32:16 -08004057 // As the ids are dynamically created, we can't guarantee that they will
4058 // be in sequence, so this static array maps ids to a window number.
4059 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4060 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4061 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4062 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4063
4064 // monitor platform changes
4065 private IntentFilter mNetworkStateChangedFilter;
4066 private BroadcastReceiver mNetworkStateIntentReceiver;
4067
Grace Klobab4da0ad2009-05-14 14:45:40 -07004068 private BroadcastReceiver mPackageInstallationReceiver;
4069
The Android Open Source Project0c908882009-03-03 19:32:16 -08004070 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004071 final static int COMBO_PAGE = 1;
4072 final static int DOWNLOAD_PAGE = 2;
4073 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004074 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004075
Andrei Popescu540035d2009-09-18 18:59:20 +01004076 // the default <video> poster
4077 private Bitmap mDefaultVideoPoster;
4078 // the video progress view
4079 private View mVideoProgressView;
4080
Andrei Popescu30995e72010-02-09 16:59:58 +00004081 // The Google packages we monitor for the navigator.isApplicationInstalled()
4082 // API. Add as needed.
4083 private static Set<String> sGoogleApps;
4084 static {
4085 sGoogleApps = new HashSet<String>();
4086 sGoogleApps.add("com.google.android.youtube");
4087 }
4088
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004089 /**
4090 * A UrlData class to abstract how the content will be set to WebView.
4091 * This base class uses loadUrl to show the content.
4092 */
4093 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004094 final String mUrl;
4095 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004096 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004097
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004098 UrlData(String url) {
4099 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004100 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004101 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004102 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004103
Leon Scroggins58d56c62010-01-28 15:12:40 -05004104 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004105 this.mUrl = url;
4106 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004107 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4108 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004109 this.mVoiceIntent = intent;
4110 } else {
4111 this.mVoiceIntent = null;
4112 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004113 }
4114
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004115 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004116 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004117 }
4118
Leon Scroggins92472e82010-02-17 16:32:28 -05004119 /**
4120 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4121 * the title bar as well.
4122 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004123 public void loadIn(Tab t) {
4124 if (mVoiceIntent != null) {
4125 t.activateVoiceSearchMode(mVoiceIntent);
4126 } else {
4127 t.getWebView().loadUrl(mUrl, mHeaders);
4128 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004129 }
4130 };
4131
Leon Scroggins1f005d32009-08-10 17:36:42 -04004132 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004133}