blob: f860b1ff3942b3d731e4d2e298b7416385d58439 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000114import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500115import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000129import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800130import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000131import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800132import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000133import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800134import java.util.regex.Matcher;
135import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
137public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800138 implements View.OnCreateContextMenuListener, DownloadListener,
139 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140
Dave Bort31a6d1c2009-04-13 15:56:49 -0700141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
143 */
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
147
Satish Sampath565505b2009-05-29 15:37:27 +0100148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
154
Fred Quintana752b6562009-12-18 10:18:26 -0800155 private Account[] mAccountsGoogle;
156 private Account[] mAccountsPreferHosted;
157
Patrick Scott43914692010-02-19 10:10:10 -0500158 // XXX: These constants should be exposed through some public api. Hardcode
159 // the values for now until some solution for gsf can be worked out.
160 // http://b/issue?id=2425179
161 private static final String ACCOUNT_TYPE = "com.google";
162 private static final String FEATURE_LEGACY_GOOGLE = "legacy_google";
163 private static final String FEATURE_LEGACY_HOSTED_OR_GOOGLE =
164 "legacy_hosted_or_google";
165
Fred Quintana752b6562009-12-18 10:18:26 -0800166 private void startReadOfGoogleAccounts() {
167 mAccountsGoogle = null;
168 mAccountsPreferHosted = null;
169
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
Patrick Scott43914692010-02-19 10:10:10 -0500171 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_HOSTED_OR_GOOGLE },
Fred Quintana752b6562009-12-18 10:18:26 -0800172 this, null);
173 }
174
175 /** This implements AccountManagerCallback<Account[]> */
176 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
177 try {
178 if (mAccountsGoogle == null) {
179 mAccountsGoogle = accountManagerFuture.getResult();
180
181 AccountManager.get(this).getAccountsByTypeAndFeatures(
Patrick Scott43914692010-02-19 10:10:10 -0500182 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_GOOGLE },
Fred Quintana752b6562009-12-18 10:18:26 -0800183 this, null);
184 } else {
185 mAccountsPreferHosted = accountManagerFuture.getResult();
186 setupHomePage();
187 }
188 } catch (OperationCanceledException e) {
189 setupHomePage();
190 } catch (IOException e) {
191 setupHomePage();
192 } catch (AuthenticatorException e) {
193 setupHomePage();
194 }
195 }
196
The Android Open Source Project0c908882009-03-03 19:32:16 -0800197 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800198 // get the default home page
199 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200
Fred Quintana752b6562009-12-18 10:18:26 -0800201 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
202 // three cases:
203 //
204 // hostedUser == googleUser
205 // The device has only a google account
206 //
207 // hostedUser != googleUser
208 // The device has a hosted account and a google account
209 //
210 // hostedUser != null, googleUser == null
211 // The device has only a hosted account (so far)
212 String hostedUser = mAccountsPreferHosted.length == 0
213 ? null
214 : mAccountsPreferHosted[0].name;
215 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800216
Fred Quintana752b6562009-12-18 10:18:26 -0800217 // developers might have no accounts at all
218 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700219
Fred Quintana752b6562009-12-18 10:18:26 -0800220 if (googleUser == null || !hostedUser.equals(googleUser)) {
221 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
222 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800223 }
Fred Quintana752b6562009-12-18 10:18:26 -0800224 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800225
Fred Quintana752b6562009-12-18 10:18:26 -0800226 mSettings.setHomePage(BrowserActivity.this, homepage);
227 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228 }
229
Cary Clarka9771242009-08-11 16:42:26 -0400230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231 @Override
232 public Void doInBackground(File... files) {
233 if (files != null) {
234 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400235 if (!f.delete()) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800238 }
239 }
240 return null;
241 }
242 }
243
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400244 /**
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
247 */
248 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400249
Grace Kloba22ac16e2009-10-07 18:00:23 -0700250 @Override
251 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700252 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800253 Log.v(LOGTAG, this + " onStart");
254 }
255 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
258
Mike Reedd334bf52010-01-26 15:21:44 -0500259 // enable this to test the browser in 32bit
260 if (false) {
261 getWindow().setFormat(PixelFormat.RGBX_8888);
262 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
263 }
264
The Android Open Source Project0c908882009-03-03 19:32:16 -0800265 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
266
267 mResolver = getContentResolver();
268
Grace Kloba0923d692009-09-23 21:37:25 -0700269 // If this was a web search request, pass it on to the default web
270 // search provider and finish this activity.
271 if (handleWebSearchIntent(getIntent())) {
272 finish();
273 return;
274 }
275
The Android Open Source Project0c908882009-03-03 19:32:16 -0800276 mSecLockIcon = Resources.getSystem().getDrawable(
277 android.R.drawable.ic_secure);
278 mMixLockIcon = Resources.getSystem().getDrawable(
279 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800280
Leon Scroggins81db3662009-06-04 17:45:11 -0400281 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
282 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400283 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
284 .inflate(R.layout.custom_screen, null);
285 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
286 R.id.main_content);
287 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
288 .findViewById(R.id.error_console);
289 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
290 .findViewById(R.id.fullscreen_custom_content);
291 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400292 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400293 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800294
295 // Create the tab control and our initial tab
296 mTabControl = new TabControl(this);
297
298 // Open the icon database and retain all the bookmark urls for favicons
299 retainIconsOnStartup();
300
301 // Keep a settings instance handy.
302 mSettings = BrowserSettings.getInstance();
303 mSettings.setTabControl(mTabControl);
304 mSettings.loadFromDb(this);
305
306 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
307 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
308
Grace Klobaa34f6862009-07-31 16:28:17 -0700309 /* enables registration for changes in network status from
310 http stack */
311 mNetworkStateChangedFilter = new IntentFilter();
312 mNetworkStateChangedFilter.addAction(
313 ConnectivityManager.CONNECTIVITY_ACTION);
314 mNetworkStateIntentReceiver = new BroadcastReceiver() {
315 @Override
316 public void onReceive(Context context, Intent intent) {
317 if (intent.getAction().equals(
318 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000319
320 NetworkInfo info = intent.getParcelableExtra(
321 ConnectivityManager.EXTRA_NETWORK_INFO);
322 String typeName = info.getTypeName();
323 String subtypeName = info.getSubtypeName();
324 sendNetworkType(typeName.toLowerCase(),
325 (subtypeName != null ? subtypeName.toLowerCase() : ""));
326
327 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700328 }
329 }
330 };
331
Grace Kloba615c6c92009-08-03 10:22:44 -0700332 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
333 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
334 filter.addDataScheme("package");
335 mPackageInstallationReceiver = new BroadcastReceiver() {
336 @Override
337 public void onReceive(Context context, Intent intent) {
338 final String action = intent.getAction();
339 final String packageName = intent.getData()
340 .getSchemeSpecificPart();
341 final boolean replacing = intent.getBooleanExtra(
342 Intent.EXTRA_REPLACING, false);
343 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
344 // if it is replacing, refreshPlugins() when adding
345 return;
346 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000347
348 if (sGoogleApps.contains(packageName)) {
349 BrowserActivity.this.packageChanged(packageName,
350 Intent.ACTION_PACKAGE_ADDED.equals(action));
351 }
352
Grace Kloba615c6c92009-08-03 10:22:44 -0700353 PackageManager pm = BrowserActivity.this.getPackageManager();
354 PackageInfo pkgInfo = null;
355 try {
356 pkgInfo = pm.getPackageInfo(packageName,
357 PackageManager.GET_PERMISSIONS);
358 } catch (PackageManager.NameNotFoundException e) {
359 return;
360 }
361 if (pkgInfo != null) {
362 String permissions[] = pkgInfo.requestedPermissions;
363 if (permissions == null) {
364 return;
365 }
366 boolean permissionOk = false;
367 for (String permit : permissions) {
368 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
369 permissionOk = true;
370 break;
371 }
372 }
373 if (permissionOk) {
374 PluginManager.getInstance(BrowserActivity.this)
375 .refreshPlugins(
376 Intent.ACTION_PACKAGE_ADDED
377 .equals(action));
378 }
379 }
380 }
381 };
382 registerReceiver(mPackageInstallationReceiver, filter);
383
The Android Open Source Project0c908882009-03-03 19:32:16 -0800384 if (!mTabControl.restoreState(icicle)) {
385 // clear up the thumbnail directory if we can't restore the state as
386 // none of the files in the directory are referenced any more.
387 new ClearThumbnails().execute(
388 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700389 // there is no quit on Android. But if we can't restore the state,
390 // we can treat it as a new Browser, remove the old session cookies.
391 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 final Intent intent = getIntent();
393 final Bundle extra = intent.getExtras();
394 // Create an initial tab.
395 // If the intent is ACTION_VIEW and data is not null, the Browser is
396 // invoked to view the content by another application. In this case,
397 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700398 UrlData urlData = getUrlDataFromIntent(intent);
399
Leon Scroggins58d56c62010-01-28 15:12:40 -0500400 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700401 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500402 (Intent.ACTION_VIEW.equals(action) &&
403 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500404 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
405 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700406 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800407 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800408 attachTabToContentView(t);
409 WebView webView = t.getWebView();
410 if (extra != null) {
411 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
412 if (scale > 0 && scale <= 1000) {
413 webView.setInitialScale(scale);
414 }
415 }
416 // If we are not restoring from an icicle, then there is a high
417 // likely hood this is the first run. So, check to see if the
418 // homepage needs to be configured and copy any plugins from our
419 // asset directory to the data partition.
420 if ((extra == null || !extra.getBoolean("testing"))
421 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800422 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700425 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400426 if (mSettings.isLoginInitialized()) {
Leon Scroggins92472e82010-02-17 16:32:28 -0500427 loadUrl(webView, mSettings.getHomePage());
Leon Scroggins30444232009-09-04 18:36:20 -0400428 } else {
429 waitForCredentials();
430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800431 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500432 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 }
434 } else {
435 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400436 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800437 attachTabToContentView(mTabControl.getCurrentTab());
438 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700439
Feng Qianb3c02da2009-06-29 15:58:08 -0700440 // Read JavaScript flags if it exists.
441 String jsFlags = mSettings.getJsFlags();
442 if (jsFlags.trim().length() != 0) {
443 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
444 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000445 // Work out which packages are installed on the system.
446 getInstalledPackages();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800447 }
448
Leon Scroggins58d56c62010-01-28 15:12:40 -0500449 /**
450 * Feed the previously stored results strings to the BrowserProvider so that
451 * the SearchDialog will show them instead of the standard searches.
452 * @param result String to show on the editable line of the SearchDialog.
453 */
454 /* package */ void showVoiceSearchResults(String result) {
455 ContentProviderClient client = mResolver.acquireContentProviderClient(
456 Browser.BOOKMARKS_URI);
457 ContentProvider prov = client.getLocalContentProvider();
458 BrowserProvider bp = (BrowserProvider) prov;
459 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
460 client.release();
461
462 startSearch(result, false,
463 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
464 false);
465 }
466
The Android Open Source Project0c908882009-03-03 19:32:16 -0800467 @Override
468 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800470 // When a tab is closed on exit, the current tab index is set to -1.
471 // Reset before proceed as Browser requires the current tab to be set.
472 if (current == null) {
473 // Try to reset the tab in case the index was incorrect.
474 current = mTabControl.getTab(0);
475 if (current == null) {
476 // No tabs at all so just ignore this intent.
477 return;
478 }
479 mTabControl.setCurrentTab(current);
480 attachTabToContentView(current);
481 resetTitleAndIcon(current.getWebView());
482 }
483 final String action = intent.getAction();
484 final int flags = intent.getFlags();
485 if (Intent.ACTION_MAIN.equals(action) ||
486 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
487 // just resume the browser
488 return;
489 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500490 boolean activateVoiceSearch = RecognizerResultsIntent
491 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800492 if (Intent.ACTION_VIEW.equals(action)
493 || Intent.ACTION_SEARCH.equals(action)
494 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500495 || Intent.ACTION_WEB_SEARCH.equals(action)
496 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500497 if (current.isInVoiceSearchMode()) {
498 String title = current.getVoiceDisplayTitle();
499 if (title != null && title.equals(intent.getStringExtra(
500 SearchManager.QUERY))) {
501 // The user submitted the same search as the last voice
502 // search, so do nothing.
503 return;
504 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500505 if (Intent.ACTION_SEARCH.equals(action)
506 && current.voiceSearchSourceIsGoogle()) {
507 Intent logIntent = new Intent(
508 LoggingEvents.ACTION_LOG_EVENT);
509 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
510 LoggingEvents.VoiceSearch.QUERY_UPDATED);
511 logIntent.putExtra(
512 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
513 intent.getDataString());
514 sendBroadcast(logIntent);
515 // Note, onPageStarted will revert the voice title bar
516 // When http://b/issue?id=2379215 is fixed, we should update
517 // the title bar here.
518 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500519 }
Satish Sampath565505b2009-05-29 15:37:27 +0100520 // If this was a search request (e.g. search query directly typed into the address bar),
521 // pass it on to the default web search provider.
522 if (handleWebSearchIntent(intent)) {
523 return;
524 }
525
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700526 UrlData urlData = getUrlDataFromIntent(intent);
527 if (urlData.isEmpty()) {
528 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800529 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700530
Grace Klobacc634032009-07-28 15:58:19 -0700531 final String appId = intent
532 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500533 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700534 && !getPackageName().equals(appId)
535 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700536 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700537 if (appTab != null) {
538 Log.i(LOGTAG, "Reusing tab for " + appId);
539 // Dismiss the subwindow if applicable.
540 dismissSubWindow(appTab);
541 // Since we might kill the WebView, remove it from the
542 // content view first.
543 removeTabFromContentView(appTab);
544 // Recreate the main WebView after destroying the old one.
545 // If the WebView has the same original url and is on that
546 // page, it can be reused.
547 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700548 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100549
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700550 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400551 switchToTab(mTabControl.getTabIndex(appTab));
552 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500553 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400554 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700555 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400556 // If the tab was the current tab, we have to attach
557 // it to the view system again.
558 attachTabToContentView(appTab);
559 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500560 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700561 }
562 }
563 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400564 } else {
565 // No matching application tab, try to find a regular tab
566 // with a matching url.
567 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400568 if (appTab != null) {
569 if (current != appTab) {
570 switchToTab(mTabControl.getTabIndex(appTab));
571 }
572 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400573 } else {
574 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
575 // will be opened in a new tab unless we have reached
576 // MAX_TABS. Then the url will be opened in the current
577 // tab. If a new tab is created, it will have "true" for
578 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400579 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400580 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700581 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800582 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800583 if (!urlData.isEmpty()
584 && urlData.mUrl.startsWith("about:debug")) {
585 if ("about:debug.dom".equals(urlData.mUrl)) {
586 current.getWebView().dumpDomTree(false);
587 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
588 current.getWebView().dumpDomTree(true);
589 } else if ("about:debug.render".equals(urlData.mUrl)) {
590 current.getWebView().dumpRenderTree(false);
591 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
592 current.getWebView().dumpRenderTree(true);
593 } else if ("about:debug.display".equals(urlData.mUrl)) {
594 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800595 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
596 int index = urlData.mUrl.codePointAt(16) - '0';
597 if (index <= 0 || index > 9) {
598 current.getWebView().setDragTracker(null);
599 } else {
600 current.getWebView().setDragTracker(new MeshTracker(index));
601 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800602 } else {
603 mSettings.toggleDebugSettings();
604 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800605 return;
606 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400607 // Get rid of the subwindow if it exists
608 dismissSubWindow(current);
Patrick Scott9d53da02010-02-19 10:19:01 -0500609 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800610 }
611 }
612 }
613
Satish Sampath565505b2009-05-29 15:37:27 +0100614 private int parseUrlShortcut(String url) {
615 if (url == null) return SHORTCUT_INVALID;
616
617 // FIXME: quick search, need to be customized by setting
618 if (url.length() > 2 && url.charAt(1) == ' ') {
619 switch (url.charAt(0)) {
620 case 'g': return SHORTCUT_GOOGLE_SEARCH;
621 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
622 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
623 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
624 }
625 }
626 return SHORTCUT_INVALID;
627 }
628
629 /**
630 * Launches the default web search activity with the query parameters if the given intent's data
631 * are identified as plain search terms and not URLs/shortcuts.
632 * @return true if the intent was handled and web search activity was launched, false if not.
633 */
634 private boolean handleWebSearchIntent(Intent intent) {
635 if (intent == null) return false;
636
637 String url = null;
638 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500639 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
640 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500641 return false;
642 }
Satish Sampath565505b2009-05-29 15:37:27 +0100643 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700644 Uri data = intent.getData();
645 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100646 } else if (Intent.ACTION_SEARCH.equals(action)
647 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
648 || Intent.ACTION_WEB_SEARCH.equals(action)) {
649 url = intent.getStringExtra(SearchManager.QUERY);
650 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100651 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
652 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100653 }
654
655 /**
656 * Launches the default web search activity with the query parameters if the given url string
657 * was identified as plain search terms and not URL/shortcut.
658 * @return true if the request was handled and web search activity was launched, false if not.
659 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100660 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100661 if (inUrl == null) return false;
662
663 // In general, we shouldn't modify URL from Intent.
664 // But currently, we get the user-typed URL from search box as well.
665 String url = fixUrl(inUrl).trim();
666
667 // URLs and site specific search shortcuts are handled by the regular flow of control, so
668 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800669 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100670 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100671 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
672 return false;
673 }
674
675 Browser.updateVisitedHistory(mResolver, url, false);
676 Browser.addSearchUrl(mResolver, url);
677
678 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
679 intent.addCategory(Intent.CATEGORY_DEFAULT);
680 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100681 if (appData != null) {
682 intent.putExtra(SearchManager.APP_DATA, appData);
683 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100684 if (extraData != null) {
685 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
686 }
Grace Klobacc634032009-07-28 15:58:19 -0700687 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100688 startActivity(intent);
689
690 return true;
691 }
692
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700693 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500694 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800695 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 if (intent != null) {
697 final String action = intent.getAction();
698 if (Intent.ACTION_VIEW.equals(action)) {
699 url = smartUrlFilter(intent.getData());
700 if (url != null && url.startsWith("content:")) {
701 /* Append mimetype so webview knows how to display */
702 String mimeType = intent.resolveType(getContentResolver());
703 if (mimeType != null) {
704 url += "?" + mimeType;
705 }
706 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800707 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800708 final Bundle pairs = intent
709 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800710 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800711 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800712 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800713 while (iter.hasNext()) {
714 String key = iter.next();
715 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800716 }
717 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700718 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800719 } else if (Intent.ACTION_SEARCH.equals(action)
720 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
721 || Intent.ACTION_WEB_SEARCH.equals(action)) {
722 url = intent.getStringExtra(SearchManager.QUERY);
723 if (url != null) {
724 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500725 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800726 // In general, we shouldn't modify URL from Intent.
727 // But currently, we get the user-typed URL from search box as well.
728 url = fixUrl(url);
729 url = smartUrlFilter(url);
730 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
731 if (url.contains(searchSource)) {
732 String source = null;
733 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
734 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000735 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800736 }
737 if (TextUtils.isEmpty(source)) {
738 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
739 }
740 url = url.replace(searchSource, "&source=android-"+source+"&");
741 }
742 }
743 }
744 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500745 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800746 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500747 /* package */ void showVoiceTitleBar(String title) {
748 mTitleBar.setInVoiceMode(true);
749 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750
Leon Scroggins58d56c62010-01-28 15:12:40 -0500751 mTitleBar.setDisplayTitle(title);
752 mFakeTitleBar.setDisplayTitle(title);
753 }
754 /* package */ void revertVoiceTitleBar() {
755 mTitleBar.setInVoiceMode(false);
756 mFakeTitleBar.setInVoiceMode(false);
757
758 mTitleBar.setDisplayTitle(mTitle);
759 mFakeTitleBar.setDisplayTitle(mTitle);
760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800761 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400762 // FIXME: Converting the url to lower case
763 // duplicates functionality in smartUrlFilter().
764 // However, changing all current callers of fixUrl to
765 // call smartUrlFilter in addition may have unwanted
766 // consequences, and is deferred for now.
767 int colon = inUrl.indexOf(':');
768 boolean allLower = true;
769 for (int index = 0; index < colon; index++) {
770 char ch = inUrl.charAt(index);
771 if (!Character.isLetter(ch)) {
772 break;
773 }
774 allLower &= Character.isLowerCase(ch);
775 if (index == colon - 1 && !allLower) {
776 inUrl = inUrl.substring(0, colon).toLowerCase()
777 + inUrl.substring(colon);
778 }
779 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800780 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
781 return inUrl;
782 if (inUrl.startsWith("http:") ||
783 inUrl.startsWith("https:")) {
784 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
785 inUrl = inUrl.replaceFirst("/", "//");
786 } else inUrl = inUrl.replaceFirst(":", "://");
787 }
788 return inUrl;
789 }
790
Grace Kloba22ac16e2009-10-07 18:00:23 -0700791 @Override
792 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700794 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800795 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
796 }
797
798 if (!mActivityInPause) {
799 Log.e(LOGTAG, "BrowserActivity is already resumed.");
800 return;
801 }
802
Mike Reed7bfa63b2009-05-28 11:08:32 -0400803 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800804 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400805 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800806
807 if (mWakeLock.isHeld()) {
808 mHandler.removeMessages(RELEASE_WAKELOCK);
809 mWakeLock.release();
810 }
811
812 if (mCredsDlg != null) {
813 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
814 // In case credential request never comes back
815 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
816 }
817 }
818
819 registerReceiver(mNetworkStateIntentReceiver,
820 mNetworkStateChangedFilter);
821 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800822 }
823
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400824 /**
825 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400826 * would change its appearance, use a different TitleBar to show overlayed
827 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 */
829 private TitleBar mFakeTitleBar;
830
831 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400832 * Holder for the fake title bar. It will have a foreground shadow, as well
833 * as a white background, so the fake title bar looks like the real one.
834 */
835 private ViewGroup mFakeTitleBarHolder;
836
837 /**
838 * Layout parameters for the fake title bar within mFakeTitleBarHolder
839 */
840 private FrameLayout.LayoutParams mFakeTitleBarParams
841 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800842 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400843 ViewGroup.LayoutParams.WRAP_CONTENT);
844 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400845 * Keeps track of whether the options menu is open. This is important in
846 * determining whether to show or hide the title bar overlay.
847 */
848 private boolean mOptionsMenuOpen;
849
850 /**
851 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
852 * of whether the configuration has changed. The first onMenuOpened call
853 * after a configuration change is simply a reopening of the same menu
854 * (i.e. mIconView did not change).
855 */
856 private boolean mConfigChanged;
857
858 /**
859 * Whether or not the options menu is in its smaller, icon menu form. When
860 * true, we want the title bar overlay to be up. When false, we do not.
861 * Only meaningful if mOptionsMenuOpen is true.
862 */
863 private boolean mIconView;
864
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400865 @Override
866 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400867 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
868 if (mOptionsMenuOpen) {
869 if (mConfigChanged) {
870 // We do not need to make any changes to the state of the
871 // title bar, since the only thing that happened was a
872 // change in orientation
873 mConfigChanged = false;
874 } else {
875 if (mIconView) {
876 // Switching the menu to expanded view, so hide the
877 // title bar.
878 hideFakeTitleBar();
879 mIconView = false;
880 } else {
881 // Switching the menu back to icon view, so show the
882 // title bar once again.
883 showFakeTitleBar();
884 mIconView = true;
885 }
886 }
887 } else {
888 // The options menu is closed, so open it, and show the title
889 showFakeTitleBar();
890 mOptionsMenuOpen = true;
891 mConfigChanged = false;
892 mIconView = true;
893 }
894 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400895 return true;
896 }
897
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400898 /**
899 * Special class used exclusively for the shadow drawn underneath the fake
900 * title bar. The shadow does not need to be drawn if the WebView
901 * underneath is scrolled to the top, because it will draw directly on top
902 * of the embedded shadow.
903 */
904 private static class Shadow extends View {
905 private WebView mWebView;
906
907 public Shadow(Context context, AttributeSet attrs) {
908 super(context, attrs);
909 }
910
911 public void setWebView(WebView view) {
912 mWebView = view;
913 }
914
915 @Override
916 public void draw(Canvas canvas) {
917 // In general onDraw is the method to override, but we care about
918 // whether or not the background gets drawn, which happens in draw()
919 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
920 super.draw(canvas);
921 }
922 // Need to invalidate so that if the scroll position changes, we
923 // still draw as appropriate.
924 invalidate();
925 }
926 }
927
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400928 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400929 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400930 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400931 && !mActivityInPause && decor != null
932 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400933 Rect visRect = new Rect();
934 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
935 if (LOGD_ENABLED) {
936 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
937 }
938 return;
939 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400940
941 WindowManager manager
942 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
943
944 // Add the title bar to the window manager so it can receive touches
945 // while the menu is up
946 WindowManager.LayoutParams params
947 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800948 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400949 ViewGroup.LayoutParams.WRAP_CONTENT,
950 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
951 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400952 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400953 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400954 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400955 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400956 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 // XXX : Without providing an offset, the fake title bar will be
958 // placed underneath the status bar. Use the global visible rect
959 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400960 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400961 // Add a holder for the title bar. It also holds a shadow to show
962 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400963 if (mFakeTitleBarHolder == null) {
964 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
965 .inflate(R.layout.title_bar_bg, null);
966 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400967 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
968 R.id.shadow);
969 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400970 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400971 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400972 }
973 }
974
975 @Override
976 public void onOptionsMenuClosed(Menu menu) {
977 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400978 if (!mInLoad) {
979 hideFakeTitleBar();
980 } else if (!mIconView) {
981 // The page is currently loading, and we are in expanded mode, so
982 // we were not showing the menu. Show it once again. It will be
983 // removed when the page finishes.
984 showFakeTitleBar();
985 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400986 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700987
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400988 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400989 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400990 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
991 mFakeTitleBarHolder.getLayoutParams();
992 WebView mainView = mTabControl.getCurrentWebView();
993 // Although we decided whether or not to animate based on the current
994 // scroll position, the scroll position may have changed since the
995 // fake title bar was displayed. Make sure it has the appropriate
996 // animation/lack thereof before removing.
997 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400998 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400999 WindowManager manager
1000 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -04001001 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -04001002 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1003 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001004 }
1005
The Android Open Source Project0c908882009-03-03 19:32:16 -08001006 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001007 * Special method for the fake title bar to call when displaying its context
1008 * menu, since it is in its own Window, and its parent does not show a
1009 * context menu.
1010 */
1011 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -04001012 if (null == mTitleBar.getParent()) {
1013 return;
1014 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001015 openContextMenu(mTitleBar);
1016 }
1017
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001018 @Override
1019 public void onContextMenuClosed(Menu menu) {
1020 super.onContextMenuClosed(menu);
1021 if (mInLoad) {
1022 showFakeTitleBar();
1023 }
1024 }
1025
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001026 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 * onSaveInstanceState(Bundle map)
1028 * onSaveInstanceState is called right before onStop(). The map contains
1029 * the saved state.
1030 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001031 @Override
1032 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001033 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1035 }
1036 // the default implementation requires each view to have an id. As the
1037 // browser handles the state itself and it doesn't use id for the views,
1038 // don't call the default implementation. Otherwise it will trigger the
1039 // warning like this, "couldn't save which view has focus because the
1040 // focused view XXX has no id".
1041
1042 // Save all the tabs
1043 mTabControl.saveState(outState);
1044 }
1045
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 @Override
1047 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 super.onPause();
1049
1050 if (mActivityInPause) {
1051 Log.e(LOGTAG, "BrowserActivity is already paused.");
1052 return;
1053 }
1054
Mike Reed7bfa63b2009-05-28 11:08:32 -04001055 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001057 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 mWakeLock.acquire();
1059 mHandler.sendMessageDelayed(mHandler
1060 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1061 }
1062
1063 // Clear the credentials toast if it is up
1064 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1065 mCredsDlg.dismiss();
1066 }
1067 mCredsDlg = null;
1068
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001069 // FIXME: This removes the active tabs page and resets the menu to
1070 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1071 // but then we would need to save it in onSaveInstanceState and restore
1072 // it in onCreate/onRestoreInstanceState
1073 if (mActiveTabsPage != null) {
1074 removeActiveTabPage(true);
1075 }
1076
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 cancelStopToast();
1078
1079 // unregister network state listener
1080 unregisterReceiver(mNetworkStateIntentReceiver);
1081 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001082 }
1083
Grace Kloba22ac16e2009-10-07 18:00:23 -07001084 @Override
1085 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001086 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001087 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1088 }
1089 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001090
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001091 if (mUploadMessage != null) {
1092 mUploadMessage.onReceiveValue(null);
1093 mUploadMessage = null;
1094 }
1095
Grace Kloba0923d692009-09-23 21:37:25 -07001096 if (mTabControl == null) return;
1097
Grace Kloba1fc98a32009-10-21 13:23:08 -07001098 // Remove the fake title bar if it is there
1099 hideFakeTitleBar();
1100
The Android Open Source Project0c908882009-03-03 19:32:16 -08001101 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001102 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001103 if (t != null) {
1104 dismissSubWindow(t);
1105 removeTabFromContentView(t);
1106 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001107 // Destroy all the tabs
1108 mTabControl.destroy();
1109 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110
Grace Klobab4da0ad2009-05-14 14:45:40 -07001111 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001112 }
1113
1114 @Override
1115 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001116 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 super.onConfigurationChanged(newConfig);
1118
1119 if (mPageInfoDialog != null) {
1120 mPageInfoDialog.dismiss();
1121 showPageInfo(
1122 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001123 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 }
1125 if (mSSLCertificateDialog != null) {
1126 mSSLCertificateDialog.dismiss();
1127 showSSLCertificate(
1128 mSSLCertificateView);
1129 }
1130 if (mSSLCertificateOnErrorDialog != null) {
1131 mSSLCertificateOnErrorDialog.dismiss();
1132 showSSLCertificateOnError(
1133 mSSLCertificateOnErrorView,
1134 mSSLCertificateOnErrorHandler,
1135 mSSLCertificateOnErrorError);
1136 }
1137 if (mHttpAuthenticationDialog != null) {
1138 String title = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1140 .toString();
1141 String name = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(R.id.username_edit)).getText().toString();
1143 String password = ((TextView) mHttpAuthenticationDialog
1144 .findViewById(R.id.password_edit)).getText().toString();
1145 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1146 .getId();
1147 mHttpAuthenticationDialog.dismiss();
1148 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1149 name, password, focusId);
1150 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001151 }
1152
Grace Kloba22ac16e2009-10-07 18:00:23 -07001153 @Override
1154 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 super.onLowMemory();
1156 mTabControl.freeMemory();
1157 }
1158
Mike Reed7bfa63b2009-05-28 11:08:32 -04001159 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001160 Tab tab = mTabControl.getCurrentTab();
1161 boolean inLoad = tab.inLoad();
1162 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001164 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001165 if (w != null) {
1166 w.resumeTimers();
1167 }
1168 return true;
1169 } else {
1170 return false;
1171 }
1172 }
1173
Mike Reed7bfa63b2009-05-28 11:08:32 -04001174 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001175 Tab tab = mTabControl.getCurrentTab();
1176 boolean inLoad = tab.inLoad();
1177 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001178 CookieSyncManager.getInstance().stopSync();
1179 WebView w = mTabControl.getCurrentWebView();
1180 if (w != null) {
1181 w.pauseTimers();
1182 }
1183 return true;
1184 } else {
1185 return false;
1186 }
1187 }
1188
Leon Scroggins1f005d32009-08-10 17:36:42 -04001189 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001190 /*
1191 * This function is called when we are launching for the first time. We
1192 * are waiting for the login credentials before loading Google home
1193 * pages. This way the user will be logged in straight away.
1194 */
1195 private void waitForCredentials() {
1196 // Show a toast
1197 mCredsDlg = new ProgressDialog(this);
1198 mCredsDlg.setIndeterminate(true);
1199 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1200 // If the user cancels the operation, then cancel the Google
1201 // Credentials request.
1202 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1203 mCredsDlg.show();
1204
1205 // We set a timeout for the retrieval of credentials in onResume()
1206 // as that is when we have freed up some CPU time to get
1207 // the login credentials.
1208 }
1209
1210 /*
1211 * If we have received the credentials or we have timed out and we are
1212 * showing the credentials dialog, then it is time to move on.
1213 */
1214 private void resumeAfterCredentials() {
1215 if (mCredsDlg == null) {
1216 return;
1217 }
1218
1219 // Clear the toast
1220 if (mCredsDlg.isShowing()) {
1221 mCredsDlg.dismiss();
1222 }
1223 mCredsDlg = null;
1224
1225 // Clear any pending timeout
1226 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1227
1228 // Load the page
1229 WebView w = mTabControl.getCurrentWebView();
1230 if (w != null) {
Leon Scroggins92472e82010-02-17 16:32:28 -05001231 loadUrl(w, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 }
1233
1234 // Update the settings, need to do this last as it can take a moment
1235 // to persist the settings. In the mean time we could be loading
1236 // content.
1237 mSettings.setLoginInitialized(this);
1238 }
1239
1240 // Open the icon database and retain all the icons for visited sites.
1241 private void retainIconsOnStartup() {
1242 final WebIconDatabase db = WebIconDatabase.getInstance();
1243 db.open(getDir("icons", 0).getPath());
1244 try {
1245 Cursor c = Browser.getAllBookmarks(mResolver);
1246 if (!c.moveToFirst()) {
1247 c.deactivate();
1248 return;
1249 }
1250 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1251 do {
1252 String url = c.getString(urlIndex);
1253 db.retainIconForPageUrl(url);
1254 } while (c.moveToNext());
1255 c.deactivate();
1256 } catch (IllegalStateException e) {
1257 Log.e(LOGTAG, "retainIconsOnStartup", e);
1258 }
1259 }
1260
1261 // Helper method for getting the top window.
1262 WebView getTopWindow() {
1263 return mTabControl.getCurrentTopWebView();
1264 }
1265
Grace Kloba22ac16e2009-10-07 18:00:23 -07001266 TabControl getTabControl() {
1267 return mTabControl;
1268 }
1269
The Android Open Source Project0c908882009-03-03 19:32:16 -08001270 @Override
1271 public boolean onCreateOptionsMenu(Menu menu) {
1272 super.onCreateOptionsMenu(menu);
1273
1274 MenuInflater inflater = getMenuInflater();
1275 inflater.inflate(R.menu.browser, menu);
1276 mMenu = menu;
1277 updateInLoadMenuItems();
1278 return true;
1279 }
1280
1281 /**
1282 * As the menu can be open when loading state changes
1283 * we must manually update the state of the stop/reload menu
1284 * item
1285 */
1286 private void updateInLoadMenuItems() {
1287 if (mMenu == null) {
1288 return;
1289 }
1290 MenuItem src = mInLoad ?
1291 mMenu.findItem(R.id.stop_menu_id):
1292 mMenu.findItem(R.id.reload_menu_id);
1293 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1294 dest.setIcon(src.getIcon());
1295 dest.setTitle(src.getTitle());
1296 }
1297
1298 @Override
1299 public boolean onContextItemSelected(MenuItem item) {
1300 // chording is not an issue with context menus, but we use the same
1301 // options selector, so set mCanChord to true so we can access them.
1302 mCanChord = true;
1303 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001304 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001306 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001307 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001308 Tab currentTab = mTabControl.getCurrentTab();
1309 if (null == currentTab) {
1310 result = false;
1311 break;
1312 }
1313 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001314 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001315 result = false;
1316 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001317 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001318 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001319 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001320 // -- Browser context menu
1321 case R.id.open_context_menu_id:
1322 case R.id.open_newtab_context_menu_id:
1323 case R.id.bookmark_context_menu_id:
1324 case R.id.save_link_context_menu_id:
1325 case R.id.share_link_context_menu_id:
1326 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001327 final WebView webView = getTopWindow();
1328 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001329 result = false;
1330 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001331 }
1332 final HashMap hrefMap = new HashMap();
1333 hrefMap.put("webview", webView);
1334 final Message msg = mHandler.obtainMessage(
1335 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001336 webView.requestFocusNodeHref(msg);
1337 break;
1338
1339 default:
1340 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001341 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001342 }
1343 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001344 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001345 }
1346
1347 private Bundle createGoogleSearchSourceBundle(String source) {
1348 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001349 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001350 return bundle;
1351 }
1352
Leon Scroggins8ad29922010-02-16 12:33:55 -05001353 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001354 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001355 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001356 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001357 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001358 }
1359
Leon Scroggins8ad29922010-02-16 12:33:55 -05001360 /**
1361 * Overriding this to insert a local information bundle
1362 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001363 @Override
1364 public void startSearch(String initialQuery, boolean selectInitialQuery,
1365 Bundle appSearchData, boolean globalSearch) {
1366 if (appSearchData == null) {
1367 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1368 }
1369 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1370 }
1371
Leon Scroggins1f005d32009-08-10 17:36:42 -04001372 /**
1373 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1374 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001375 * @param index Index of the tab to change to, as defined by
1376 * mTabControl.getTabIndex(Tab t).
1377 * @return boolean True if we successfully switched to a different tab. If
1378 * the indexth tab is null, or if that tab is the same as
1379 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001382 Tab tab = mTabControl.getTab(index);
1383 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001384 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001385 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 }
1387 if (currentTab != null) {
1388 // currentTab may be null if it was just removed. In that case,
1389 // we do not need to remove it
1390 removeTabFromContentView(currentTab);
1391 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001392 mTabControl.setCurrentTab(tab);
1393 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001394 resetTitleIconAndProgress();
1395 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001396 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001397 }
1398
Grace Kloba22ac16e2009-10-07 18:00:23 -07001399 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001400 return openTabAndShow(mSettings.getHomePage(), false, null);
1401 }
1402
Leon Scroggins1f005d32009-08-10 17:36:42 -04001403 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001404 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001405 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001406 // This is the last tab. Open a new one, with the home
1407 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001408 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001409 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001410 return;
1411 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001412 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001413 int indexToShow = -1;
1414 if (parent != null) {
1415 indexToShow = mTabControl.getTabIndex(parent);
1416 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001417 final int currentIndex = mTabControl.getCurrentIndex();
1418 // Try to move to the tab to the right
1419 indexToShow = currentIndex + 1;
1420 if (indexToShow > mTabControl.getTabCount() - 1) {
1421 // Try to move to the tab to the left
1422 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001423 }
1424 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001425 if (switchToTab(indexToShow)) {
1426 // Close window
1427 closeTab(current);
1428 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001429 }
1430
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001431 private ActiveTabsPage mActiveTabsPage;
1432
1433 /**
1434 * Remove the active tabs page.
1435 * @param needToAttach If true, the active tabs page did not attach a tab
1436 * to the content view, so we need to do that here.
1437 */
1438 /* package */ void removeActiveTabPage(boolean needToAttach) {
1439 mContentView.removeView(mActiveTabsPage);
1440 mActiveTabsPage = null;
1441 mMenuState = R.id.MAIN_MENU;
1442 if (needToAttach) {
1443 attachTabToContentView(mTabControl.getCurrentTab());
1444 }
1445 getTopWindow().requestFocus();
1446 }
1447
The Android Open Source Project0c908882009-03-03 19:32:16 -08001448 @Override
1449 public boolean onOptionsItemSelected(MenuItem item) {
1450 if (!mCanChord) {
1451 // The user has already fired a shortcut with this hold down of the
1452 // menu key.
1453 return false;
1454 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001455 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001456 return false;
1457 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001458 if (mMenuIsDown) {
1459 // The shortcut action consumes the MENU. Even if it is still down,
1460 // it won't trigger the next shortcut action. In the case of the
1461 // shortcut action triggering a new activity, like Bookmarks, we
1462 // won't get onKeyUp for MENU. So it is important to reset it here.
1463 mMenuIsDown = false;
1464 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001465 switch (item.getItemId()) {
1466 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001467 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001468 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001469 break;
1470
Leon Scroggins64b80f32009-08-07 12:03:34 -04001471 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001472 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001473 break;
1474
1475 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001476 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001477 break;
1478
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001479 case R.id.active_tabs_menu_id:
1480 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1481 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001482 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001483 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1484 mActiveTabsPage.requestFocus();
1485 mMenuState = EMPTY_MENU;
1486 break;
1487
Leon Scroggins1f005d32009-08-10 17:36:42 -04001488 case R.id.add_bookmark_menu_id:
1489 Intent i = new Intent(BrowserActivity.this,
1490 AddBookmarkPage.class);
1491 WebView w = getTopWindow();
1492 i.putExtra("url", w.getUrl());
1493 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001494 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001495 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001496 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001497 break;
1498
1499 case R.id.stop_reload_menu_id:
1500 if (mInLoad) {
1501 stopLoading();
1502 } else {
1503 getTopWindow().reload();
1504 }
1505 break;
1506
1507 case R.id.back_menu_id:
1508 getTopWindow().goBack();
1509 break;
1510
1511 case R.id.forward_menu_id:
1512 getTopWindow().goForward();
1513 break;
1514
1515 case R.id.close_menu_id:
1516 // Close the subwindow if it exists.
1517 if (mTabControl.getCurrentSubWindow() != null) {
1518 dismissSubWindow(mTabControl.getCurrentTab());
1519 break;
1520 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001521 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 break;
1523
1524 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001525 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001526 if (current != null) {
1527 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001528 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 }
1530 break;
1531
1532 case R.id.preferences_menu_id:
1533 Intent intent = new Intent(this,
1534 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001535 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1536 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001537 startActivityForResult(intent, PREFERENCES_PAGE);
1538 break;
1539
1540 case R.id.find_menu_id:
1541 if (null == mFindDialog) {
1542 mFindDialog = new FindDialog(this);
1543 }
1544 mFindDialog.setWebView(getTopWindow());
1545 mFindDialog.show();
1546 mMenuState = EMPTY_MENU;
1547 break;
1548
1549 case R.id.select_text_id:
1550 getTopWindow().emulateShiftHeld();
1551 break;
1552 case R.id.page_info_menu_id:
1553 showPageInfo(mTabControl.getCurrentTab(), false);
1554 break;
1555
1556 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001557 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001558 break;
1559
Leon Scroggins96afcb12009-12-10 12:35:56 -05001560 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001562 Tab currentTab = mTabControl.getCurrentTab();
1563 if (null == currentTab) {
1564 mCanChord = false;
1565 return false;
1566 }
1567 currentTab.populatePickerData();
1568 sharePage(this, currentTab.getTitle(),
1569 currentTab.getUrl(), currentTab.getFavicon(),
1570 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 break;
1572
1573 case R.id.dump_nav_menu_id:
1574 getTopWindow().debugDump();
1575 break;
1576
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001577 case R.id.dump_counters_menu_id:
1578 getTopWindow().dumpV8Counters();
1579 break;
1580
The Android Open Source Project0c908882009-03-03 19:32:16 -08001581 case R.id.zoom_in_menu_id:
1582 getTopWindow().zoomIn();
1583 break;
1584
1585 case R.id.zoom_out_menu_id:
1586 getTopWindow().zoomOut();
1587 break;
1588
1589 case R.id.view_downloads_menu_id:
1590 viewDownloads(null);
1591 break;
1592
The Android Open Source Project0c908882009-03-03 19:32:16 -08001593 case R.id.window_one_menu_id:
1594 case R.id.window_two_menu_id:
1595 case R.id.window_three_menu_id:
1596 case R.id.window_four_menu_id:
1597 case R.id.window_five_menu_id:
1598 case R.id.window_six_menu_id:
1599 case R.id.window_seven_menu_id:
1600 case R.id.window_eight_menu_id:
1601 {
1602 int menuid = item.getItemId();
1603 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1604 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001605 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001606 if (desiredTab != null &&
1607 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001608 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 }
1610 break;
1611 }
1612 }
1613 }
1614 break;
1615
1616 default:
1617 if (!super.onOptionsItemSelected(item)) {
1618 return false;
1619 }
1620 // Otherwise fall through.
1621 }
1622 mCanChord = false;
1623 return true;
1624 }
1625
1626 public void closeFind() {
1627 mMenuState = R.id.MAIN_MENU;
1628 }
1629
Grace Kloba22ac16e2009-10-07 18:00:23 -07001630 @Override
1631 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001632 // This happens when the user begins to hold down the menu key, so
1633 // allow them to chord to get a shortcut.
1634 mCanChord = true;
1635 // Note: setVisible will decide whether an item is visible; while
1636 // setEnabled() will decide whether an item is enabled, which also means
1637 // whether the matching shortcut key will function.
1638 super.onPrepareOptionsMenu(menu);
1639 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 case EMPTY_MENU:
1641 if (mCurrentMenuState != mMenuState) {
1642 menu.setGroupVisible(R.id.MAIN_MENU, false);
1643 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1644 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001645 }
1646 break;
1647 default:
1648 if (mCurrentMenuState != mMenuState) {
1649 menu.setGroupVisible(R.id.MAIN_MENU, true);
1650 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1651 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001652 }
1653 final WebView w = getTopWindow();
1654 boolean canGoBack = false;
1655 boolean canGoForward = false;
1656 boolean isHome = false;
1657 if (w != null) {
1658 canGoBack = w.canGoBack();
1659 canGoForward = w.canGoForward();
1660 isHome = mSettings.getHomePage().equals(w.getUrl());
1661 }
1662 final MenuItem back = menu.findItem(R.id.back_menu_id);
1663 back.setEnabled(canGoBack);
1664
1665 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1666 home.setEnabled(!isHome);
1667
1668 menu.findItem(R.id.forward_menu_id)
1669 .setEnabled(canGoForward);
1670
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001671 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001672 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001673
The Android Open Source Project0c908882009-03-03 19:32:16 -08001674 // decide whether to show the share link option
1675 PackageManager pm = getPackageManager();
1676 Intent send = new Intent(Intent.ACTION_SEND);
1677 send.setType("text/plain");
1678 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1679 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1680
The Android Open Source Project0c908882009-03-03 19:32:16 -08001681 boolean isNavDump = mSettings.isNavDump();
1682 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1683 nav.setVisible(isNavDump);
1684 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001685
1686 boolean showDebugSettings = mSettings.showDebugSettings();
1687 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1688 counter.setVisible(showDebugSettings);
1689 counter.setEnabled(showDebugSettings);
1690
The Android Open Source Project0c908882009-03-03 19:32:16 -08001691 break;
1692 }
1693 mCurrentMenuState = mMenuState;
1694 return true;
1695 }
1696
1697 @Override
1698 public void onCreateContextMenu(ContextMenu menu, View v,
1699 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001700 if (v instanceof TitleBar) {
1701 return;
1702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001703 WebView webview = (WebView) v;
1704 WebView.HitTestResult result = webview.getHitTestResult();
1705 if (result == null) {
1706 return;
1707 }
1708
1709 int type = result.getType();
1710 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1711 Log.w(LOGTAG,
1712 "We should not show context menu when nothing is touched");
1713 return;
1714 }
1715 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1716 // let TextView handles context menu
1717 return;
1718 }
1719
1720 // Note, http://b/issue?id=1106666 is requesting that
1721 // an inflated menu can be used again. This is not available
1722 // yet, so inflate each time (yuk!)
1723 MenuInflater inflater = getMenuInflater();
1724 inflater.inflate(R.menu.browsercontext, menu);
1725
1726 // Show the correct menu group
1727 String extra = result.getExtra();
1728 menu.setGroupVisible(R.id.PHONE_MENU,
1729 type == WebView.HitTestResult.PHONE_TYPE);
1730 menu.setGroupVisible(R.id.EMAIL_MENU,
1731 type == WebView.HitTestResult.EMAIL_TYPE);
1732 menu.setGroupVisible(R.id.GEO_MENU,
1733 type == WebView.HitTestResult.GEO_TYPE);
1734 menu.setGroupVisible(R.id.IMAGE_MENU,
1735 type == WebView.HitTestResult.IMAGE_TYPE
1736 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1737 menu.setGroupVisible(R.id.ANCHOR_MENU,
1738 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1739 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1740
1741 // Setup custom handling depending on the type
1742 switch (type) {
1743 case WebView.HitTestResult.PHONE_TYPE:
1744 menu.setHeaderTitle(Uri.decode(extra));
1745 menu.findItem(R.id.dial_context_menu_id).setIntent(
1746 new Intent(Intent.ACTION_VIEW, Uri
1747 .parse(WebView.SCHEME_TEL + extra)));
1748 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1749 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001750 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1752 addIntent);
1753 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1754 new Copy(extra));
1755 break;
1756
1757 case WebView.HitTestResult.EMAIL_TYPE:
1758 menu.setHeaderTitle(extra);
1759 menu.findItem(R.id.email_context_menu_id).setIntent(
1760 new Intent(Intent.ACTION_VIEW, Uri
1761 .parse(WebView.SCHEME_MAILTO + extra)));
1762 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1763 new Copy(extra));
1764 break;
1765
1766 case WebView.HitTestResult.GEO_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.map_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_GEO
1771 + URLEncoder.encode(extra))));
1772 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1773 new Copy(extra));
1774 break;
1775
1776 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1777 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1778 TextView titleView = (TextView) LayoutInflater.from(this)
1779 .inflate(android.R.layout.browser_link_context_header,
1780 null);
1781 titleView.setText(extra);
1782 menu.setHeaderView(titleView);
1783 // decide whether to show the open link in new tab option
1784 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001786 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1787 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001788 PackageManager pm = getPackageManager();
1789 Intent send = new Intent(Intent.ACTION_SEND);
1790 send.setType("text/plain");
1791 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1792 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1793 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1794 break;
1795 }
1796 // otherwise fall through to handle image part
1797 case WebView.HitTestResult.IMAGE_TYPE:
1798 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1799 menu.setHeaderTitle(extra);
1800 }
1801 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1802 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1803 menu.findItem(R.id.download_context_menu_id).
1804 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001805 menu.findItem(R.id.set_wallpaper_context_menu_id).
1806 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 break;
1808
1809 default:
1810 Log.w(LOGTAG, "We should not get here.");
1811 break;
1812 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001813 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001814 }
1815
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001817 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001819 // Attach the container that contains the main WebView and any other UI
1820 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001821 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001822
1823 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001824 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001825 if (errorConsole.numberOfErrors() == 0) {
1826 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1827 } else {
1828 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1829 }
1830
1831 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001832 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001833 ViewGroup.LayoutParams.WRAP_CONTENT));
1834 }
1835
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001836 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001837 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001838 if (t.isInVoiceSearchMode()) {
1839 showVoiceTitleBar(t.getVoiceDisplayTitle());
1840 } else {
1841 revertVoiceTitleBar();
1842 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001843 // Request focus on the top window.
1844 t.getTopWindow().requestFocus();
1845 }
1846
1847 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001849 t.attachSubWindow(mContentView);
1850 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001851 }
1852
1853 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001854 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001855 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001856 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001857
Grace Kloba22ac16e2009-10-07 18:00:23 -07001858 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1859 if (errorConsole != null) {
1860 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001861 }
1862
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001863 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001864 if (view != null) {
1865 view.setEmbeddedTitleBar(null);
1866 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 }
1868
1869 // Remove the sub window if it exists. Also called by TabControl when the
1870 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001871 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001872 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001873 // dismiss the subwindow. This will destroy the WebView.
1874 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001875 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877
Leon Scroggins1f005d32009-08-10 17:36:42 -04001878 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001879 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001880 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001881 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 }
1883
1884 // This method does a ton of stuff. It will attempt to create a new tab
1885 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001886 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001887 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1888 String appId) {
1889 final Tab currentTab = mTabControl.getCurrentTab();
1890 if (mTabControl.canCreateNewTab()) {
1891 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1892 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001894 // If the last tab was removed from the active tabs page, currentTab
1895 // will be null.
1896 if (currentTab != null) {
1897 removeTabFromContentView(currentTab);
1898 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001899 // We must set the new tab as the current tab to reflect the old
1900 // animation behavior.
1901 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001902 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001903 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001904 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001905 }
1906 return tab;
1907 } else {
1908 // Get rid of the subwindow if it exists
1909 dismissSubWindow(currentTab);
1910 if (!urlData.isEmpty()) {
1911 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001912 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001913 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001914 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001915 }
1916 }
1917
Grace Kloba22ac16e2009-10-07 18:00:23 -07001918 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001919 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001920 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001922 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001923 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001924 }
Grace Klobac9181842009-04-14 08:53:22 -07001925 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001926 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001927 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001928 }
1929 }
1930
1931 private class Copy implements OnMenuItemClickListener {
1932 private CharSequence mText;
1933
1934 public boolean onMenuItemClick(MenuItem item) {
1935 copy(mText);
1936 return true;
1937 }
1938
1939 public Copy(CharSequence toCopy) {
1940 mText = toCopy;
1941 }
1942 }
1943
1944 private class Download implements OnMenuItemClickListener {
1945 private String mText;
1946
1947 public boolean onMenuItemClick(MenuItem item) {
1948 onDownloadStartNoStream(mText, null, null, null, -1);
1949 return true;
1950 }
1951
1952 public Download(String toDownload) {
1953 mText = toDownload;
1954 }
1955 }
1956
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001957 private class SetAsWallpaper extends Thread implements
1958 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1959 private URL mUrl;
1960 private ProgressDialog mWallpaperProgress;
1961 private boolean mCanceled = false;
1962
1963 public SetAsWallpaper(String url) {
1964 try {
1965 mUrl = new URL(url);
1966 } catch (MalformedURLException e) {
1967 mUrl = null;
1968 }
1969 }
1970
1971 public void onCancel(DialogInterface dialog) {
1972 mCanceled = true;
1973 }
1974
1975 public boolean onMenuItemClick(MenuItem item) {
1976 if (mUrl != null) {
1977 // The user may have tried to set a image with a large file size as their
1978 // background so it may take a few moments to perform the operation. Display
1979 // a progress spinner while it is working.
1980 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1981 mWallpaperProgress.setIndeterminate(true);
1982 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1983 mWallpaperProgress.setCancelable(true);
1984 mWallpaperProgress.setOnCancelListener(this);
1985 mWallpaperProgress.show();
1986 start();
1987 }
1988 return true;
1989 }
1990
1991 public void run() {
1992 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1993 try {
1994 // TODO: This will cause the resource to be downloaded again, when we
1995 // should in most cases be able to grab it from the cache. To fix this
1996 // we should query WebCore to see if we can access a cached version and
1997 // instead open an input stream on that. This pattern could also be used
1998 // in the download manager where the same problem exists.
1999 InputStream inputstream = mUrl.openStream();
2000 if (inputstream != null) {
2001 setWallpaper(inputstream);
2002 }
2003 } catch (IOException e) {
2004 Log.e(LOGTAG, "Unable to set new wallpaper");
2005 // Act as though the user canceled the operation so we try to
2006 // restore the old wallpaper.
2007 mCanceled = true;
2008 }
2009
2010 if (mCanceled) {
2011 // Restore the old wallpaper if the user cancelled whilst we were setting
2012 // the new wallpaper.
2013 int width = oldWallpaper.getIntrinsicWidth();
2014 int height = oldWallpaper.getIntrinsicHeight();
2015 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2016 Canvas canvas = new Canvas(bm);
2017 oldWallpaper.setBounds(0, 0, width, height);
2018 oldWallpaper.draw(canvas);
2019 try {
2020 setWallpaper(bm);
2021 } catch (IOException e) {
2022 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2023 }
2024 mCanceled = false;
2025 }
2026
2027 if (mWallpaperProgress.isShowing()) {
2028 mWallpaperProgress.dismiss();
2029 }
2030 }
2031 }
2032
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 private void copy(CharSequence text) {
2034 try {
2035 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2036 if (clip != null) {
2037 clip.setClipboardText(text);
2038 }
2039 } catch (android.os.RemoteException e) {
2040 Log.e(LOGTAG, "Copy failed", e);
2041 }
2042 }
2043
2044 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 * Resets the browser title-view to whatever it must be
2046 * (for example, if we had a loading error)
2047 * When we have a new page, we call resetTitle, when we
2048 * have to reset the titlebar to whatever it used to be
2049 * (for example, if the user chose to stop loading), we
2050 * call resetTitleAndRevertLockIcon.
2051 */
2052 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 mTabControl.getCurrentTab().revertLockIcon();
2054 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 resetTitleIconAndProgress();
2056 }
2057
2058 /**
2059 * Reset the title, favicon, and progress.
2060 */
2061 private void resetTitleIconAndProgress() {
2062 WebView current = mTabControl.getCurrentWebView();
2063 if (current == null) {
2064 return;
2065 }
2066 resetTitleAndIcon(current);
2067 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002068 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 }
2070
2071 // Reset the title and the icon based on the given item.
2072 private void resetTitleAndIcon(WebView view) {
2073 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2074 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002075 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002076 setFavicon(item.getFavicon());
2077 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002078 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 setFavicon(null);
2080 }
2081 }
2082
2083 /**
2084 * Sets a title composed of the URL and the title string.
2085 * @param url The URL of the site being loaded.
2086 * @param title The title of the site being loaded.
2087 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002088 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 mUrl = url;
2090 mTitle = title;
2091
Leon Scroggins58d56c62010-01-28 15:12:40 -05002092 // If we are in voice search mode, the title has already been set.
2093 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2094 mTitleBar.setDisplayTitle(url);
2095 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096 }
2097
2098 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002099 * @param url The URL to build a title version of the URL from.
2100 * @return The title version of the URL or null if fails.
2101 * The title version of the URL can be either the URL hostname,
2102 * or the hostname with an "https://" prefix (for secure URLs),
2103 * or an empty string if, for example, the URL in question is a
2104 * file:// URL with no hostname.
2105 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002106 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002107 String titleUrl = null;
2108
2109 if (url != null) {
2110 try {
2111 // parse the url string
2112 URL urlObj = new URL(url);
2113 if (urlObj != null) {
2114 titleUrl = "";
2115
2116 String protocol = urlObj.getProtocol();
2117 String host = urlObj.getHost();
2118
2119 if (host != null && 0 < host.length()) {
2120 titleUrl = host;
2121 if (protocol != null) {
2122 // if a secure site, add an "https://" prefix!
2123 if (protocol.equalsIgnoreCase("https")) {
2124 titleUrl = protocol + "://" + host;
2125 }
2126 }
2127 }
2128 }
2129 } catch (MalformedURLException e) {}
2130 }
2131
2132 return titleUrl;
2133 }
2134
2135 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002137 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002138 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 }
2140
2141 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002142 * Close the tab, remove its associated title bar, and adjust mTabControl's
2143 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002144 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002146 int currentIndex = mTabControl.getCurrentIndex();
2147 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002148 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002149 if (currentIndex >= removeIndex && currentIndex != 0) {
2150 currentIndex--;
2151 }
2152 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002153 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 }
2155
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05002156 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002157 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002158 if (current == null) {
2159 /*
2160 * Instead of finishing the activity, simply push this to the back
2161 * of the stack and let ActivityManager to choose the foreground
2162 * activity. As BrowserActivity is singleTask, it will be always the
2163 * root of the task. So we can use either true or false for
2164 * moveTaskToBack().
2165 */
2166 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002167 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168 }
2169 WebView w = current.getWebView();
2170 if (w.canGoBack()) {
2171 w.goBack();
2172 } else {
2173 // Check to see if we are closing a window that was created by
2174 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002175 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002177 switchToTab(mTabControl.getTabIndex(parent));
2178 // Now we close the other tab
2179 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 } else {
2181 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002182 // force the tab's inLoad() to be false as we are going to
2183 // either finish the activity or remove the tab. This will
2184 // ensure pauseWebViewTimers() taking action.
2185 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 if (mTabControl.getTabCount() == 1) {
2187 finish();
2188 return;
2189 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002190 // call pauseWebViewTimers() now, we won't be able to call
2191 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002192 // Temporarily change mActivityInPause to be true as
2193 // pauseWebViewTimers() will do nothing if mActivityInPause
2194 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002195 boolean savedState = mActivityInPause;
2196 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002197 Log.e(LOGTAG, "BrowserActivity is already paused "
2198 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002199 }
2200 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002201 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002202 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203 removeTabFromContentView(current);
2204 mTabControl.removeTab(current);
2205 }
2206 /*
2207 * Instead of finishing the activity, simply push this to the back
2208 * of the stack and let ActivityManager to choose the foreground
2209 * activity. As BrowserActivity is singleTask, it will be always the
2210 * root of the task. So we can use either true or false for
2211 * moveTaskToBack().
2212 */
2213 moveTaskToBack(true);
2214 }
2215 }
2216 }
2217
Grace Kloba22ac16e2009-10-07 18:00:23 -07002218 boolean isMenuDown() {
2219 return mMenuIsDown;
2220 }
2221
Grace Kloba5942df02009-09-18 11:48:29 -07002222 @Override
2223 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002224 // Even if MENU is already held down, we need to call to super to open
2225 // the IME on long press.
2226 if (KeyEvent.KEYCODE_MENU == keyCode) {
2227 mMenuIsDown = true;
2228 return super.onKeyDown(keyCode, event);
2229 }
Grace Kloba5942df02009-09-18 11:48:29 -07002230 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2231 // still down, we don't want to trigger the search. Pretend to consume
2232 // the key and do nothing.
2233 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234
Grace Kloba5942df02009-09-18 11:48:29 -07002235 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002236 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002237 // WebView/WebTextView handle the keys in the KeyDown. As
2238 // the Activity's shortcut keys are only handled when WebView
2239 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2240 if (event.isShiftPressed()) {
2241 getTopWindow().pageUp(false);
2242 } else {
2243 getTopWindow().pageDown(false);
2244 }
Grace Kloba5942df02009-09-18 11:48:29 -07002245 return true;
2246 case KeyEvent.KEYCODE_BACK:
2247 if (event.getRepeatCount() == 0) {
2248 event.startTracking();
2249 return true;
2250 } else if (mCustomView == null && mActiveTabsPage == null
2251 && event.isLongPress()) {
2252 bookmarksOrHistoryPicker(true);
2253 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002254 }
Grace Kloba5942df02009-09-18 11:48:29 -07002255 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
Grace Kloba5942df02009-09-18 11:48:29 -07002257 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 }
2259
Grace Kloba5942df02009-09-18 11:48:29 -07002260 @Override
2261 public boolean onKeyUp(int keyCode, KeyEvent event) {
2262 switch(keyCode) {
2263 case KeyEvent.KEYCODE_MENU:
2264 mMenuIsDown = false;
2265 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002266 case KeyEvent.KEYCODE_BACK:
2267 if (event.isTracking() && !event.isCanceled()) {
2268 if (mCustomView != null) {
2269 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002270 mTabControl.getCurrentWebView().getWebChromeClient()
2271 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002272 } else if (mActiveTabsPage != null) {
2273 // if tab page is showing, hide it
2274 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002276 WebView subwindow = mTabControl.getCurrentSubWindow();
2277 if (subwindow != null) {
2278 if (subwindow.canGoBack()) {
2279 subwindow.goBack();
2280 } else {
2281 dismissSubWindow(mTabControl.getCurrentTab());
2282 }
2283 } else {
2284 goBackOnePageOrQuit();
2285 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 }
Grace Kloba5942df02009-09-18 11:48:29 -07002287 return true;
2288 }
2289 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290 }
Grace Kloba5942df02009-09-18 11:48:29 -07002291 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002292 }
2293
Leon Scroggins68579392009-09-15 15:31:54 -04002294 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002295 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002296 resetTitleAndRevertLockIcon();
2297 WebView w = getTopWindow();
2298 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002299 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2300 // same logic here. But for subwindow case, should we call into the main
2301 // WebView's onPageFinished as we never call its onPageStarted and if
2302 // the page finishes itself, we don't call onPageFinished.
2303 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2304 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002305
2306 cancelStopToast();
2307 mStopToast = Toast
2308 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2309 mStopToast.show();
2310 }
2311
Grace Kloba22ac16e2009-10-07 18:00:23 -07002312 boolean didUserStopLoading() {
2313 return mDidStopLoad;
2314 }
2315
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 private void cancelStopToast() {
2317 if (mStopToast != null) {
2318 mStopToast.cancel();
2319 mStopToast = null;
2320 }
2321 }
2322
Grace Kloba22ac16e2009-10-07 18:00:23 -07002323 // called by a UI or non-UI thread to post the message
2324 public void postMessage(int what, int arg1, int arg2, Object obj,
2325 long delayMillis) {
2326 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2327 obj), delayMillis);
2328 }
2329
2330 // called by a UI or non-UI thread to remove the message
2331 void removeMessages(int what, Object object) {
2332 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002333 }
2334
2335 // public message ids
2336 public final static int LOAD_URL = 1001;
2337 public final static int STOP_LOAD = 1002;
2338
2339 // Message Ids
2340 private static final int FOCUS_NODE_HREF = 102;
2341 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002342 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002343
Grace Kloba22ac16e2009-10-07 18:00:23 -07002344 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002345
The Android Open Source Project0c908882009-03-03 19:32:16 -08002346 // Private handler for handling javascript and saving passwords
2347 private Handler mHandler = new Handler() {
2348
2349 public void handleMessage(Message msg) {
2350 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002352 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002353 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002354 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002355 if (url == null || url.length() == 0) {
2356 break;
2357 }
2358 HashMap focusNodeMap = (HashMap) msg.obj;
2359 WebView view = (WebView) focusNodeMap.get("webview");
2360 // Only apply the action if the top window did not change.
2361 if (getTopWindow() != view) {
2362 break;
2363 }
2364 switch (msg.arg1) {
2365 case R.id.open_context_menu_id:
2366 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002367 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 break;
2369 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002370 final Tab parent = mTabControl.getCurrentTab();
2371 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002372 if (newTab != parent) {
2373 parent.addChildTab(newTab);
2374 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002375 break;
2376 case R.id.bookmark_context_menu_id:
2377 Intent intent = new Intent(BrowserActivity.this,
2378 AddBookmarkPage.class);
2379 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002380 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002381 startActivity(intent);
2382 break;
2383 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002384 // See if this site has been visited before
2385 StringBuilder sb = new StringBuilder(
2386 Browser.BookmarkColumns.URL + " = ");
2387 DatabaseUtils.appendEscapedSQLString(sb, url);
2388 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2389 Browser.HISTORY_PROJECTION,
2390 sb.toString(),
2391 null,
2392 null);
2393 if (c.moveToFirst()) {
2394 // The site has been visited before, so grab the
2395 // info from the database.
2396 Bitmap favicon = null;
2397 Bitmap thumbnail = null;
2398 String linkTitle = c.getString(Browser.
2399 HISTORY_PROJECTION_TITLE_INDEX);
2400 byte[] data = c.getBlob(Browser.
2401 HISTORY_PROJECTION_FAVICON_INDEX);
2402 if (data != null) {
2403 favicon = BitmapFactory.decodeByteArray(
2404 data, 0, data.length);
2405 }
2406 data = c.getBlob(Browser.
2407 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2408 if (data != null) {
2409 thumbnail = BitmapFactory.decodeByteArray(
2410 data, 0, data.length);
2411 }
2412 sharePage(BrowserActivity.this,
2413 linkTitle, url, favicon, thumbnail);
2414 } else {
2415 Browser.sendString(BrowserActivity.this, url,
2416 getString(
2417 R.string.choosertitle_sharevia));
2418 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002419 break;
2420 case R.id.copy_link_context_menu_id:
2421 copy(url);
2422 break;
2423 case R.id.save_link_context_menu_id:
2424 case R.id.download_context_menu_id:
2425 onDownloadStartNoStream(url, null, null, null, -1);
2426 break;
2427 }
2428 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002429 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002430
2431 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002432 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 break;
2434
2435 case STOP_LOAD:
2436 stopLoading();
2437 break;
2438
2439 case CANCEL_CREDS_REQUEST:
2440 resumeAfterCredentials();
2441 break;
2442
The Android Open Source Project0c908882009-03-03 19:32:16 -08002443 case RELEASE_WAKELOCK:
2444 if (mWakeLock.isHeld()) {
2445 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002446 // if we reach here, Browser should be still in the
2447 // background loading after WAKELOCK_TIMEOUT (5-min).
2448 // To avoid burning the battery, stop loading.
2449 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002450 }
2451 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002452
2453 case UPDATE_BOOKMARK_THUMBNAIL:
2454 WebView view = (WebView) msg.obj;
2455 if (view != null) {
2456 updateScreenshot(view);
2457 }
2458 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002459 }
2460 }
2461 };
2462
Leon Scroggins96afcb12009-12-10 12:35:56 -05002463 /**
2464 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2465 * an {@link Intent} to launch the Activity chooser.
2466 * @param c Context used to launch a new Activity.
2467 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002468 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002469 * @param url URL of the page. Stored in the Intent with
2470 * {@link Intent#EXTRA_TEXT}
2471 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2472 * with {@link Browser#EXTRA_SHARE_FAVICON}
2473 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2474 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2475 */
2476 public static final void sharePage(Context c, String title, String url,
2477 Bitmap favicon, Bitmap screenshot) {
2478 Intent send = new Intent(Intent.ACTION_SEND);
2479 send.setType("text/plain");
2480 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002481 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002482 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2483 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2484 try {
2485 c.startActivity(Intent.createChooser(send, c.getString(
2486 R.string.choosertitle_sharevia)));
2487 } catch(android.content.ActivityNotFoundException ex) {
2488 // if no app handles it, do nothing
2489 }
2490 }
2491
Leon Scroggins89c6d362009-07-15 16:54:37 -04002492 private void updateScreenshot(WebView view) {
2493 // If this is a bookmarked site, add a screenshot to the database.
2494 // FIXME: When should we update? Every time?
2495 // FIXME: Would like to make sure there is actually something to
2496 // draw, but the API for that (WebViewCore.pictureReady()) is not
2497 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002498
Patrick Scott3918d442009-08-04 13:22:29 -04002499 ContentResolver cr = getContentResolver();
2500 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002501 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002502 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002503 boolean succeed = c.moveToFirst();
2504 ContentValues values = null;
2505 while (succeed) {
2506 if (values == null) {
2507 final ByteArrayOutputStream os
2508 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002509 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002510 if (bm == null) {
2511 c.close();
2512 return;
2513 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002514 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2515 values = new ContentValues();
2516 values.put(Browser.BookmarkColumns.THUMBNAIL,
2517 os.toByteArray());
2518 }
2519 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2520 c.getInt(0)), values, null, null);
2521 succeed = c.moveToNext();
2522 }
2523 c.close();
2524 }
2525 }
2526
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002527 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002528 * Values for the size of the thumbnail created when taking a screenshot.
2529 * Lazily initialized. Instead of using these directly, use
2530 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002531 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002532 private static int THUMBNAIL_WIDTH = 0;
2533 private static int THUMBNAIL_HEIGHT = 0;
2534
2535 /**
2536 * Return the desired width for thumbnail screenshots, which are stored in
2537 * the database, and used on the bookmarks screen.
2538 * @param context Context for finding out the density of the screen.
2539 * @return int desired width for thumbnail screenshot.
2540 */
2541 /* package */ static int getDesiredThumbnailWidth(Context context) {
2542 if (THUMBNAIL_WIDTH == 0) {
2543 float density = context.getResources().getDisplayMetrics().density;
2544 THUMBNAIL_WIDTH = (int) (90 * density);
2545 THUMBNAIL_HEIGHT = (int) (80 * density);
2546 }
2547 return THUMBNAIL_WIDTH;
2548 }
2549
2550 /**
2551 * Return the desired height for thumbnail screenshots, which are stored in
2552 * the database, and used on the bookmarks screen.
2553 * @param context Context for finding out the density of the screen.
2554 * @return int desired height for thumbnail screenshot.
2555 */
2556 /* package */ static int getDesiredThumbnailHeight(Context context) {
2557 // To ensure that they are both initialized.
2558 getDesiredThumbnailWidth(context);
2559 return THUMBNAIL_HEIGHT;
2560 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002561
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002562 private Bitmap createScreenshot(WebView view) {
2563 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002564 if (thumbnail == null) {
2565 return null;
2566 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002567 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2568 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002569 Canvas canvas = new Canvas(bm);
2570 // May need to tweak these values to determine what is the
2571 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002572 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002573 int thumbnailHeight = thumbnail.getHeight();
2574 float scaleFactorX = 1.0f;
2575 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002576 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002577 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002578 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002579 } else {
2580 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002581 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002582
2583 if (view.getWidth() > view.getHeight() &&
2584 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2585 // If the device is in landscape and the page is shorter
2586 // than the height of the view, stretch the thumbnail to fill the
2587 // space.
2588 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2589 (float)thumbnailHeight;
2590 } else {
2591 // In the portrait case, this looks nice.
2592 scaleFactorY = scaleFactorX;
2593 }
2594
2595 canvas.scale(scaleFactorX, scaleFactorY);
2596
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002597 thumbnail.draw(canvas);
2598 return bm;
2599 }
2600
The Android Open Source Project0c908882009-03-03 19:32:16 -08002601 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 //-------------------------------------------------------------------------
2604
2605 // Use in overrideUrlLoading
2606 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2607 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2608 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2609 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2610
Leon Scroggins92472e82010-02-17 16:32:28 -05002611 // Keep this initial progress in sync with initialProgressValue (* 100)
2612 // in ProgressTracker.cpp
2613 private final static int INITIAL_PROGRESS = 10;
2614
Grace Kloba22ac16e2009-10-07 18:00:23 -07002615 void onPageStarted(WebView view, String url, Bitmap favicon) {
2616 // when BrowserActivity just starts, onPageStarted may be called before
2617 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2618 // to start the timer. As we won't switch tabs while an activity is in
2619 // pause state, we can ensure calling resume and pause in pair.
2620 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002621
Grace Kloba22ac16e2009-10-07 18:00:23 -07002622 resetLockIcon(url);
2623 setUrlTitle(url, null);
2624 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002625 // Show some progress so that the user knows the page is beginning to
2626 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002627 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002628 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002630
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 if (mSettings.isTracing()) {
2632 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002633 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002634 WebAddress uri = new WebAddress(url);
2635 host = uri.mHost;
2636 } catch (android.net.ParseException ex) {
2637 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 host = host.replace('.', '_');
2640 host += ".trace";
2641 mInTrace = true;
2642 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2643 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644
Grace Kloba22ac16e2009-10-07 18:00:23 -07002645 // Performance probe
2646 if (false) {
2647 mStart = SystemClock.uptimeMillis();
2648 mProcessStart = Process.getElapsedCpuTime();
2649 long[] sysCpu = new long[7];
2650 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2651 sysCpu, null)) {
2652 mUserStart = sysCpu[0] + sysCpu[1];
2653 mSystemStart = sysCpu[2];
2654 mIdleStart = sysCpu[3];
2655 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2656 }
2657 mUiStart = SystemClock.currentThreadTimeMillis();
2658 }
2659 }
2660
2661 void onPageFinished(WebView view, String url) {
2662 // Reset the title and icon in case we stopped a provisional load.
2663 resetTitleAndIcon(view);
2664 // Update the lock icon image only once we are done loading
2665 updateLockIconToLatest();
2666 // pause the WebView timer and release the wake lock if it is finished
2667 // while BrowserActivity is in pause state.
2668 if (mActivityInPause && pauseWebViewTimers()) {
2669 if (mWakeLock.isHeld()) {
2670 mHandler.removeMessages(RELEASE_WAKELOCK);
2671 mWakeLock.release();
2672 }
2673 }
2674
2675 // Performance probe
2676 if (false) {
2677 long[] sysCpu = new long[7];
2678 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2679 sysCpu, null)) {
2680 String uiInfo = "UI thread used "
2681 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2682 + " ms";
2683 if (LOGD_ENABLED) {
2684 Log.d(LOGTAG, uiInfo);
2685 }
2686 //The string that gets written to the log
2687 String performanceString = "It took total "
2688 + (SystemClock.uptimeMillis() - mStart)
2689 + " ms clock time to load the page."
2690 + "\nbrowser process used "
2691 + (Process.getElapsedCpuTime() - mProcessStart)
2692 + " ms, user processes used "
2693 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2694 + " ms, kernel used "
2695 + (sysCpu[2] - mSystemStart) * 10
2696 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2697 + " ms and irq took "
2698 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2699 * 10 + " ms, " + uiInfo;
2700 if (LOGD_ENABLED) {
2701 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2702 }
2703 if (url != null) {
2704 // strip the url to maintain consistency
2705 String newUrl = new String(url);
2706 if (newUrl.startsWith("http://www.")) {
2707 newUrl = newUrl.substring(11);
2708 } else if (newUrl.startsWith("http://")) {
2709 newUrl = newUrl.substring(7);
2710 } else if (newUrl.startsWith("https://www.")) {
2711 newUrl = newUrl.substring(12);
2712 } else if (newUrl.startsWith("https://")) {
2713 newUrl = newUrl.substring(8);
2714 }
2715 if (LOGD_ENABLED) {
2716 Log.d(LOGTAG, newUrl + " loaded");
2717 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002718 }
2719 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002721
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 if (mInTrace) {
2723 mInTrace = false;
2724 Debug.stopMethodTracing();
2725 }
2726 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002727
Grace Kloba22ac16e2009-10-07 18:00:23 -07002728 boolean shouldOverrideUrlLoading(WebView view, String url) {
2729 if (url.startsWith(SCHEME_WTAI)) {
2730 // wtai://wp/mc;number
2731 // number=string(phone-number)
2732 if (url.startsWith(SCHEME_WTAI_MC)) {
2733 Intent intent = new Intent(Intent.ACTION_VIEW,
2734 Uri.parse(WebView.SCHEME_TEL +
2735 url.substring(SCHEME_WTAI_MC.length())));
2736 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737 return true;
2738 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002739 // wtai://wp/sd;dtmf
2740 // dtmf=string(dialstring)
2741 if (url.startsWith(SCHEME_WTAI_SD)) {
2742 // TODO: only send when there is active voice connection
2743 return false;
2744 }
2745 // wtai://wp/ap;number;name
2746 // number=string(phone-number)
2747 // name=string
2748 if (url.startsWith(SCHEME_WTAI_AP)) {
2749 // TODO
2750 return false;
2751 }
2752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753
Grace Kloba22ac16e2009-10-07 18:00:23 -07002754 // The "about:" schemes are internal to the browser; don't want these to
2755 // be dispatched to other apps.
2756 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757 return false;
2758 }
2759
Grace Kloba22ac16e2009-10-07 18:00:23 -07002760 Intent intent;
2761 // perform generic parsing of the URI to turn it into an Intent.
2762 try {
2763 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2764 } catch (URISyntaxException ex) {
2765 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2766 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767 }
2768
Grace Kloba22ac16e2009-10-07 18:00:23 -07002769 // check whether the intent can be resolved. If not, we will see
2770 // whether we can download it from the Market.
2771 if (getPackageManager().resolveActivity(intent, 0) == null) {
2772 String packagename = intent.getPackage();
2773 if (packagename != null) {
2774 intent = new Intent(Intent.ACTION_VIEW, Uri
2775 .parse("market://search?q=pname:" + packagename));
2776 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2777 startActivity(intent);
2778 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002779 } else {
2780 return false;
2781 }
2782 }
2783
Grace Kloba22ac16e2009-10-07 18:00:23 -07002784 // sanitize the Intent, ensuring web pages can not bypass browser
2785 // security (only access to BROWSABLE activities).
2786 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2787 intent.setComponent(null);
2788 try {
2789 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790 return true;
2791 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 } catch (ActivityNotFoundException ex) {
2793 // ignore the error. If no application can handle the URL,
2794 // eg about:blank, assume the browser can handle it.
2795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797 if (mMenuIsDown) {
2798 openTab(url);
2799 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800 return true;
2801 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002802 return false;
2803 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002804
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 // -------------------------------------------------------------------------
2806 // Helper function for WebChromeClient
2807 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002808
Grace Kloba22ac16e2009-10-07 18:00:23 -07002809 void onProgressChanged(WebView view, int newProgress) {
2810 mTitleBar.setProgress(newProgress);
2811 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002812
Grace Kloba22ac16e2009-10-07 18:00:23 -07002813 if (newProgress == 100) {
2814 // onProgressChanged() may continue to be called after the main
2815 // frame has finished loading, as any remaining sub frames continue
2816 // to load. We'll only get called once though with newProgress as
2817 // 100 when everything is loaded. (onPageFinished is called once
2818 // when the main frame completes loading regardless of the state of
2819 // any sub frames so calls to onProgressChanges may continue after
2820 // onPageFinished has executed)
2821 if (mInLoad) {
2822 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002823 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002824 // If the options menu is open, leave the title bar
2825 if (!mOptionsMenuOpen || !mIconView) {
2826 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002827 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002828 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 } else if (!mInLoad) {
2830 // onPageFinished may have already been called but a subframe is
2831 // still loading and updating the progress. Reset mInLoad and update
2832 // the menu items.
2833 mInLoad = true;
2834 updateInLoadMenuItems();
2835 if (!mOptionsMenuOpen || mIconView) {
2836 // This page has begun to load, so show the title bar
2837 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002838 }
2839 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002841
Grace Kloba22ac16e2009-10-07 18:00:23 -07002842 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002843 // if a view already exists then immediately terminate the new one
2844 if (mCustomView != null) {
2845 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002846 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002847 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002848
2849 // Add the custom view to its container.
2850 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2851 mCustomView = view;
2852 mCustomViewCallback = callback;
2853 // Save the menu state and set it to empty while the custom
2854 // view is showing.
2855 mOldMenuState = mMenuState;
2856 mMenuState = EMPTY_MENU;
2857 // Hide the content view.
2858 mContentView.setVisibility(View.GONE);
2859 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002860 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002861 mCustomViewContainer.setVisibility(View.VISIBLE);
2862 mCustomViewContainer.bringToFront();
2863 }
2864
2865 void onHideCustomView() {
2866 if (mCustomView == null)
2867 return;
2868
2869 // Hide the custom view.
2870 mCustomView.setVisibility(View.GONE);
2871 // Remove the custom view from its container.
2872 mCustomViewContainer.removeView(mCustomView);
2873 mCustomView = null;
2874 // Reset the old menu state.
2875 mMenuState = mOldMenuState;
2876 mOldMenuState = EMPTY_MENU;
2877 mCustomViewContainer.setVisibility(View.GONE);
2878 mCustomViewCallback.onCustomViewHidden();
2879 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002880 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002881 mContentView.setVisibility(View.VISIBLE);
2882 }
2883
2884 Bitmap getDefaultVideoPoster() {
2885 if (mDefaultVideoPoster == null) {
2886 mDefaultVideoPoster = BitmapFactory.decodeResource(
2887 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002888 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002889 return mDefaultVideoPoster;
2890 }
Patrick Scott3918d442009-08-04 13:22:29 -04002891
Grace Kloba22ac16e2009-10-07 18:00:23 -07002892 View getVideoLoadingProgressView() {
2893 if (mVideoProgressView == null) {
2894 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2895 mVideoProgressView = inflater.inflate(
2896 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002897 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002898 return mVideoProgressView;
2899 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002900
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002901 /*
2902 * The Object used to inform the WebView of the file to upload.
2903 */
2904 private ValueCallback<Uri> mUploadMessage;
2905
Grace Kloba22ac16e2009-10-07 18:00:23 -07002906 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2907 if (mUploadMessage != null) return;
2908 mUploadMessage = uploadMsg;
2909 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2910 i.addCategory(Intent.CATEGORY_OPENABLE);
2911 i.setType("*/*");
2912 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2913 getString(R.string.choose_upload)), FILE_SELECTED);
2914 }
2915
2916 // -------------------------------------------------------------------------
2917 // Implement functions for DownloadListener
2918 // -------------------------------------------------------------------------
2919
The Android Open Source Project0c908882009-03-03 19:32:16 -08002920 /**
2921 * Notify the host application a download should be done, or that
2922 * the data should be streamed if a streaming viewer is available.
2923 * @param url The full url to the content that should be downloaded
2924 * @param contentDisposition Content-disposition http header, if
2925 * present.
2926 * @param mimetype The mimetype of the content reported by the server
2927 * @param contentLength The file size reported by the server
2928 */
2929 public void onDownloadStart(String url, String userAgent,
2930 String contentDisposition, String mimetype, long contentLength) {
2931 // if we're dealing wih A/V content that's not explicitly marked
2932 // for download, check if it's streamable.
2933 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002934 || !contentDisposition.regionMatches(
2935 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936 // query the package manager to see if there's a registered handler
2937 // that matches.
2938 Intent intent = new Intent(Intent.ACTION_VIEW);
2939 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002940 ResolveInfo info = getPackageManager().resolveActivity(intent,
2941 PackageManager.MATCH_DEFAULT_ONLY);
2942 if (info != null) {
2943 ComponentName myName = getComponentName();
2944 // If we resolved to ourselves, we don't want to attempt to
2945 // load the url only to try and download it again.
2946 if (!myName.getPackageName().equals(
2947 info.activityInfo.packageName)
2948 || !myName.getClassName().equals(
2949 info.activityInfo.name)) {
2950 // someone (other than us) knows how to handle this mime
2951 // type with this scheme, don't download.
2952 try {
2953 startActivity(intent);
2954 return;
2955 } catch (ActivityNotFoundException ex) {
2956 if (LOGD_ENABLED) {
2957 Log.d(LOGTAG, "activity not found for " + mimetype
2958 + " over " + Uri.parse(url).getScheme(),
2959 ex);
2960 }
2961 // Best behavior is to fall back to a download in this
2962 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002963 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 }
2965 }
2966 }
2967 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2968 }
2969
2970 /**
2971 * Notify the host application a download should be done, even if there
2972 * is a streaming viewer available for thise type.
2973 * @param url The full url to the content that should be downloaded
2974 * @param contentDisposition Content-disposition http header, if
2975 * present.
2976 * @param mimetype The mimetype of the content reported by the server
2977 * @param contentLength The file size reported by the server
2978 */
2979 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2980 String contentDisposition, String mimetype, long contentLength) {
2981
2982 String filename = URLUtil.guessFileName(url,
2983 contentDisposition, mimetype);
2984
2985 // Check to see if we have an SDCard
2986 String status = Environment.getExternalStorageState();
2987 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2988 int title;
2989 String msg;
2990
2991 // Check to see if the SDCard is busy, same as the music app
2992 if (status.equals(Environment.MEDIA_SHARED)) {
2993 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2994 title = R.string.download_sdcard_busy_dlg_title;
2995 } else {
2996 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2997 title = R.string.download_no_sdcard_dlg_title;
2998 }
2999
3000 new AlertDialog.Builder(this)
3001 .setTitle(title)
3002 .setIcon(android.R.drawable.ic_dialog_alert)
3003 .setMessage(msg)
3004 .setPositiveButton(R.string.ok, null)
3005 .show();
3006 return;
3007 }
3008
3009 // java.net.URI is a lot stricter than KURL so we have to undo
3010 // KURL's percent-encoding and redo the encoding using java.net.URI.
3011 URI uri = null;
3012 try {
3013 // Undo the percent-encoding that KURL may have done.
3014 String newUrl = new String(URLUtil.decode(url.getBytes()));
3015 // Parse the url into pieces
3016 WebAddress w = new WebAddress(newUrl);
3017 String frag = null;
3018 String query = null;
3019 String path = w.mPath;
3020 // Break the path into path, query, and fragment
3021 if (path.length() > 0) {
3022 // Strip the fragment
3023 int idx = path.lastIndexOf('#');
3024 if (idx != -1) {
3025 frag = path.substring(idx + 1);
3026 path = path.substring(0, idx);
3027 }
3028 idx = path.lastIndexOf('?');
3029 if (idx != -1) {
3030 query = path.substring(idx + 1);
3031 path = path.substring(0, idx);
3032 }
3033 }
3034 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3035 query, frag);
3036 } catch (Exception e) {
3037 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3038 return;
3039 }
3040
3041 // XXX: Have to use the old url since the cookies were stored using the
3042 // old percent-encoded url.
3043 String cookies = CookieManager.getInstance().getCookie(url);
3044
3045 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003046 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3047 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3048 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3049 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003050 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003051 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003053 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3054 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3055 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3056 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3057 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003059 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060 }
3061 if (mimetype == null) {
3062 // We must have long pressed on a link or image to download it. We
3063 // are not sure of the mimetype in this case, so do a head request
3064 new FetchUrlMimeType(this).execute(values);
3065 } else {
3066 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003067 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003068 }
3069
3070 }
3071
Grace Kloba22ac16e2009-10-07 18:00:23 -07003072 // -------------------------------------------------------------------------
3073
The Android Open Source Project0c908882009-03-03 19:32:16 -08003074 /**
3075 * Resets the lock icon. This method is called when we start a new load and
3076 * know the url to be loaded.
3077 */
3078 private void resetLockIcon(String url) {
3079 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003081 updateLockIconImage(LOCK_ICON_UNSECURE);
3082 }
3083
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003085 * Update the lock icon to correspond to our latest state.
3086 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003087 private void updateLockIconToLatest() {
3088 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003089 }
3090
3091 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003092 * Updates the lock-icon image in the title-bar.
3093 */
3094 private void updateLockIconImage(int lockIconType) {
3095 Drawable d = null;
3096 if (lockIconType == LOCK_ICON_SECURE) {
3097 d = mSecLockIcon;
3098 } else if (lockIconType == LOCK_ICON_MIXED) {
3099 d = mMixLockIcon;
3100 }
Leon Scroggins68579392009-09-15 15:31:54 -04003101 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003102 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003103 }
3104
3105 /**
3106 * Displays a page-info dialog.
3107 * @param tab The tab to show info about
3108 * @param fromShowSSLCertificateOnError The flag that indicates whether
3109 * this dialog was opened from the SSL-certificate-on-error dialog or
3110 * not. This is important, since we need to know whether to return to
3111 * the parent dialog or simply dismiss.
3112 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003113 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003114 final boolean fromShowSSLCertificateOnError) {
3115 final LayoutInflater factory = LayoutInflater
3116 .from(this);
3117
3118 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3119
3120 final WebView view = tab.getWebView();
3121
3122 String url = null;
3123 String title = null;
3124
3125 if (view == null) {
3126 url = tab.getUrl();
3127 title = tab.getTitle();
3128 } else if (view == mTabControl.getCurrentWebView()) {
3129 // Use the cached title and url if this is the current WebView
3130 url = mUrl;
3131 title = mTitle;
3132 } else {
3133 url = view.getUrl();
3134 title = view.getTitle();
3135 }
3136
3137 if (url == null) {
3138 url = "";
3139 }
3140 if (title == null) {
3141 title = "";
3142 }
3143
3144 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3145 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3146
3147 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003148 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003149
3150 AlertDialog.Builder alertDialogBuilder =
3151 new AlertDialog.Builder(this)
3152 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3153 .setView(pageInfoView)
3154 .setPositiveButton(
3155 R.string.ok,
3156 new DialogInterface.OnClickListener() {
3157 public void onClick(DialogInterface dialog,
3158 int whichButton) {
3159 mPageInfoDialog = null;
3160 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003161
3162 // if we came here from the SSL error dialog
3163 if (fromShowSSLCertificateOnError) {
3164 // go back to the SSL error dialog
3165 showSSLCertificateOnError(
3166 mSSLCertificateOnErrorView,
3167 mSSLCertificateOnErrorHandler,
3168 mSSLCertificateOnErrorError);
3169 }
3170 }
3171 })
3172 .setOnCancelListener(
3173 new DialogInterface.OnCancelListener() {
3174 public void onCancel(DialogInterface dialog) {
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
3189 // if we have a main top-level page SSL certificate set or a certificate
3190 // error
3191 if (fromShowSSLCertificateOnError ||
3192 (view != null && view.getCertificate() != null)) {
3193 // add a 'View Certificate' button
3194 alertDialogBuilder.setNeutralButton(
3195 R.string.view_certificate,
3196 new DialogInterface.OnClickListener() {
3197 public void onClick(DialogInterface dialog,
3198 int whichButton) {
3199 mPageInfoDialog = null;
3200 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003201
3202 // if we came here from the SSL error dialog
3203 if (fromShowSSLCertificateOnError) {
3204 // go back to the SSL error dialog
3205 showSSLCertificateOnError(
3206 mSSLCertificateOnErrorView,
3207 mSSLCertificateOnErrorHandler,
3208 mSSLCertificateOnErrorError);
3209 } else {
3210 // otherwise, display the top-most certificate from
3211 // the chain
3212 if (view.getCertificate() != null) {
3213 showSSLCertificate(tab);
3214 }
3215 }
3216 }
3217 });
3218 }
3219
3220 mPageInfoDialog = alertDialogBuilder.show();
3221 }
3222
3223 /**
3224 * Displays the main top-level page SSL certificate dialog
3225 * (accessible from the Page-Info dialog).
3226 * @param tab The tab to show certificate for.
3227 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003228 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003229 final View certificateView =
3230 inflateCertificateView(tab.getWebView().getCertificate());
3231 if (certificateView == null) {
3232 return;
3233 }
3234
3235 LayoutInflater factory = LayoutInflater.from(this);
3236
3237 final LinearLayout placeholder =
3238 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3239
3240 LinearLayout ll = (LinearLayout) factory.inflate(
3241 R.layout.ssl_success, placeholder);
3242 ((TextView)ll.findViewById(R.id.success))
3243 .setText(R.string.ssl_certificate_is_valid);
3244
3245 mSSLCertificateView = tab;
3246 mSSLCertificateDialog =
3247 new AlertDialog.Builder(this)
3248 .setTitle(R.string.ssl_certificate).setIcon(
3249 R.drawable.ic_dialog_browser_certificate_secure)
3250 .setView(certificateView)
3251 .setPositiveButton(R.string.ok,
3252 new DialogInterface.OnClickListener() {
3253 public void onClick(DialogInterface dialog,
3254 int whichButton) {
3255 mSSLCertificateDialog = null;
3256 mSSLCertificateView = null;
3257
3258 showPageInfo(tab, false);
3259 }
3260 })
3261 .setOnCancelListener(
3262 new DialogInterface.OnCancelListener() {
3263 public void onCancel(DialogInterface dialog) {
3264 mSSLCertificateDialog = null;
3265 mSSLCertificateView = null;
3266
3267 showPageInfo(tab, false);
3268 }
3269 })
3270 .show();
3271 }
3272
3273 /**
3274 * Displays the SSL error certificate dialog.
3275 * @param view The target web-view.
3276 * @param handler The SSL error handler responsible for cancelling the
3277 * connection that resulted in an SSL error or proceeding per user request.
3278 * @param error The SSL error object.
3279 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003280 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003281 final WebView view, final SslErrorHandler handler, final SslError error) {
3282
3283 final View certificateView =
3284 inflateCertificateView(error.getCertificate());
3285 if (certificateView == null) {
3286 return;
3287 }
3288
3289 LayoutInflater factory = LayoutInflater.from(this);
3290
3291 final LinearLayout placeholder =
3292 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3293
3294 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3295 LinearLayout ll = (LinearLayout)factory
3296 .inflate(R.layout.ssl_warning, placeholder);
3297 ((TextView)ll.findViewById(R.id.warning))
3298 .setText(R.string.ssl_untrusted);
3299 }
3300
3301 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3302 LinearLayout ll = (LinearLayout)factory
3303 .inflate(R.layout.ssl_warning, placeholder);
3304 ((TextView)ll.findViewById(R.id.warning))
3305 .setText(R.string.ssl_mismatch);
3306 }
3307
3308 if (error.hasError(SslError.SSL_EXPIRED)) {
3309 LinearLayout ll = (LinearLayout)factory
3310 .inflate(R.layout.ssl_warning, placeholder);
3311 ((TextView)ll.findViewById(R.id.warning))
3312 .setText(R.string.ssl_expired);
3313 }
3314
3315 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3316 LinearLayout ll = (LinearLayout)factory
3317 .inflate(R.layout.ssl_warning, placeholder);
3318 ((TextView)ll.findViewById(R.id.warning))
3319 .setText(R.string.ssl_not_yet_valid);
3320 }
3321
3322 mSSLCertificateOnErrorHandler = handler;
3323 mSSLCertificateOnErrorView = view;
3324 mSSLCertificateOnErrorError = error;
3325 mSSLCertificateOnErrorDialog =
3326 new AlertDialog.Builder(this)
3327 .setTitle(R.string.ssl_certificate).setIcon(
3328 R.drawable.ic_dialog_browser_certificate_partially_secure)
3329 .setView(certificateView)
3330 .setPositiveButton(R.string.ok,
3331 new DialogInterface.OnClickListener() {
3332 public void onClick(DialogInterface dialog,
3333 int whichButton) {
3334 mSSLCertificateOnErrorDialog = null;
3335 mSSLCertificateOnErrorView = null;
3336 mSSLCertificateOnErrorHandler = null;
3337 mSSLCertificateOnErrorError = null;
3338
Grace Kloba22ac16e2009-10-07 18:00:23 -07003339 view.getWebViewClient().onReceivedSslError(
3340 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003341 }
3342 })
3343 .setNeutralButton(R.string.page_info_view,
3344 new DialogInterface.OnClickListener() {
3345 public void onClick(DialogInterface dialog,
3346 int whichButton) {
3347 mSSLCertificateOnErrorDialog = null;
3348
3349 // do not clear the dialog state: we will
3350 // need to show the dialog again once the
3351 // user is done exploring the page-info details
3352
3353 showPageInfo(mTabControl.getTabFromView(view),
3354 true);
3355 }
3356 })
3357 .setOnCancelListener(
3358 new DialogInterface.OnCancelListener() {
3359 public void onCancel(DialogInterface dialog) {
3360 mSSLCertificateOnErrorDialog = null;
3361 mSSLCertificateOnErrorView = null;
3362 mSSLCertificateOnErrorHandler = null;
3363 mSSLCertificateOnErrorError = null;
3364
Grace Kloba22ac16e2009-10-07 18:00:23 -07003365 view.getWebViewClient().onReceivedSslError(
3366 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003367 }
3368 })
3369 .show();
3370 }
3371
3372 /**
3373 * Inflates the SSL certificate view (helper method).
3374 * @param certificate The SSL certificate.
3375 * @return The resultant certificate view with issued-to, issued-by,
3376 * issued-on, expires-on, and possibly other fields set.
3377 * If the input certificate is null, returns null.
3378 */
3379 private View inflateCertificateView(SslCertificate certificate) {
3380 if (certificate == null) {
3381 return null;
3382 }
3383
3384 LayoutInflater factory = LayoutInflater.from(this);
3385
3386 View certificateView = factory.inflate(
3387 R.layout.ssl_certificate, null);
3388
3389 // issued to:
3390 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3391 if (issuedTo != null) {
3392 ((TextView) certificateView.findViewById(R.id.to_common))
3393 .setText(issuedTo.getCName());
3394 ((TextView) certificateView.findViewById(R.id.to_org))
3395 .setText(issuedTo.getOName());
3396 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3397 .setText(issuedTo.getUName());
3398 }
3399
3400 // issued by:
3401 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3402 if (issuedBy != null) {
3403 ((TextView) certificateView.findViewById(R.id.by_common))
3404 .setText(issuedBy.getCName());
3405 ((TextView) certificateView.findViewById(R.id.by_org))
3406 .setText(issuedBy.getOName());
3407 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3408 .setText(issuedBy.getUName());
3409 }
3410
3411 // issued on:
3412 String issuedOn = reformatCertificateDate(
3413 certificate.getValidNotBefore());
3414 ((TextView) certificateView.findViewById(R.id.issued_on))
3415 .setText(issuedOn);
3416
3417 // expires on:
3418 String expiresOn = reformatCertificateDate(
3419 certificate.getValidNotAfter());
3420 ((TextView) certificateView.findViewById(R.id.expires_on))
3421 .setText(expiresOn);
3422
3423 return certificateView;
3424 }
3425
3426 /**
3427 * Re-formats the certificate date (Date.toString()) string to
3428 * a properly localized date string.
3429 * @return Properly localized version of the certificate date string and
3430 * the original certificate date string if fails to localize.
3431 * If the original string is null, returns an empty string "".
3432 */
3433 private String reformatCertificateDate(String certificateDate) {
3434 String reformattedDate = null;
3435
3436 if (certificateDate != null) {
3437 Date date = null;
3438 try {
3439 date = java.text.DateFormat.getInstance().parse(certificateDate);
3440 } catch (ParseException e) {
3441 date = null;
3442 }
3443
3444 if (date != null) {
3445 reformattedDate =
3446 DateFormat.getDateFormat(this).format(date);
3447 }
3448 }
3449
3450 return reformattedDate != null ? reformattedDate :
3451 (certificateDate != null ? certificateDate : "");
3452 }
3453
3454 /**
3455 * Displays an http-authentication dialog.
3456 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003457 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003458 final String host, final String realm, final String title,
3459 final String name, final String password, int focusId) {
3460 LayoutInflater factory = LayoutInflater.from(this);
3461 final View v = factory
3462 .inflate(R.layout.http_authentication, null);
3463 if (name != null) {
3464 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3465 }
3466 if (password != null) {
3467 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3468 }
3469
3470 String titleText = title;
3471 if (titleText == null) {
3472 titleText = getText(R.string.sign_in_to).toString().replace(
3473 "%s1", host).replace("%s2", realm);
3474 }
3475
3476 mHttpAuthHandler = handler;
3477 AlertDialog dialog = new AlertDialog.Builder(this)
3478 .setTitle(titleText)
3479 .setIcon(android.R.drawable.ic_dialog_alert)
3480 .setView(v)
3481 .setPositiveButton(R.string.action,
3482 new DialogInterface.OnClickListener() {
3483 public void onClick(DialogInterface dialog,
3484 int whichButton) {
3485 String nm = ((EditText) v
3486 .findViewById(R.id.username_edit))
3487 .getText().toString();
3488 String pw = ((EditText) v
3489 .findViewById(R.id.password_edit))
3490 .getText().toString();
3491 BrowserActivity.this.setHttpAuthUsernamePassword
3492 (host, realm, nm, pw);
3493 handler.proceed(nm, pw);
3494 mHttpAuthenticationDialog = null;
3495 mHttpAuthHandler = null;
3496 }})
3497 .setNegativeButton(R.string.cancel,
3498 new DialogInterface.OnClickListener() {
3499 public void onClick(DialogInterface dialog,
3500 int whichButton) {
3501 handler.cancel();
3502 BrowserActivity.this.resetTitleAndRevertLockIcon();
3503 mHttpAuthenticationDialog = null;
3504 mHttpAuthHandler = null;
3505 }})
3506 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3507 public void onCancel(DialogInterface dialog) {
3508 handler.cancel();
3509 BrowserActivity.this.resetTitleAndRevertLockIcon();
3510 mHttpAuthenticationDialog = null;
3511 mHttpAuthHandler = null;
3512 }})
3513 .create();
3514 // Make the IME appear when the dialog is displayed if applicable.
3515 dialog.getWindow().setSoftInputMode(
3516 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3517 dialog.show();
3518 if (focusId != 0) {
3519 dialog.findViewById(focusId).requestFocus();
3520 } else {
3521 v.findViewById(R.id.username_edit).requestFocus();
3522 }
3523 mHttpAuthenticationDialog = dialog;
3524 }
3525
3526 public int getProgress() {
3527 WebView w = mTabControl.getCurrentWebView();
3528 if (w != null) {
3529 return w.getProgress();
3530 } else {
3531 return 100;
3532 }
3533 }
3534
3535 /**
3536 * Set HTTP authentication password.
3537 *
3538 * @param host The host for the password
3539 * @param realm The realm for the password
3540 * @param username The username for the password. If it is null, it means
3541 * password can't be saved.
3542 * @param password The password
3543 */
3544 public void setHttpAuthUsernamePassword(String host, String realm,
3545 String username,
3546 String password) {
3547 WebView w = mTabControl.getCurrentWebView();
3548 if (w != null) {
3549 w.setHttpAuthUsernamePassword(host, realm, username, password);
3550 }
3551 }
3552
3553 /**
3554 * connectivity manager says net has come or gone... inform the user
3555 * @param up true if net has come up, false if net has gone down
3556 */
3557 public void onNetworkToggle(boolean up) {
3558 if (up == mIsNetworkUp) {
3559 return;
3560 } else if (up) {
3561 mIsNetworkUp = true;
3562 if (mAlertDialog != null) {
3563 mAlertDialog.cancel();
3564 mAlertDialog = null;
3565 }
3566 } else {
3567 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003568 if (mInLoad) {
3569 createAndShowNetworkDialog();
3570 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571 }
3572 WebView w = mTabControl.getCurrentWebView();
3573 if (w != null) {
3574 w.setNetworkAvailable(up);
3575 }
3576 }
3577
Grace Kloba22ac16e2009-10-07 18:00:23 -07003578 boolean isNetworkUp() {
3579 return mIsNetworkUp;
3580 }
3581
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003582 // This method shows the network dialog alerting the user that the net is
3583 // down. It will only show the dialog if mAlertDialog is null.
3584 private void createAndShowNetworkDialog() {
3585 if (mAlertDialog == null) {
3586 mAlertDialog = new AlertDialog.Builder(this)
3587 .setTitle(R.string.loadSuspendedTitle)
3588 .setMessage(R.string.loadSuspended)
3589 .setPositiveButton(R.string.ok, null)
3590 .show();
3591 }
3592 }
3593
The Android Open Source Project0c908882009-03-03 19:32:16 -08003594 @Override
3595 protected void onActivityResult(int requestCode, int resultCode,
3596 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003597 if (getTopWindow() == null) return;
3598
The Android Open Source Project0c908882009-03-03 19:32:16 -08003599 switch (requestCode) {
3600 case COMBO_PAGE:
3601 if (resultCode == RESULT_OK && intent != null) {
3602 String data = intent.getAction();
3603 Bundle extras = intent.getExtras();
3604 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003605 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003607 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003609 dismissSubWindow(currentTab);
3610 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003611 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612 }
3613 }
3614 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003615 // Deliberately fall through to PREFERENCES_PAGE, since the
3616 // same extra may be attached to the COMBO_PAGE
3617 case PREFERENCES_PAGE:
3618 if (resultCode == RESULT_OK && intent != null) {
3619 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3620 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3621 mTabControl.removeParentChildRelationShips();
3622 }
3623 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003624 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003625 // Choose a file from the file picker.
3626 case FILE_SELECTED:
3627 if (null == mUploadMessage) break;
3628 Uri result = intent == null || resultCode != RESULT_OK ? null
3629 : intent.getData();
3630 mUploadMessage.onReceiveValue(result);
3631 mUploadMessage = null;
3632 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 default:
3634 break;
3635 }
Leon Scroggins30444232009-09-04 18:36:20 -04003636 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637 }
3638
3639 /*
3640 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003641 * menu to see the download window. It shows the download window on top of
3642 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003644 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003645 Intent intent = new Intent(this,
3646 BrowserDownloadPage.class);
3647 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003648 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649
3650 }
3651
Leon Scroggins160a7e72009-08-14 18:28:01 -04003652 /**
3653 * Open the Go page.
3654 * @param startWithHistory If true, open starting on the history tab.
3655 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003656 */
Leon Scroggins30444232009-09-04 18:36:20 -04003657 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003658 WebView current = mTabControl.getCurrentWebView();
3659 if (current == null) {
3660 return;
3661 }
3662 Intent intent = new Intent(this,
3663 CombinedBookmarkHistoryActivity.class);
3664 String title = current.getTitle();
3665 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003666 Bitmap thumbnail = createScreenshot(current);
3667
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 // Just in case the user opens bookmarks before a page finishes loading
3669 // so the current history item, and therefore the page, is null.
3670 if (null == url) {
3671 url = mLastEnteredUrl;
3672 // This can happen.
3673 if (null == url) {
3674 url = mSettings.getHomePage();
3675 }
3676 }
3677 // In case the web page has not yet received its associated title.
3678 if (title == null) {
3679 title = url;
3680 }
3681 intent.putExtra("title", title);
3682 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003683 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003684 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003685 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003686 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003687 if (startWithHistory) {
3688 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3689 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3690 }
3691 startActivityForResult(intent, COMBO_PAGE);
3692 }
3693
3694 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003695 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 // In case the user enters nothing.
3697 if (url != null && url.length() != 0 && view != null) {
3698 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003699 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003700 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701 }
3702 }
3703 }
3704
Leon Scroggins92472e82010-02-17 16:32:28 -05003705 /**
3706 * Load the URL into the given WebView and update the title bar
3707 * to reflect the new load. Call this instead of WebView.loadUrl
3708 * directly.
3709 * @param view The WebView used to load url.
3710 * @param url The URL to load.
3711 */
3712 private void loadUrl(WebView view, String url) {
3713 updateTitleBarForNewLoad(view, url);
3714 view.loadUrl(url);
3715 }
3716
3717 /**
3718 * Load UrlData into a Tab and update the title bar to reflect the new
3719 * load. Call this instead of UrlData.loadIn directly.
3720 * @param t The Tab used to load.
3721 * @param data The UrlData being loaded.
3722 */
3723 private void loadUrlDataIn(Tab t, UrlData data) {
3724 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3725 data.loadIn(t);
3726 }
3727
3728 /**
3729 * If the WebView is the top window, update the title bar to reflect
3730 * loading the new URL. i.e. set its text, clear the favicon (which
3731 * will be set once the page begins loading), and set the progress to
3732 * INITIAL_PROGRESS to show that the page has begun to load. Called
3733 * by loadUrl and loadUrlDataIn.
3734 * @param view The WebView that is starting a load.
3735 * @param url The URL that is being loaded.
3736 */
3737 private void updateTitleBarForNewLoad(WebView view, String url) {
3738 if (view == getTopWindow()) {
3739 setUrlTitle(url, null);
3740 setFavicon(null);
3741 onProgressChanged(view, INITIAL_PROGRESS);
3742 }
3743 }
3744
The Android Open Source Project0c908882009-03-03 19:32:16 -08003745 private String smartUrlFilter(Uri inUri) {
3746 if (inUri != null) {
3747 return smartUrlFilter(inUri.toString());
3748 }
3749 return null;
3750 }
3751
Feng Qianb34f87a2009-03-24 21:27:26 -07003752 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003753 "(?i)" + // switch on case insensitive matching
3754 "(" + // begin group for schema
3755 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003756 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003757 ")" +
3758 "(.*)" );
3759
3760 /**
3761 * Attempts to determine whether user input is a URL or search
3762 * terms. Anything with a space is passed to search.
3763 *
3764 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3765 * "Http://" converts to "http://"
3766 *
3767 * @return Original or modified URL
3768 *
3769 */
3770 String smartUrlFilter(String url) {
3771
3772 String inUrl = url.trim();
3773 boolean hasSpace = inUrl.indexOf(' ') != -1;
3774
3775 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3776 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 // force scheme to lowercase
3778 String scheme = matcher.group(1);
3779 String lcScheme = scheme.toLowerCase();
3780 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003781 inUrl = lcScheme + matcher.group(2);
3782 }
3783 if (hasSpace) {
3784 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003785 }
3786 return inUrl;
3787 }
3788 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003789 // FIXME: Is this the correct place to add to searches?
3790 // what if someone else calls this function?
3791 int shortcut = parseUrlShortcut(inUrl);
3792 if (shortcut != SHORTCUT_INVALID) {
3793 Browser.addSearchUrl(mResolver, inUrl);
3794 String query = inUrl.substring(2);
3795 switch (shortcut) {
3796 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003797 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003798 case SHORTCUT_WIKIPEDIA_SEARCH:
3799 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3800 case SHORTCUT_DICTIONARY_SEARCH:
3801 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3802 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003803 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003804 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805 }
3806 }
3807 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003808 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003809 return URLUtil.guessUrl(inUrl);
3810 }
3811 }
3812
3813 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003814 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 }
3816
Ben Murdochbff2d602009-07-01 20:19:05 +01003817 /* package */ void setShouldShowErrorConsole(boolean flag) {
3818 if (flag == mShouldShowErrorConsole) {
3819 // Nothing to do.
3820 return;
3821 }
3822
3823 mShouldShowErrorConsole = flag;
3824
Grace Kloba22ac16e2009-10-07 18:00:23 -07003825 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3826 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003827
3828 if (flag) {
3829 // Setting the show state of the console will cause it's the layout to be inflated.
3830 if (errorConsole.numberOfErrors() > 0) {
3831 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3832 } else {
3833 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3834 }
3835
3836 // Now we can add it to the main view.
3837 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003838 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003839 ViewGroup.LayoutParams.WRAP_CONTENT));
3840 } else {
3841 mErrorConsoleContainer.removeView(errorConsole);
3842 }
3843
3844 }
3845
Grace Kloba22ac16e2009-10-07 18:00:23 -07003846 boolean shouldShowErrorConsole() {
3847 return mShouldShowErrorConsole;
3848 }
3849
Andrei Popescu163ab742009-10-20 17:58:23 +01003850 private void setStatusBarVisibility(boolean visible) {
3851 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3852 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3853 }
3854
Andrei Popescu56199cc2010-01-12 22:39:16 +00003855
3856 private void sendNetworkType(String type, String subtype) {
3857 WebView w = mTabControl.getCurrentWebView();
3858 if (w != null) {
3859 w.setNetworkType(type, subtype);
3860 }
3861 }
3862
Andrei Popescu30995e72010-02-09 16:59:58 +00003863 private void packageChanged(String packageName, boolean wasAdded) {
3864 WebView w = mTabControl.getCurrentWebView();
3865 if (w == null) {
3866 return;
3867 }
3868
3869 if (wasAdded) {
3870 w.addPackageName(packageName);
3871 } else {
3872 w.removePackageName(packageName);
3873 }
3874 }
3875
3876 private void addPackageNames(Set<String> packageNames) {
3877 WebView w = mTabControl.getCurrentWebView();
3878 if (w == null) {
3879 return;
3880 }
3881
3882 w.addPackageNames(packageNames);
3883 }
3884
3885 private void getInstalledPackages() {
3886 AsyncTask<Void, Void, Set<String> > task =
3887 new AsyncTask<Void, Void, Set<String> >() {
3888 protected Set<String> doInBackground(Void... unused) {
3889 Set<String> installedPackages = new HashSet<String>();
3890 PackageManager pm = BrowserActivity.this.getPackageManager();
3891 if (pm != null) {
3892 List<PackageInfo> packages = pm.getInstalledPackages(0);
3893 for (PackageInfo p : packages) {
3894 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3895 installedPackages.add(p.packageName);
3896 }
3897 }
3898 }
3899
3900 return installedPackages;
3901 }
3902
3903 // Executes on the UI thread
3904 protected void onPostExecute(Set<String> installedPackages) {
3905 addPackageNames(installedPackages);
3906 }
3907 };
3908 task.execute();
3909 }
3910
Grace Klobaeb6eef42009-09-15 17:56:32 -07003911 final static int LOCK_ICON_UNSECURE = 0;
3912 final static int LOCK_ICON_SECURE = 1;
3913 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914
The Android Open Source Project0c908882009-03-03 19:32:16 -08003915 private BrowserSettings mSettings;
3916 private TabControl mTabControl;
3917 private ContentResolver mResolver;
3918 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003919 private View mCustomView;
3920 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003921 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003922
3923 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3924 // view, we should rewrite this.
3925 private int mCurrentMenuState = 0;
3926 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003927 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003928 private static final int EMPTY_MENU = -1;
3929 private Menu mMenu;
3930
3931 private FindDialog mFindDialog;
3932 // Used to prevent chording to result in firing two shortcuts immediately
3933 // one after another. Fixes bug 1211714.
3934 boolean mCanChord;
3935
3936 private boolean mInLoad;
3937 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003938 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003939
The Android Open Source Project0c908882009-03-03 19:32:16 -08003940 private boolean mActivityInPause = true;
3941
3942 private boolean mMenuIsDown;
3943
The Android Open Source Project0c908882009-03-03 19:32:16 -08003944 private static boolean mInTrace;
3945
3946 // Performance probe
3947 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3948 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3949 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3950 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3951 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3952 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3953 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3956 };
3957
3958 private long mStart;
3959 private long mProcessStart;
3960 private long mUserStart;
3961 private long mSystemStart;
3962 private long mIdleStart;
3963 private long mIrqStart;
3964
3965 private long mUiStart;
3966
3967 private Drawable mMixLockIcon;
3968 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003969
3970 /* hold a ref so we can auto-cancel if necessary */
3971 private AlertDialog mAlertDialog;
3972
3973 // Wait for credentials before loading google.com
3974 private ProgressDialog mCredsDlg;
3975
3976 // The up-to-date URL and title (these can be different from those stored
3977 // in WebView, since it takes some time for the information in WebView to
3978 // get updated)
3979 private String mUrl;
3980 private String mTitle;
3981
3982 // As PageInfo has different style for landscape / portrait, we have
3983 // to re-open it when configuration changed
3984 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003985 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003986 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3987 // dialog, we should not just dismiss it, but should get back to the
3988 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003989 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003990
3991 // as SSLCertificateOnError has different style for landscape / portrait,
3992 // we have to re-open it when configuration changed
3993 private AlertDialog mSSLCertificateOnErrorDialog;
3994 private WebView mSSLCertificateOnErrorView;
3995 private SslErrorHandler mSSLCertificateOnErrorHandler;
3996 private SslError mSSLCertificateOnErrorError;
3997
3998 // as SSLCertificate has different style for landscape / portrait, we
3999 // have to re-open it when configuration changed
4000 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07004001 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004002
4003 // as HttpAuthentication has different style for landscape / portrait, we
4004 // have to re-open it when configuration changed
4005 private AlertDialog mHttpAuthenticationDialog;
4006 private HttpAuthHandler mHttpAuthHandler;
4007
4008 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4009 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08004010 ViewGroup.LayoutParams.MATCH_PARENT,
4011 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01004012 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
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 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004017 // Google search
4018 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 // Wikipedia search
4020 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4021 // Dictionary search
4022 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4023 // Google Mobile Local search
4024 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4025
4026 final static String QUERY_PLACE_HOLDER = "%s";
4027
4028 // "source" parameter for Google search through search key
4029 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4030 // "source" parameter for Google search through goto menu
4031 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4032 // "source" parameter for Google search through simplily type
4033 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4034 // "source" parameter for Google search suggested by the browser
4035 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4036 // "source" parameter for Google search from unknown source
4037 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4038
4039 private final static String LOGTAG = "browser";
4040
The Android Open Source Project0c908882009-03-03 19:32:16 -08004041 private String mLastEnteredUrl;
4042
4043 private PowerManager.WakeLock mWakeLock;
4044 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4045
4046 private Toast mStopToast;
4047
Leon Scroggins68579392009-09-15 15:31:54 -04004048 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04004049
Ben Murdochbff2d602009-07-01 20:19:05 +01004050 private LinearLayout mErrorConsoleContainer = null;
4051 private boolean mShouldShowErrorConsole = false;
4052
The Android Open Source Project0c908882009-03-03 19:32:16 -08004053 // As the ids are dynamically created, we can't guarantee that they will
4054 // be in sequence, so this static array maps ids to a window number.
4055 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4056 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4057 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4058 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4059
4060 // monitor platform changes
4061 private IntentFilter mNetworkStateChangedFilter;
4062 private BroadcastReceiver mNetworkStateIntentReceiver;
4063
Grace Klobab4da0ad2009-05-14 14:45:40 -07004064 private BroadcastReceiver mPackageInstallationReceiver;
4065
The Android Open Source Project0c908882009-03-03 19:32:16 -08004066 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01004067 final static int COMBO_PAGE = 1;
4068 final static int DOWNLOAD_PAGE = 2;
4069 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04004070 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004071
Andrei Popescu540035d2009-09-18 18:59:20 +01004072 // the default <video> poster
4073 private Bitmap mDefaultVideoPoster;
4074 // the video progress view
4075 private View mVideoProgressView;
4076
Andrei Popescu30995e72010-02-09 16:59:58 +00004077 // The Google packages we monitor for the navigator.isApplicationInstalled()
4078 // API. Add as needed.
4079 private static Set<String> sGoogleApps;
4080 static {
4081 sGoogleApps = new HashSet<String>();
4082 sGoogleApps.add("com.google.android.youtube");
4083 }
4084
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004085 /**
4086 * A UrlData class to abstract how the content will be set to WebView.
4087 * This base class uses loadUrl to show the content.
4088 */
4089 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08004090 final String mUrl;
4091 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004092 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07004093
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004094 UrlData(String url) {
4095 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08004096 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05004097 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004098 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004099
Leon Scroggins58d56c62010-01-28 15:12:40 -05004100 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08004101 this.mUrl = url;
4102 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05004103 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4104 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004105 this.mVoiceIntent = intent;
4106 } else {
4107 this.mVoiceIntent = null;
4108 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004109 }
4110
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004111 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05004112 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004113 }
4114
Leon Scroggins92472e82010-02-17 16:32:28 -05004115 /**
4116 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4117 * the title bar as well.
4118 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05004119 public void loadIn(Tab t) {
4120 if (mVoiceIntent != null) {
4121 t.activateVoiceSearchMode(mVoiceIntent);
4122 } else {
4123 t.getWebView().loadUrl(mUrl, mHeaders);
4124 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004125 }
4126 };
4127
Leon Scroggins1f005d32009-08-10 17:36:42 -04004128 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004129}