blob: 8d471a247c6180264e52354ad82b8aa6ae927267 [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;
76import android.view.ContextMenu;
77import android.view.Gravity;
78import android.view.KeyEvent;
79import android.view.LayoutInflater;
80import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
83import android.view.View;
84import android.view.ViewGroup;
85import android.view.Window;
86import android.view.WindowManager;
87import android.view.ContextMenu.ContextMenuInfo;
88import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.webkit.CookieManager;
90import android.webkit.CookieSyncManager;
91import android.webkit.DownloadListener;
92import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070093import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.SslErrorHandler;
95import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010096import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.WebChromeClient;
98import android.webkit.WebHistoryItem;
99import android.webkit.WebIconDatabase;
100import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.widget.EditText;
102import android.widget.FrameLayout;
103import android.widget.LinearLayout;
104import android.widget.TextView;
105import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800106import android.accounts.Account;
107import android.accounts.AccountManager;
108import android.accounts.AccountManagerFuture;
109import android.accounts.AuthenticatorException;
110import android.accounts.OperationCanceledException;
111import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112
Dan Egnor5ee906c2009-11-18 12:11:49 -0800113import com.android.common.Patterns;
114
Doug Zongker716d4f52010-01-21 14:35:23 -0800115import com.google.android.gsf.GoogleLoginServiceConstants;
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;
Grace Kloba00f54c52010-01-27 14:53:51 -0800129import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800130import java.util.Map;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131import java.util.regex.Matcher;
132import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
134public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800135 implements View.OnCreateContextMenuListener, DownloadListener,
136 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137
Dave Bort31a6d1c2009-04-13 15:56:49 -0700138 /* Define some aliases to make these debugging flags easier to refer to.
139 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
140 */
141 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
142 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
143 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
144
Satish Sampath565505b2009-05-29 15:37:27 +0100145 // These are single-character shortcuts for searching popular sources.
146 private static final int SHORTCUT_INVALID = 0;
147 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
148 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
149 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
150 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
151
Fred Quintana752b6562009-12-18 10:18:26 -0800152 private Account[] mAccountsGoogle;
153 private Account[] mAccountsPreferHosted;
154
155 private void startReadOfGoogleAccounts() {
156 mAccountsGoogle = null;
157 mAccountsPreferHosted = null;
158
159 AccountManager.get(this).getAccountsByTypeAndFeatures(
160 GoogleLoginServiceConstants.ACCOUNT_TYPE,
161 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
162 this, null);
163 }
164
165 /** This implements AccountManagerCallback<Account[]> */
166 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
167 try {
168 if (mAccountsGoogle == null) {
169 mAccountsGoogle = accountManagerFuture.getResult();
170
171 AccountManager.get(this).getAccountsByTypeAndFeatures(
172 GoogleLoginServiceConstants.ACCOUNT_TYPE,
173 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
174 this, null);
175 } else {
176 mAccountsPreferHosted = accountManagerFuture.getResult();
177 setupHomePage();
178 }
179 } catch (OperationCanceledException e) {
180 setupHomePage();
181 } catch (IOException e) {
182 setupHomePage();
183 } catch (AuthenticatorException e) {
184 setupHomePage();
185 }
186 }
187
The Android Open Source Project0c908882009-03-03 19:32:16 -0800188 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800189 // get the default home page
190 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800191
Fred Quintana752b6562009-12-18 10:18:26 -0800192 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
193 // three cases:
194 //
195 // hostedUser == googleUser
196 // The device has only a google account
197 //
198 // hostedUser != googleUser
199 // The device has a hosted account and a google account
200 //
201 // hostedUser != null, googleUser == null
202 // The device has only a hosted account (so far)
203 String hostedUser = mAccountsPreferHosted.length == 0
204 ? null
205 : mAccountsPreferHosted[0].name;
206 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207
Fred Quintana752b6562009-12-18 10:18:26 -0800208 // developers might have no accounts at all
209 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700210
Fred Quintana752b6562009-12-18 10:18:26 -0800211 if (googleUser == null || !hostedUser.equals(googleUser)) {
212 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
213 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800214 }
Fred Quintana752b6562009-12-18 10:18:26 -0800215 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800216
Fred Quintana752b6562009-12-18 10:18:26 -0800217 mSettings.setHomePage(BrowserActivity.this, homepage);
218 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800219 }
220
Cary Clarka9771242009-08-11 16:42:26 -0400221 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800222 @Override
223 public Void doInBackground(File... files) {
224 if (files != null) {
225 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400226 if (!f.delete()) {
227 Log.e(LOGTAG, f.getPath() + " was not deleted");
228 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800229 }
230 }
231 return null;
232 }
233 }
234
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400235 /**
236 * This layout holds everything you see below the status bar, including the
237 * error console, the custom view container, and the webviews.
238 */
239 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400240
Grace Kloba22ac16e2009-10-07 18:00:23 -0700241 @Override
242 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700243 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244 Log.v(LOGTAG, this + " onStart");
245 }
246 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247 // test the browser in OpenGL
248 // requestWindowFeature(Window.FEATURE_OPENGL);
249
Mike Reedd334bf52010-01-26 15:21:44 -0500250 // enable this to test the browser in 32bit
251 if (false) {
252 getWindow().setFormat(PixelFormat.RGBX_8888);
253 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
254 }
255
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
257
258 mResolver = getContentResolver();
259
Grace Kloba0923d692009-09-23 21:37:25 -0700260 // If this was a web search request, pass it on to the default web
261 // search provider and finish this activity.
262 if (handleWebSearchIntent(getIntent())) {
263 finish();
264 return;
265 }
266
The Android Open Source Project0c908882009-03-03 19:32:16 -0800267 mSecLockIcon = Resources.getSystem().getDrawable(
268 android.R.drawable.ic_secure);
269 mMixLockIcon = Resources.getSystem().getDrawable(
270 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800271
Leon Scroggins81db3662009-06-04 17:45:11 -0400272 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
273 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400274 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
275 .inflate(R.layout.custom_screen, null);
276 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
277 R.id.main_content);
278 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
279 .findViewById(R.id.error_console);
280 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
281 .findViewById(R.id.fullscreen_custom_content);
282 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400283 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400284 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800285
286 // Create the tab control and our initial tab
287 mTabControl = new TabControl(this);
288
289 // Open the icon database and retain all the bookmark urls for favicons
290 retainIconsOnStartup();
291
292 // Keep a settings instance handy.
293 mSettings = BrowserSettings.getInstance();
294 mSettings.setTabControl(mTabControl);
295 mSettings.loadFromDb(this);
296
297 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
298 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
299
Grace Klobaa34f6862009-07-31 16:28:17 -0700300 /* enables registration for changes in network status from
301 http stack */
302 mNetworkStateChangedFilter = new IntentFilter();
303 mNetworkStateChangedFilter.addAction(
304 ConnectivityManager.CONNECTIVITY_ACTION);
305 mNetworkStateIntentReceiver = new BroadcastReceiver() {
306 @Override
307 public void onReceive(Context context, Intent intent) {
308 if (intent.getAction().equals(
309 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700310 boolean noConnectivity = intent.getBooleanExtra(
311 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000312 if (!noConnectivity) {
313 NetworkInfo info = intent.getParcelableExtra(
314 ConnectivityManager.EXTRA_NETWORK_INFO);
315 String typeName = info.getTypeName();
316 String subtypeName = info.getSubtypeName();
317 sendNetworkType(typeName.toLowerCase(),
318 (subtypeName != null ? subtypeName.toLowerCase() : ""));
319 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700320 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700321 }
322 }
323 };
324
Grace Kloba615c6c92009-08-03 10:22:44 -0700325 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
326 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
327 filter.addDataScheme("package");
328 mPackageInstallationReceiver = new BroadcastReceiver() {
329 @Override
330 public void onReceive(Context context, Intent intent) {
331 final String action = intent.getAction();
332 final String packageName = intent.getData()
333 .getSchemeSpecificPart();
334 final boolean replacing = intent.getBooleanExtra(
335 Intent.EXTRA_REPLACING, false);
336 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
337 // if it is replacing, refreshPlugins() when adding
338 return;
339 }
340 PackageManager pm = BrowserActivity.this.getPackageManager();
341 PackageInfo pkgInfo = null;
342 try {
343 pkgInfo = pm.getPackageInfo(packageName,
344 PackageManager.GET_PERMISSIONS);
345 } catch (PackageManager.NameNotFoundException e) {
346 return;
347 }
348 if (pkgInfo != null) {
349 String permissions[] = pkgInfo.requestedPermissions;
350 if (permissions == null) {
351 return;
352 }
353 boolean permissionOk = false;
354 for (String permit : permissions) {
355 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
356 permissionOk = true;
357 break;
358 }
359 }
360 if (permissionOk) {
361 PluginManager.getInstance(BrowserActivity.this)
362 .refreshPlugins(
363 Intent.ACTION_PACKAGE_ADDED
364 .equals(action));
365 }
366 }
367 }
368 };
369 registerReceiver(mPackageInstallationReceiver, filter);
370
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 if (!mTabControl.restoreState(icicle)) {
372 // clear up the thumbnail directory if we can't restore the state as
373 // none of the files in the directory are referenced any more.
374 new ClearThumbnails().execute(
375 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700376 // there is no quit on Android. But if we can't restore the state,
377 // we can treat it as a new Browser, remove the old session cookies.
378 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800379 final Intent intent = getIntent();
380 final Bundle extra = intent.getExtras();
381 // Create an initial tab.
382 // If the intent is ACTION_VIEW and data is not null, the Browser is
383 // invoked to view the content by another application. In this case,
384 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 UrlData urlData = getUrlDataFromIntent(intent);
386
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700388 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500389 (Intent.ACTION_VIEW.equals(action) &&
390 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500391 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
392 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700393 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 attachTabToContentView(t);
396 WebView webView = t.getWebView();
397 if (extra != null) {
398 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
399 if (scale > 0 && scale <= 1000) {
400 webView.setInitialScale(scale);
401 }
402 }
403 // If we are not restoring from an icicle, then there is a high
404 // likely hood this is the first run. So, check to see if the
405 // homepage needs to be configured and copy any plugins from our
406 // asset directory to the data partition.
407 if ((extra == null || !extra.getBoolean("testing"))
408 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800409 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800411
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700412 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400413 if (mSettings.isLoginInitialized()) {
414 webView.loadUrl(mSettings.getHomePage());
415 } else {
416 waitForCredentials();
417 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 } else {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500419 urlData.loadIn(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 }
421 } else {
422 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400423 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 attachTabToContentView(mTabControl.getCurrentTab());
425 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700426
Feng Qianb3c02da2009-06-29 15:58:08 -0700427 // Read JavaScript flags if it exists.
428 String jsFlags = mSettings.getJsFlags();
429 if (jsFlags.trim().length() != 0) {
430 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
431 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432 }
433
Leon Scroggins58d56c62010-01-28 15:12:40 -0500434 /**
435 * Feed the previously stored results strings to the BrowserProvider so that
436 * the SearchDialog will show them instead of the standard searches.
437 * @param result String to show on the editable line of the SearchDialog.
438 */
439 /* package */ void showVoiceSearchResults(String result) {
440 ContentProviderClient client = mResolver.acquireContentProviderClient(
441 Browser.BOOKMARKS_URI);
442 ContentProvider prov = client.getLocalContentProvider();
443 BrowserProvider bp = (BrowserProvider) prov;
444 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
445 client.release();
446
447 startSearch(result, false,
448 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
449 false);
450 }
451
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 @Override
453 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700454 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800455 // When a tab is closed on exit, the current tab index is set to -1.
456 // Reset before proceed as Browser requires the current tab to be set.
457 if (current == null) {
458 // Try to reset the tab in case the index was incorrect.
459 current = mTabControl.getTab(0);
460 if (current == null) {
461 // No tabs at all so just ignore this intent.
462 return;
463 }
464 mTabControl.setCurrentTab(current);
465 attachTabToContentView(current);
466 resetTitleAndIcon(current.getWebView());
467 }
468 final String action = intent.getAction();
469 final int flags = intent.getFlags();
470 if (Intent.ACTION_MAIN.equals(action) ||
471 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
472 // just resume the browser
473 return;
474 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500475 boolean activateVoiceSearch = RecognizerResultsIntent
476 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800477 if (Intent.ACTION_VIEW.equals(action)
478 || Intent.ACTION_SEARCH.equals(action)
479 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500480 || Intent.ACTION_WEB_SEARCH.equals(action)
481 || activateVoiceSearch) {
Satish Sampath565505b2009-05-29 15:37:27 +0100482 // If this was a search request (e.g. search query directly typed into the address bar),
483 // pass it on to the default web search provider.
484 if (handleWebSearchIntent(intent)) {
485 return;
486 }
487
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700488 UrlData urlData = getUrlDataFromIntent(intent);
489 if (urlData.isEmpty()) {
490 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800491 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700492
Grace Klobacc634032009-07-28 15:58:19 -0700493 final String appId = intent
494 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500495 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700496 && !getPackageName().equals(appId)
497 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700498 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700499 if (appTab != null) {
500 Log.i(LOGTAG, "Reusing tab for " + appId);
501 // Dismiss the subwindow if applicable.
502 dismissSubWindow(appTab);
503 // Since we might kill the WebView, remove it from the
504 // content view first.
505 removeTabFromContentView(appTab);
506 // Recreate the main WebView after destroying the old one.
507 // If the WebView has the same original url and is on that
508 // page, it can be reused.
509 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700510 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100511
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700512 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 switchToTab(mTabControl.getTabIndex(appTab));
514 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500515 urlData.loadIn(appTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400516 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700517 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 // If the tab was the current tab, we have to attach
519 // it to the view system again.
520 attachTabToContentView(appTab);
521 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500522 urlData.loadIn(appTab);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700523 }
524 }
525 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400526 } else {
527 // No matching application tab, try to find a regular tab
528 // with a matching url.
529 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400530 if (appTab != null) {
531 if (current != appTab) {
532 switchToTab(mTabControl.getTabIndex(appTab));
533 }
534 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400535 } else {
536 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
537 // will be opened in a new tab unless we have reached
538 // MAX_TABS. Then the url will be opened in the current
539 // tab. If a new tab is created, it will have "true" for
540 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400541 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400542 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700543 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800544 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800545 if (!urlData.isEmpty()
546 && urlData.mUrl.startsWith("about:debug")) {
547 if ("about:debug.dom".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(false);
549 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
550 current.getWebView().dumpDomTree(true);
551 } else if ("about:debug.render".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(false);
553 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
554 current.getWebView().dumpRenderTree(true);
555 } else if ("about:debug.display".equals(urlData.mUrl)) {
556 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800557 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
558 int index = urlData.mUrl.codePointAt(16) - '0';
559 if (index <= 0 || index > 9) {
560 current.getWebView().setDragTracker(null);
561 } else {
562 current.getWebView().setDragTracker(new MeshTracker(index));
563 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800564 } else {
565 mSettings.toggleDebugSettings();
566 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800567 return;
568 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400569 // Get rid of the subwindow if it exists
570 dismissSubWindow(current);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500571 urlData.loadIn(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800572 }
573 }
574 }
575
Satish Sampath565505b2009-05-29 15:37:27 +0100576 private int parseUrlShortcut(String url) {
577 if (url == null) return SHORTCUT_INVALID;
578
579 // FIXME: quick search, need to be customized by setting
580 if (url.length() > 2 && url.charAt(1) == ' ') {
581 switch (url.charAt(0)) {
582 case 'g': return SHORTCUT_GOOGLE_SEARCH;
583 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
584 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
585 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
586 }
587 }
588 return SHORTCUT_INVALID;
589 }
590
591 /**
592 * Launches the default web search activity with the query parameters if the given intent's data
593 * are identified as plain search terms and not URLs/shortcuts.
594 * @return true if the intent was handled and web search activity was launched, false if not.
595 */
596 private boolean handleWebSearchIntent(Intent intent) {
597 if (intent == null) return false;
598
599 String url = null;
600 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500601 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
602 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500603 return false;
604 }
Satish Sampath565505b2009-05-29 15:37:27 +0100605 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700606 Uri data = intent.getData();
607 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100608 } else if (Intent.ACTION_SEARCH.equals(action)
609 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
610 || Intent.ACTION_WEB_SEARCH.equals(action)) {
611 url = intent.getStringExtra(SearchManager.QUERY);
612 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100613 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
614 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100615 }
616
617 /**
618 * Launches the default web search activity with the query parameters if the given url string
619 * was identified as plain search terms and not URL/shortcut.
620 * @return true if the request was handled and web search activity was launched, false if not.
621 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100622 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100623 if (inUrl == null) return false;
624
625 // In general, we shouldn't modify URL from Intent.
626 // But currently, we get the user-typed URL from search box as well.
627 String url = fixUrl(inUrl).trim();
628
629 // URLs and site specific search shortcuts are handled by the regular flow of control, so
630 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800631 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100632 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100633 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
634 return false;
635 }
636
637 Browser.updateVisitedHistory(mResolver, url, false);
638 Browser.addSearchUrl(mResolver, url);
639
640 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
641 intent.addCategory(Intent.CATEGORY_DEFAULT);
642 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100643 if (appData != null) {
644 intent.putExtra(SearchManager.APP_DATA, appData);
645 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100646 if (extraData != null) {
647 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
648 }
Grace Klobacc634032009-07-28 15:58:19 -0700649 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100650 startActivity(intent);
651
652 return true;
653 }
654
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700655 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500656 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800657 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
667 }
668 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800669 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800670 final Bundle pairs = intent
671 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800672 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800673 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800674 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800675 while (iter.hasNext()) {
676 String key = iter.next();
677 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800678 }
679 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800681 } else if (Intent.ACTION_SEARCH.equals(action)
682 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
683 || Intent.ACTION_WEB_SEARCH.equals(action)) {
684 url = intent.getStringExtra(SearchManager.QUERY);
685 if (url != null) {
686 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500687 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 // In general, we shouldn't modify URL from Intent.
689 // But currently, we get the user-typed URL from search box as well.
690 url = fixUrl(url);
691 url = smartUrlFilter(url);
692 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
693 if (url.contains(searchSource)) {
694 String source = null;
695 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
696 if (appData != null) {
697 source = appData.getString(SearchManager.SOURCE);
698 }
699 if (TextUtils.isEmpty(source)) {
700 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
701 }
702 url = url.replace(searchSource, "&source=android-"+source+"&");
703 }
704 }
705 }
706 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500707 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800708 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500709 /* package */ void showVoiceTitleBar(String title) {
710 mTitleBar.setInVoiceMode(true);
711 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800712
Leon Scroggins58d56c62010-01-28 15:12:40 -0500713 mTitleBar.setDisplayTitle(title);
714 mFakeTitleBar.setDisplayTitle(title);
715 }
716 /* package */ void revertVoiceTitleBar() {
717 mTitleBar.setInVoiceMode(false);
718 mFakeTitleBar.setInVoiceMode(false);
719
720 mTitleBar.setDisplayTitle(mTitle);
721 mFakeTitleBar.setDisplayTitle(mTitle);
722 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800723 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400724 // FIXME: Converting the url to lower case
725 // duplicates functionality in smartUrlFilter().
726 // However, changing all current callers of fixUrl to
727 // call smartUrlFilter in addition may have unwanted
728 // consequences, and is deferred for now.
729 int colon = inUrl.indexOf(':');
730 boolean allLower = true;
731 for (int index = 0; index < colon; index++) {
732 char ch = inUrl.charAt(index);
733 if (!Character.isLetter(ch)) {
734 break;
735 }
736 allLower &= Character.isLowerCase(ch);
737 if (index == colon - 1 && !allLower) {
738 inUrl = inUrl.substring(0, colon).toLowerCase()
739 + inUrl.substring(colon);
740 }
741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800742 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
743 return inUrl;
744 if (inUrl.startsWith("http:") ||
745 inUrl.startsWith("https:")) {
746 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
747 inUrl = inUrl.replaceFirst("/", "//");
748 } else inUrl = inUrl.replaceFirst(":", "://");
749 }
750 return inUrl;
751 }
752
Grace Kloba22ac16e2009-10-07 18:00:23 -0700753 @Override
754 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800755 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700756 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800757 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
758 }
759
760 if (!mActivityInPause) {
761 Log.e(LOGTAG, "BrowserActivity is already resumed.");
762 return;
763 }
764
Mike Reed7bfa63b2009-05-28 11:08:32 -0400765 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400767 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800768
769 if (mWakeLock.isHeld()) {
770 mHandler.removeMessages(RELEASE_WAKELOCK);
771 mWakeLock.release();
772 }
773
774 if (mCredsDlg != null) {
775 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
776 // In case credential request never comes back
777 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
778 }
779 }
780
781 registerReceiver(mNetworkStateIntentReceiver,
782 mNetworkStateChangedFilter);
783 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800784 }
785
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400786 /**
787 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400788 * would change its appearance, use a different TitleBar to show overlayed
789 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400790 */
791 private TitleBar mFakeTitleBar;
792
793 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400794 * Holder for the fake title bar. It will have a foreground shadow, as well
795 * as a white background, so the fake title bar looks like the real one.
796 */
797 private ViewGroup mFakeTitleBarHolder;
798
799 /**
800 * Layout parameters for the fake title bar within mFakeTitleBarHolder
801 */
802 private FrameLayout.LayoutParams mFakeTitleBarParams
803 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800804 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400805 ViewGroup.LayoutParams.WRAP_CONTENT);
806 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400807 * Keeps track of whether the options menu is open. This is important in
808 * determining whether to show or hide the title bar overlay.
809 */
810 private boolean mOptionsMenuOpen;
811
812 /**
813 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
814 * of whether the configuration has changed. The first onMenuOpened call
815 * after a configuration change is simply a reopening of the same menu
816 * (i.e. mIconView did not change).
817 */
818 private boolean mConfigChanged;
819
820 /**
821 * Whether or not the options menu is in its smaller, icon menu form. When
822 * true, we want the title bar overlay to be up. When false, we do not.
823 * Only meaningful if mOptionsMenuOpen is true.
824 */
825 private boolean mIconView;
826
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400827 @Override
828 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400829 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
830 if (mOptionsMenuOpen) {
831 if (mConfigChanged) {
832 // We do not need to make any changes to the state of the
833 // title bar, since the only thing that happened was a
834 // change in orientation
835 mConfigChanged = false;
836 } else {
837 if (mIconView) {
838 // Switching the menu to expanded view, so hide the
839 // title bar.
840 hideFakeTitleBar();
841 mIconView = false;
842 } else {
843 // Switching the menu back to icon view, so show the
844 // title bar once again.
845 showFakeTitleBar();
846 mIconView = true;
847 }
848 }
849 } else {
850 // The options menu is closed, so open it, and show the title
851 showFakeTitleBar();
852 mOptionsMenuOpen = true;
853 mConfigChanged = false;
854 mIconView = true;
855 }
856 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400857 return true;
858 }
859
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400860 /**
861 * Special class used exclusively for the shadow drawn underneath the fake
862 * title bar. The shadow does not need to be drawn if the WebView
863 * underneath is scrolled to the top, because it will draw directly on top
864 * of the embedded shadow.
865 */
866 private static class Shadow extends View {
867 private WebView mWebView;
868
869 public Shadow(Context context, AttributeSet attrs) {
870 super(context, attrs);
871 }
872
873 public void setWebView(WebView view) {
874 mWebView = view;
875 }
876
877 @Override
878 public void draw(Canvas canvas) {
879 // In general onDraw is the method to override, but we care about
880 // whether or not the background gets drawn, which happens in draw()
881 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
882 super.draw(canvas);
883 }
884 // Need to invalidate so that if the scroll position changes, we
885 // still draw as appropriate.
886 invalidate();
887 }
888 }
889
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400890 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400891 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400892 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400893 && !mActivityInPause && decor != null
894 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400895 Rect visRect = new Rect();
896 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
897 if (LOGD_ENABLED) {
898 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
899 }
900 return;
901 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400902
903 WindowManager manager
904 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
905
906 // Add the title bar to the window manager so it can receive touches
907 // while the menu is up
908 WindowManager.LayoutParams params
909 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800910 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911 ViewGroup.LayoutParams.WRAP_CONTENT,
912 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
913 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400914 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400915 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400916 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400917 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400918 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400919 // XXX : Without providing an offset, the fake title bar will be
920 // placed underneath the status bar. Use the global visible rect
921 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400922 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400923 // Add a holder for the title bar. It also holds a shadow to show
924 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400925 if (mFakeTitleBarHolder == null) {
926 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
927 .inflate(R.layout.title_bar_bg, null);
928 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400929 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
930 R.id.shadow);
931 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400932 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400933 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400934 }
935 }
936
937 @Override
938 public void onOptionsMenuClosed(Menu menu) {
939 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400940 if (!mInLoad) {
941 hideFakeTitleBar();
942 } else if (!mIconView) {
943 // The page is currently loading, and we are in expanded mode, so
944 // we were not showing the menu. Show it once again. It will be
945 // removed when the page finishes.
946 showFakeTitleBar();
947 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400948 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700949
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400950 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400951 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400952 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
953 mFakeTitleBarHolder.getLayoutParams();
954 WebView mainView = mTabControl.getCurrentWebView();
955 // Although we decided whether or not to animate based on the current
956 // scroll position, the scroll position may have changed since the
957 // fake title bar was displayed. Make sure it has the appropriate
958 // animation/lack thereof before removing.
959 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400960 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400961 WindowManager manager
962 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400963 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400964 mFakeTitleBarHolder.removeView(mFakeTitleBar);
965 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400966 }
967
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400969 * Special method for the fake title bar to call when displaying its context
970 * menu, since it is in its own Window, and its parent does not show a
971 * context menu.
972 */
973 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400974 if (null == mTitleBar.getParent()) {
975 return;
976 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400977 openContextMenu(mTitleBar);
978 }
979
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400980 @Override
981 public void onContextMenuClosed(Menu menu) {
982 super.onContextMenuClosed(menu);
983 if (mInLoad) {
984 showFakeTitleBar();
985 }
986 }
987
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400988 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 * onSaveInstanceState(Bundle map)
990 * onSaveInstanceState is called right before onStop(). The map contains
991 * the saved state.
992 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700993 @Override
994 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700995 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
997 }
998 // the default implementation requires each view to have an id. As the
999 // browser handles the state itself and it doesn't use id for the views,
1000 // don't call the default implementation. Otherwise it will trigger the
1001 // warning like this, "couldn't save which view has focus because the
1002 // focused view XXX has no id".
1003
1004 // Save all the tabs
1005 mTabControl.saveState(outState);
1006 }
1007
Grace Kloba22ac16e2009-10-07 18:00:23 -07001008 @Override
1009 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 super.onPause();
1011
1012 if (mActivityInPause) {
1013 Log.e(LOGTAG, "BrowserActivity is already paused.");
1014 return;
1015 }
1016
Mike Reed7bfa63b2009-05-28 11:08:32 -04001017 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001018 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001019 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020 mWakeLock.acquire();
1021 mHandler.sendMessageDelayed(mHandler
1022 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1023 }
1024
1025 // Clear the credentials toast if it is up
1026 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1027 mCredsDlg.dismiss();
1028 }
1029 mCredsDlg = null;
1030
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001031 // FIXME: This removes the active tabs page and resets the menu to
1032 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1033 // but then we would need to save it in onSaveInstanceState and restore
1034 // it in onCreate/onRestoreInstanceState
1035 if (mActiveTabsPage != null) {
1036 removeActiveTabPage(true);
1037 }
1038
The Android Open Source Project0c908882009-03-03 19:32:16 -08001039 cancelStopToast();
1040
1041 // unregister network state listener
1042 unregisterReceiver(mNetworkStateIntentReceiver);
1043 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 @Override
1047 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001048 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001049 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1050 }
1051 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001052
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001053 if (mUploadMessage != null) {
1054 mUploadMessage.onReceiveValue(null);
1055 mUploadMessage = null;
1056 }
1057
Grace Kloba0923d692009-09-23 21:37:25 -07001058 if (mTabControl == null) return;
1059
Grace Kloba1fc98a32009-10-21 13:23:08 -07001060 // Remove the fake title bar if it is there
1061 hideFakeTitleBar();
1062
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001065 if (t != null) {
1066 dismissSubWindow(t);
1067 removeTabFromContentView(t);
1068 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069 // Destroy all the tabs
1070 mTabControl.destroy();
1071 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072
Grace Klobab4da0ad2009-05-14 14:45:40 -07001073 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001074 }
1075
1076 @Override
1077 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001078 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 super.onConfigurationChanged(newConfig);
1080
1081 if (mPageInfoDialog != null) {
1082 mPageInfoDialog.dismiss();
1083 showPageInfo(
1084 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001085 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001086 }
1087 if (mSSLCertificateDialog != null) {
1088 mSSLCertificateDialog.dismiss();
1089 showSSLCertificate(
1090 mSSLCertificateView);
1091 }
1092 if (mSSLCertificateOnErrorDialog != null) {
1093 mSSLCertificateOnErrorDialog.dismiss();
1094 showSSLCertificateOnError(
1095 mSSLCertificateOnErrorView,
1096 mSSLCertificateOnErrorHandler,
1097 mSSLCertificateOnErrorError);
1098 }
1099 if (mHttpAuthenticationDialog != null) {
1100 String title = ((TextView) mHttpAuthenticationDialog
1101 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1102 .toString();
1103 String name = ((TextView) mHttpAuthenticationDialog
1104 .findViewById(R.id.username_edit)).getText().toString();
1105 String password = ((TextView) mHttpAuthenticationDialog
1106 .findViewById(R.id.password_edit)).getText().toString();
1107 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1108 .getId();
1109 mHttpAuthenticationDialog.dismiss();
1110 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1111 name, password, focusId);
1112 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 }
1114
Grace Kloba22ac16e2009-10-07 18:00:23 -07001115 @Override
1116 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001117 super.onLowMemory();
1118 mTabControl.freeMemory();
1119 }
1120
Mike Reed7bfa63b2009-05-28 11:08:32 -04001121 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001122 Tab tab = mTabControl.getCurrentTab();
1123 boolean inLoad = tab.inLoad();
1124 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001125 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001126 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001127 if (w != null) {
1128 w.resumeTimers();
1129 }
1130 return true;
1131 } else {
1132 return false;
1133 }
1134 }
1135
Mike Reed7bfa63b2009-05-28 11:08:32 -04001136 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001137 Tab tab = mTabControl.getCurrentTab();
1138 boolean inLoad = tab.inLoad();
1139 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001140 CookieSyncManager.getInstance().stopSync();
1141 WebView w = mTabControl.getCurrentWebView();
1142 if (w != null) {
1143 w.pauseTimers();
1144 }
1145 return true;
1146 } else {
1147 return false;
1148 }
1149 }
1150
Leon Scroggins1f005d32009-08-10 17:36:42 -04001151 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001152 /*
1153 * This function is called when we are launching for the first time. We
1154 * are waiting for the login credentials before loading Google home
1155 * pages. This way the user will be logged in straight away.
1156 */
1157 private void waitForCredentials() {
1158 // Show a toast
1159 mCredsDlg = new ProgressDialog(this);
1160 mCredsDlg.setIndeterminate(true);
1161 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1162 // If the user cancels the operation, then cancel the Google
1163 // Credentials request.
1164 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1165 mCredsDlg.show();
1166
1167 // We set a timeout for the retrieval of credentials in onResume()
1168 // as that is when we have freed up some CPU time to get
1169 // the login credentials.
1170 }
1171
1172 /*
1173 * If we have received the credentials or we have timed out and we are
1174 * showing the credentials dialog, then it is time to move on.
1175 */
1176 private void resumeAfterCredentials() {
1177 if (mCredsDlg == null) {
1178 return;
1179 }
1180
1181 // Clear the toast
1182 if (mCredsDlg.isShowing()) {
1183 mCredsDlg.dismiss();
1184 }
1185 mCredsDlg = null;
1186
1187 // Clear any pending timeout
1188 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1189
1190 // Load the page
1191 WebView w = mTabControl.getCurrentWebView();
1192 if (w != null) {
1193 w.loadUrl(mSettings.getHomePage());
1194 }
1195
1196 // Update the settings, need to do this last as it can take a moment
1197 // to persist the settings. In the mean time we could be loading
1198 // content.
1199 mSettings.setLoginInitialized(this);
1200 }
1201
1202 // Open the icon database and retain all the icons for visited sites.
1203 private void retainIconsOnStartup() {
1204 final WebIconDatabase db = WebIconDatabase.getInstance();
1205 db.open(getDir("icons", 0).getPath());
1206 try {
1207 Cursor c = Browser.getAllBookmarks(mResolver);
1208 if (!c.moveToFirst()) {
1209 c.deactivate();
1210 return;
1211 }
1212 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1213 do {
1214 String url = c.getString(urlIndex);
1215 db.retainIconForPageUrl(url);
1216 } while (c.moveToNext());
1217 c.deactivate();
1218 } catch (IllegalStateException e) {
1219 Log.e(LOGTAG, "retainIconsOnStartup", e);
1220 }
1221 }
1222
1223 // Helper method for getting the top window.
1224 WebView getTopWindow() {
1225 return mTabControl.getCurrentTopWebView();
1226 }
1227
Grace Kloba22ac16e2009-10-07 18:00:23 -07001228 TabControl getTabControl() {
1229 return mTabControl;
1230 }
1231
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232 @Override
1233 public boolean onCreateOptionsMenu(Menu menu) {
1234 super.onCreateOptionsMenu(menu);
1235
1236 MenuInflater inflater = getMenuInflater();
1237 inflater.inflate(R.menu.browser, menu);
1238 mMenu = menu;
1239 updateInLoadMenuItems();
1240 return true;
1241 }
1242
1243 /**
1244 * As the menu can be open when loading state changes
1245 * we must manually update the state of the stop/reload menu
1246 * item
1247 */
1248 private void updateInLoadMenuItems() {
1249 if (mMenu == null) {
1250 return;
1251 }
1252 MenuItem src = mInLoad ?
1253 mMenu.findItem(R.id.stop_menu_id):
1254 mMenu.findItem(R.id.reload_menu_id);
1255 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1256 dest.setIcon(src.getIcon());
1257 dest.setTitle(src.getTitle());
1258 }
1259
1260 @Override
1261 public boolean onContextItemSelected(MenuItem item) {
1262 // chording is not an issue with context menus, but we use the same
1263 // options selector, so set mCanChord to true so we can access them.
1264 mCanChord = true;
1265 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001266 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001267 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001268 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001269 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001270 Tab currentTab = mTabControl.getCurrentTab();
1271 if (null == currentTab) {
1272 result = false;
1273 break;
1274 }
1275 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001276 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001277 result = false;
1278 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001279 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001280 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001281 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001282 // -- Browser context menu
1283 case R.id.open_context_menu_id:
1284 case R.id.open_newtab_context_menu_id:
1285 case R.id.bookmark_context_menu_id:
1286 case R.id.save_link_context_menu_id:
1287 case R.id.share_link_context_menu_id:
1288 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001289 final WebView webView = getTopWindow();
1290 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001291 result = false;
1292 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001293 }
1294 final HashMap hrefMap = new HashMap();
1295 hrefMap.put("webview", webView);
1296 final Message msg = mHandler.obtainMessage(
1297 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001298 webView.requestFocusNodeHref(msg);
1299 break;
1300
1301 default:
1302 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001303 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 }
1305 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001306 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001307 }
1308
1309 private Bundle createGoogleSearchSourceBundle(String source) {
1310 Bundle bundle = new Bundle();
1311 bundle.putString(SearchManager.SOURCE, source);
1312 return bundle;
1313 }
1314
1315 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001316 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001317 */
1318 @Override
1319 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001320 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001321 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001322 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001323 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001324 return true;
1325 }
1326
1327 @Override
1328 public void startSearch(String initialQuery, boolean selectInitialQuery,
1329 Bundle appSearchData, boolean globalSearch) {
1330 if (appSearchData == null) {
1331 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1332 }
1333 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1334 }
1335
Leon Scroggins1f005d32009-08-10 17:36:42 -04001336 /**
1337 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1338 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001339 * @param index Index of the tab to change to, as defined by
1340 * mTabControl.getTabIndex(Tab t).
1341 * @return boolean True if we successfully switched to a different tab. If
1342 * the indexth tab is null, or if that tab is the same as
1343 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001344 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001345 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001346 Tab tab = mTabControl.getTab(index);
1347 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001348 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001349 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001350 }
1351 if (currentTab != null) {
1352 // currentTab may be null if it was just removed. In that case,
1353 // we do not need to remove it
1354 removeTabFromContentView(currentTab);
1355 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001356 mTabControl.setCurrentTab(tab);
1357 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001358 resetTitleIconAndProgress();
1359 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001360 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001361 }
1362
Grace Kloba22ac16e2009-10-07 18:00:23 -07001363 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001364 return openTabAndShow(mSettings.getHomePage(), false, null);
1365 }
1366
Leon Scroggins1f005d32009-08-10 17:36:42 -04001367 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001368 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001369 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001370 // This is the last tab. Open a new one, with the home
1371 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001372 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001373 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001374 return;
1375 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001376 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001377 int indexToShow = -1;
1378 if (parent != null) {
1379 indexToShow = mTabControl.getTabIndex(parent);
1380 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001381 final int currentIndex = mTabControl.getCurrentIndex();
1382 // Try to move to the tab to the right
1383 indexToShow = currentIndex + 1;
1384 if (indexToShow > mTabControl.getTabCount() - 1) {
1385 // Try to move to the tab to the left
1386 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 }
1388 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001389 if (switchToTab(indexToShow)) {
1390 // Close window
1391 closeTab(current);
1392 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001393 }
1394
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 private ActiveTabsPage mActiveTabsPage;
1396
1397 /**
1398 * Remove the active tabs page.
1399 * @param needToAttach If true, the active tabs page did not attach a tab
1400 * to the content view, so we need to do that here.
1401 */
1402 /* package */ void removeActiveTabPage(boolean needToAttach) {
1403 mContentView.removeView(mActiveTabsPage);
1404 mActiveTabsPage = null;
1405 mMenuState = R.id.MAIN_MENU;
1406 if (needToAttach) {
1407 attachTabToContentView(mTabControl.getCurrentTab());
1408 }
1409 getTopWindow().requestFocus();
1410 }
1411
The Android Open Source Project0c908882009-03-03 19:32:16 -08001412 @Override
1413 public boolean onOptionsItemSelected(MenuItem item) {
1414 if (!mCanChord) {
1415 // The user has already fired a shortcut with this hold down of the
1416 // menu key.
1417 return false;
1418 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001419 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001420 return false;
1421 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001422 if (mMenuIsDown) {
1423 // The shortcut action consumes the MENU. Even if it is still down,
1424 // it won't trigger the next shortcut action. In the case of the
1425 // shortcut action triggering a new activity, like Bookmarks, we
1426 // won't get onKeyUp for MENU. So it is important to reset it here.
1427 mMenuIsDown = false;
1428 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 switch (item.getItemId()) {
1430 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001431 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001432 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001433 break;
1434
Leon Scroggins64b80f32009-08-07 12:03:34 -04001435 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001436 onSearchRequested();
1437 break;
1438
1439 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001440 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001441 break;
1442
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001443 case R.id.active_tabs_menu_id:
1444 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1445 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001446 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001447 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1448 mActiveTabsPage.requestFocus();
1449 mMenuState = EMPTY_MENU;
1450 break;
1451
Leon Scroggins1f005d32009-08-10 17:36:42 -04001452 case R.id.add_bookmark_menu_id:
1453 Intent i = new Intent(BrowserActivity.this,
1454 AddBookmarkPage.class);
1455 WebView w = getTopWindow();
1456 i.putExtra("url", w.getUrl());
1457 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001458 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001459 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001460 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001461 break;
1462
1463 case R.id.stop_reload_menu_id:
1464 if (mInLoad) {
1465 stopLoading();
1466 } else {
1467 getTopWindow().reload();
1468 }
1469 break;
1470
1471 case R.id.back_menu_id:
1472 getTopWindow().goBack();
1473 break;
1474
1475 case R.id.forward_menu_id:
1476 getTopWindow().goForward();
1477 break;
1478
1479 case R.id.close_menu_id:
1480 // Close the subwindow if it exists.
1481 if (mTabControl.getCurrentSubWindow() != null) {
1482 dismissSubWindow(mTabControl.getCurrentTab());
1483 break;
1484 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001485 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 break;
1487
1488 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001489 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001490 if (current != null) {
1491 dismissSubWindow(current);
1492 current.getWebView().loadUrl(mSettings.getHomePage());
1493 }
1494 break;
1495
1496 case R.id.preferences_menu_id:
1497 Intent intent = new Intent(this,
1498 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001499 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1500 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 startActivityForResult(intent, PREFERENCES_PAGE);
1502 break;
1503
1504 case R.id.find_menu_id:
1505 if (null == mFindDialog) {
1506 mFindDialog = new FindDialog(this);
1507 }
1508 mFindDialog.setWebView(getTopWindow());
1509 mFindDialog.show();
1510 mMenuState = EMPTY_MENU;
1511 break;
1512
1513 case R.id.select_text_id:
1514 getTopWindow().emulateShiftHeld();
1515 break;
1516 case R.id.page_info_menu_id:
1517 showPageInfo(mTabControl.getCurrentTab(), false);
1518 break;
1519
1520 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001521 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 break;
1523
Leon Scroggins96afcb12009-12-10 12:35:56 -05001524 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001526 Tab currentTab = mTabControl.getCurrentTab();
1527 if (null == currentTab) {
1528 mCanChord = false;
1529 return false;
1530 }
1531 currentTab.populatePickerData();
1532 sharePage(this, currentTab.getTitle(),
1533 currentTab.getUrl(), currentTab.getFavicon(),
1534 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001535 break;
1536
1537 case R.id.dump_nav_menu_id:
1538 getTopWindow().debugDump();
1539 break;
1540
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001541 case R.id.dump_counters_menu_id:
1542 getTopWindow().dumpV8Counters();
1543 break;
1544
The Android Open Source Project0c908882009-03-03 19:32:16 -08001545 case R.id.zoom_in_menu_id:
1546 getTopWindow().zoomIn();
1547 break;
1548
1549 case R.id.zoom_out_menu_id:
1550 getTopWindow().zoomOut();
1551 break;
1552
1553 case R.id.view_downloads_menu_id:
1554 viewDownloads(null);
1555 break;
1556
The Android Open Source Project0c908882009-03-03 19:32:16 -08001557 case R.id.window_one_menu_id:
1558 case R.id.window_two_menu_id:
1559 case R.id.window_three_menu_id:
1560 case R.id.window_four_menu_id:
1561 case R.id.window_five_menu_id:
1562 case R.id.window_six_menu_id:
1563 case R.id.window_seven_menu_id:
1564 case R.id.window_eight_menu_id:
1565 {
1566 int menuid = item.getItemId();
1567 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1568 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001569 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001570 if (desiredTab != null &&
1571 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001572 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001573 }
1574 break;
1575 }
1576 }
1577 }
1578 break;
1579
1580 default:
1581 if (!super.onOptionsItemSelected(item)) {
1582 return false;
1583 }
1584 // Otherwise fall through.
1585 }
1586 mCanChord = false;
1587 return true;
1588 }
1589
1590 public void closeFind() {
1591 mMenuState = R.id.MAIN_MENU;
1592 }
1593
Grace Kloba22ac16e2009-10-07 18:00:23 -07001594 @Override
1595 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001596 // This happens when the user begins to hold down the menu key, so
1597 // allow them to chord to get a shortcut.
1598 mCanChord = true;
1599 // Note: setVisible will decide whether an item is visible; while
1600 // setEnabled() will decide whether an item is enabled, which also means
1601 // whether the matching shortcut key will function.
1602 super.onPrepareOptionsMenu(menu);
1603 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001604 case EMPTY_MENU:
1605 if (mCurrentMenuState != mMenuState) {
1606 menu.setGroupVisible(R.id.MAIN_MENU, false);
1607 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1608 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 }
1610 break;
1611 default:
1612 if (mCurrentMenuState != mMenuState) {
1613 menu.setGroupVisible(R.id.MAIN_MENU, true);
1614 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1615 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001616 }
1617 final WebView w = getTopWindow();
1618 boolean canGoBack = false;
1619 boolean canGoForward = false;
1620 boolean isHome = false;
1621 if (w != null) {
1622 canGoBack = w.canGoBack();
1623 canGoForward = w.canGoForward();
1624 isHome = mSettings.getHomePage().equals(w.getUrl());
1625 }
1626 final MenuItem back = menu.findItem(R.id.back_menu_id);
1627 back.setEnabled(canGoBack);
1628
1629 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1630 home.setEnabled(!isHome);
1631
1632 menu.findItem(R.id.forward_menu_id)
1633 .setEnabled(canGoForward);
1634
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001635 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001636 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001637
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 // decide whether to show the share link option
1639 PackageManager pm = getPackageManager();
1640 Intent send = new Intent(Intent.ACTION_SEND);
1641 send.setType("text/plain");
1642 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1643 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1644
The Android Open Source Project0c908882009-03-03 19:32:16 -08001645 boolean isNavDump = mSettings.isNavDump();
1646 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1647 nav.setVisible(isNavDump);
1648 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001649
1650 boolean showDebugSettings = mSettings.showDebugSettings();
1651 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1652 counter.setVisible(showDebugSettings);
1653 counter.setEnabled(showDebugSettings);
1654
The Android Open Source Project0c908882009-03-03 19:32:16 -08001655 break;
1656 }
1657 mCurrentMenuState = mMenuState;
1658 return true;
1659 }
1660
1661 @Override
1662 public void onCreateContextMenu(ContextMenu menu, View v,
1663 ContextMenuInfo menuInfo) {
1664 WebView webview = (WebView) v;
1665 WebView.HitTestResult result = webview.getHitTestResult();
1666 if (result == null) {
1667 return;
1668 }
1669
1670 int type = result.getType();
1671 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1672 Log.w(LOGTAG,
1673 "We should not show context menu when nothing is touched");
1674 return;
1675 }
1676 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1677 // let TextView handles context menu
1678 return;
1679 }
1680
1681 // Note, http://b/issue?id=1106666 is requesting that
1682 // an inflated menu can be used again. This is not available
1683 // yet, so inflate each time (yuk!)
1684 MenuInflater inflater = getMenuInflater();
1685 inflater.inflate(R.menu.browsercontext, menu);
1686
1687 // Show the correct menu group
1688 String extra = result.getExtra();
1689 menu.setGroupVisible(R.id.PHONE_MENU,
1690 type == WebView.HitTestResult.PHONE_TYPE);
1691 menu.setGroupVisible(R.id.EMAIL_MENU,
1692 type == WebView.HitTestResult.EMAIL_TYPE);
1693 menu.setGroupVisible(R.id.GEO_MENU,
1694 type == WebView.HitTestResult.GEO_TYPE);
1695 menu.setGroupVisible(R.id.IMAGE_MENU,
1696 type == WebView.HitTestResult.IMAGE_TYPE
1697 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1698 menu.setGroupVisible(R.id.ANCHOR_MENU,
1699 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1700 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1701
1702 // Setup custom handling depending on the type
1703 switch (type) {
1704 case WebView.HitTestResult.PHONE_TYPE:
1705 menu.setHeaderTitle(Uri.decode(extra));
1706 menu.findItem(R.id.dial_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_TEL + extra)));
1709 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1710 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001711 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1713 addIntent);
1714 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1715 new Copy(extra));
1716 break;
1717
1718 case WebView.HitTestResult.EMAIL_TYPE:
1719 menu.setHeaderTitle(extra);
1720 menu.findItem(R.id.email_context_menu_id).setIntent(
1721 new Intent(Intent.ACTION_VIEW, Uri
1722 .parse(WebView.SCHEME_MAILTO + extra)));
1723 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1724 new Copy(extra));
1725 break;
1726
1727 case WebView.HitTestResult.GEO_TYPE:
1728 menu.setHeaderTitle(extra);
1729 menu.findItem(R.id.map_context_menu_id).setIntent(
1730 new Intent(Intent.ACTION_VIEW, Uri
1731 .parse(WebView.SCHEME_GEO
1732 + URLEncoder.encode(extra))));
1733 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1734 new Copy(extra));
1735 break;
1736
1737 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1738 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1739 TextView titleView = (TextView) LayoutInflater.from(this)
1740 .inflate(android.R.layout.browser_link_context_header,
1741 null);
1742 titleView.setText(extra);
1743 menu.setHeaderView(titleView);
1744 // decide whether to show the open link in new tab option
1745 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001747 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1748 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 PackageManager pm = getPackageManager();
1750 Intent send = new Intent(Intent.ACTION_SEND);
1751 send.setType("text/plain");
1752 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1753 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1754 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1755 break;
1756 }
1757 // otherwise fall through to handle image part
1758 case WebView.HitTestResult.IMAGE_TYPE:
1759 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1760 menu.setHeaderTitle(extra);
1761 }
1762 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1763 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1764 menu.findItem(R.id.download_context_menu_id).
1765 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001766 menu.findItem(R.id.set_wallpaper_context_menu_id).
1767 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001768 break;
1769
1770 default:
1771 Log.w(LOGTAG, "We should not get here.");
1772 break;
1773 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001774 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001775 }
1776
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001778 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001779 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001780 // Attach the container that contains the main WebView and any other UI
1781 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001782 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001783
1784 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001785 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001786 if (errorConsole.numberOfErrors() == 0) {
1787 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1788 } else {
1789 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1790 }
1791
1792 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001793 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001794 ViewGroup.LayoutParams.WRAP_CONTENT));
1795 }
1796
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001797 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001798 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001799 if (t.isInVoiceSearchMode()) {
1800 showVoiceTitleBar(t.getVoiceDisplayTitle());
1801 } else {
1802 revertVoiceTitleBar();
1803 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001804 // Request focus on the top window.
1805 t.getTopWindow().requestFocus();
1806 }
1807
1808 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001809 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001810 t.attachSubWindow(mContentView);
1811 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001812 }
1813
1814 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001815 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001816 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001817 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001818
Grace Kloba22ac16e2009-10-07 18:00:23 -07001819 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1820 if (errorConsole != null) {
1821 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001822 }
1823
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001824 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001825 if (view != null) {
1826 view.setEmbeddedTitleBar(null);
1827 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 }
1829
1830 // Remove the sub window if it exists. Also called by TabControl when the
1831 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001832 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001833 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001834 // dismiss the subwindow. This will destroy the WebView.
1835 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001836 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001837 }
1838
Leon Scroggins1f005d32009-08-10 17:36:42 -04001839 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001840 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001841 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001842 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001843 }
1844
1845 // This method does a ton of stuff. It will attempt to create a new tab
1846 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001847 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001848 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1849 String appId) {
1850 final Tab currentTab = mTabControl.getCurrentTab();
1851 if (mTabControl.canCreateNewTab()) {
1852 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1853 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001854 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001855 // If the last tab was removed from the active tabs page, currentTab
1856 // will be null.
1857 if (currentTab != null) {
1858 removeTabFromContentView(currentTab);
1859 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001860 // We must set the new tab as the current tab to reflect the old
1861 // animation behavior.
1862 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001863 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001864 if (!urlData.isEmpty()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05001865 urlData.loadIn(tab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001866 }
1867 return tab;
1868 } else {
1869 // Get rid of the subwindow if it exists
1870 dismissSubWindow(currentTab);
1871 if (!urlData.isEmpty()) {
1872 // Load the given url.
Leon Scroggins58d56c62010-01-28 15:12:40 -05001873 urlData.loadIn(currentTab);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001875 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877 }
1878
Grace Kloba22ac16e2009-10-07 18:00:23 -07001879 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001880 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001881 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001882 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001883 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001884 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
Grace Klobac9181842009-04-14 08:53:22 -07001886 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001887 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001888 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 }
1890 }
1891
1892 private class Copy implements OnMenuItemClickListener {
1893 private CharSequence mText;
1894
1895 public boolean onMenuItemClick(MenuItem item) {
1896 copy(mText);
1897 return true;
1898 }
1899
1900 public Copy(CharSequence toCopy) {
1901 mText = toCopy;
1902 }
1903 }
1904
1905 private class Download implements OnMenuItemClickListener {
1906 private String mText;
1907
1908 public boolean onMenuItemClick(MenuItem item) {
1909 onDownloadStartNoStream(mText, null, null, null, -1);
1910 return true;
1911 }
1912
1913 public Download(String toDownload) {
1914 mText = toDownload;
1915 }
1916 }
1917
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001918 private class SetAsWallpaper extends Thread implements
1919 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1920 private URL mUrl;
1921 private ProgressDialog mWallpaperProgress;
1922 private boolean mCanceled = false;
1923
1924 public SetAsWallpaper(String url) {
1925 try {
1926 mUrl = new URL(url);
1927 } catch (MalformedURLException e) {
1928 mUrl = null;
1929 }
1930 }
1931
1932 public void onCancel(DialogInterface dialog) {
1933 mCanceled = true;
1934 }
1935
1936 public boolean onMenuItemClick(MenuItem item) {
1937 if (mUrl != null) {
1938 // The user may have tried to set a image with a large file size as their
1939 // background so it may take a few moments to perform the operation. Display
1940 // a progress spinner while it is working.
1941 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1942 mWallpaperProgress.setIndeterminate(true);
1943 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1944 mWallpaperProgress.setCancelable(true);
1945 mWallpaperProgress.setOnCancelListener(this);
1946 mWallpaperProgress.show();
1947 start();
1948 }
1949 return true;
1950 }
1951
1952 public void run() {
1953 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1954 try {
1955 // TODO: This will cause the resource to be downloaded again, when we
1956 // should in most cases be able to grab it from the cache. To fix this
1957 // we should query WebCore to see if we can access a cached version and
1958 // instead open an input stream on that. This pattern could also be used
1959 // in the download manager where the same problem exists.
1960 InputStream inputstream = mUrl.openStream();
1961 if (inputstream != null) {
1962 setWallpaper(inputstream);
1963 }
1964 } catch (IOException e) {
1965 Log.e(LOGTAG, "Unable to set new wallpaper");
1966 // Act as though the user canceled the operation so we try to
1967 // restore the old wallpaper.
1968 mCanceled = true;
1969 }
1970
1971 if (mCanceled) {
1972 // Restore the old wallpaper if the user cancelled whilst we were setting
1973 // the new wallpaper.
1974 int width = oldWallpaper.getIntrinsicWidth();
1975 int height = oldWallpaper.getIntrinsicHeight();
1976 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1977 Canvas canvas = new Canvas(bm);
1978 oldWallpaper.setBounds(0, 0, width, height);
1979 oldWallpaper.draw(canvas);
1980 try {
1981 setWallpaper(bm);
1982 } catch (IOException e) {
1983 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1984 }
1985 mCanceled = false;
1986 }
1987
1988 if (mWallpaperProgress.isShowing()) {
1989 mWallpaperProgress.dismiss();
1990 }
1991 }
1992 }
1993
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 private void copy(CharSequence text) {
1995 try {
1996 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1997 if (clip != null) {
1998 clip.setClipboardText(text);
1999 }
2000 } catch (android.os.RemoteException e) {
2001 Log.e(LOGTAG, "Copy failed", e);
2002 }
2003 }
2004
2005 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 * Resets the browser title-view to whatever it must be
2007 * (for example, if we had a loading error)
2008 * When we have a new page, we call resetTitle, when we
2009 * have to reset the titlebar to whatever it used to be
2010 * (for example, if the user chose to stop loading), we
2011 * call resetTitleAndRevertLockIcon.
2012 */
2013 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002014 mTabControl.getCurrentTab().revertLockIcon();
2015 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002016 resetTitleIconAndProgress();
2017 }
2018
2019 /**
2020 * Reset the title, favicon, and progress.
2021 */
2022 private void resetTitleIconAndProgress() {
2023 WebView current = mTabControl.getCurrentWebView();
2024 if (current == null) {
2025 return;
2026 }
2027 resetTitleAndIcon(current);
2028 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002029 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 }
2031
2032 // Reset the title and the icon based on the given item.
2033 private void resetTitleAndIcon(WebView view) {
2034 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2035 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002036 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 setFavicon(item.getFavicon());
2038 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002039 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 setFavicon(null);
2041 }
2042 }
2043
2044 /**
2045 * Sets a title composed of the URL and the title string.
2046 * @param url The URL of the site being loaded.
2047 * @param title The title of the site being loaded.
2048 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002049 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 mUrl = url;
2051 mTitle = title;
2052
Leon Scroggins58d56c62010-01-28 15:12:40 -05002053 // If we are in voice search mode, the title has already been set.
2054 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2055 mTitleBar.setDisplayTitle(url);
2056 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 }
2058
2059 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 * @param url The URL to build a title version of the URL from.
2061 * @return The title version of the URL or null if fails.
2062 * The title version of the URL can be either the URL hostname,
2063 * or the hostname with an "https://" prefix (for secure URLs),
2064 * or an empty string if, for example, the URL in question is a
2065 * file:// URL with no hostname.
2066 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002067 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 String titleUrl = null;
2069
2070 if (url != null) {
2071 try {
2072 // parse the url string
2073 URL urlObj = new URL(url);
2074 if (urlObj != null) {
2075 titleUrl = "";
2076
2077 String protocol = urlObj.getProtocol();
2078 String host = urlObj.getHost();
2079
2080 if (host != null && 0 < host.length()) {
2081 titleUrl = host;
2082 if (protocol != null) {
2083 // if a secure site, add an "https://" prefix!
2084 if (protocol.equalsIgnoreCase("https")) {
2085 titleUrl = protocol + "://" + host;
2086 }
2087 }
2088 }
2089 }
2090 } catch (MalformedURLException e) {}
2091 }
2092
2093 return titleUrl;
2094 }
2095
2096 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002097 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002098 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002099 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 }
2101
2102 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002103 * Close the tab, remove its associated title bar, and adjust mTabControl's
2104 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002105 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002106 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002107 int currentIndex = mTabControl.getCurrentIndex();
2108 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002109 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002110 if (currentIndex >= removeIndex && currentIndex != 0) {
2111 currentIndex--;
2112 }
2113 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002114 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
2116
2117 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002118 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 if (current == null) {
2120 /*
2121 * Instead of finishing the activity, simply push this to the back
2122 * of the stack and let ActivityManager to choose the foreground
2123 * activity. As BrowserActivity is singleTask, it will be always the
2124 * root of the task. So we can use either true or false for
2125 * moveTaskToBack().
2126 */
2127 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002128 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130 WebView w = current.getWebView();
2131 if (w.canGoBack()) {
2132 w.goBack();
2133 } else {
2134 // Check to see if we are closing a window that was created by
2135 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002136 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002138 switchToTab(mTabControl.getTabIndex(parent));
2139 // Now we close the other tab
2140 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002141 } else {
2142 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002143 // force the tab's inLoad() to be false as we are going to
2144 // either finish the activity or remove the tab. This will
2145 // ensure pauseWebViewTimers() taking action.
2146 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002147 if (mTabControl.getTabCount() == 1) {
2148 finish();
2149 return;
2150 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002151 // call pauseWebViewTimers() now, we won't be able to call
2152 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002153 // Temporarily change mActivityInPause to be true as
2154 // pauseWebViewTimers() will do nothing if mActivityInPause
2155 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002156 boolean savedState = mActivityInPause;
2157 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002158 Log.e(LOGTAG, "BrowserActivity is already paused "
2159 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002160 }
2161 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002162 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002163 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002164 removeTabFromContentView(current);
2165 mTabControl.removeTab(current);
2166 }
2167 /*
2168 * Instead of finishing the activity, simply push this to the back
2169 * of the stack and let ActivityManager to choose the foreground
2170 * activity. As BrowserActivity is singleTask, it will be always the
2171 * root of the task. So we can use either true or false for
2172 * moveTaskToBack().
2173 */
2174 moveTaskToBack(true);
2175 }
2176 }
2177 }
2178
Grace Kloba22ac16e2009-10-07 18:00:23 -07002179 boolean isMenuDown() {
2180 return mMenuIsDown;
2181 }
2182
Grace Kloba5942df02009-09-18 11:48:29 -07002183 @Override
2184 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002185 // Even if MENU is already held down, we need to call to super to open
2186 // the IME on long press.
2187 if (KeyEvent.KEYCODE_MENU == keyCode) {
2188 mMenuIsDown = true;
2189 return super.onKeyDown(keyCode, event);
2190 }
Grace Kloba5942df02009-09-18 11:48:29 -07002191 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2192 // still down, we don't want to trigger the search. Pretend to consume
2193 // the key and do nothing.
2194 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002195
Grace Kloba5942df02009-09-18 11:48:29 -07002196 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002197 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002198 // WebView/WebTextView handle the keys in the KeyDown. As
2199 // the Activity's shortcut keys are only handled when WebView
2200 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2201 if (event.isShiftPressed()) {
2202 getTopWindow().pageUp(false);
2203 } else {
2204 getTopWindow().pageDown(false);
2205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 return true;
2207 case KeyEvent.KEYCODE_BACK:
2208 if (event.getRepeatCount() == 0) {
2209 event.startTracking();
2210 return true;
2211 } else if (mCustomView == null && mActiveTabsPage == null
2212 && event.isLongPress()) {
2213 bookmarksOrHistoryPicker(true);
2214 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 }
Grace Kloba5942df02009-09-18 11:48:29 -07002216 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 }
Grace Kloba5942df02009-09-18 11:48:29 -07002218 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 }
2220
Grace Kloba5942df02009-09-18 11:48:29 -07002221 @Override
2222 public boolean onKeyUp(int keyCode, KeyEvent event) {
2223 switch(keyCode) {
2224 case KeyEvent.KEYCODE_MENU:
2225 mMenuIsDown = false;
2226 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002227 case KeyEvent.KEYCODE_BACK:
2228 if (event.isTracking() && !event.isCanceled()) {
2229 if (mCustomView != null) {
2230 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002231 mTabControl.getCurrentWebView().getWebChromeClient()
2232 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002233 } else if (mActiveTabsPage != null) {
2234 // if tab page is showing, hide it
2235 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002237 WebView subwindow = mTabControl.getCurrentSubWindow();
2238 if (subwindow != null) {
2239 if (subwindow.canGoBack()) {
2240 subwindow.goBack();
2241 } else {
2242 dismissSubWindow(mTabControl.getCurrentTab());
2243 }
2244 } else {
2245 goBackOnePageOrQuit();
2246 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 }
Grace Kloba5942df02009-09-18 11:48:29 -07002248 return true;
2249 }
2250 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 }
Grace Kloba5942df02009-09-18 11:48:29 -07002252 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 }
2254
Leon Scroggins68579392009-09-15 15:31:54 -04002255 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002256 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 resetTitleAndRevertLockIcon();
2258 WebView w = getTopWindow();
2259 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002260 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2261 // same logic here. But for subwindow case, should we call into the main
2262 // WebView's onPageFinished as we never call its onPageStarted and if
2263 // the page finishes itself, we don't call onPageFinished.
2264 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2265 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266
2267 cancelStopToast();
2268 mStopToast = Toast
2269 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2270 mStopToast.show();
2271 }
2272
Grace Kloba22ac16e2009-10-07 18:00:23 -07002273 boolean didUserStopLoading() {
2274 return mDidStopLoad;
2275 }
2276
The Android Open Source Project0c908882009-03-03 19:32:16 -08002277 private void cancelStopToast() {
2278 if (mStopToast != null) {
2279 mStopToast.cancel();
2280 mStopToast = null;
2281 }
2282 }
2283
Grace Kloba22ac16e2009-10-07 18:00:23 -07002284 // called by a UI or non-UI thread to post the message
2285 public void postMessage(int what, int arg1, int arg2, Object obj,
2286 long delayMillis) {
2287 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2288 obj), delayMillis);
2289 }
2290
2291 // called by a UI or non-UI thread to remove the message
2292 void removeMessages(int what, Object object) {
2293 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 }
2295
2296 // public message ids
2297 public final static int LOAD_URL = 1001;
2298 public final static int STOP_LOAD = 1002;
2299
2300 // Message Ids
2301 private static final int FOCUS_NODE_HREF = 102;
2302 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002303 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304
Grace Kloba22ac16e2009-10-07 18:00:23 -07002305 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002306
The Android Open Source Project0c908882009-03-03 19:32:16 -08002307 // Private handler for handling javascript and saving passwords
2308 private Handler mHandler = new Handler() {
2309
2310 public void handleMessage(Message msg) {
2311 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002312 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002313 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002314 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002315 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 if (url == null || url.length() == 0) {
2317 break;
2318 }
2319 HashMap focusNodeMap = (HashMap) msg.obj;
2320 WebView view = (WebView) focusNodeMap.get("webview");
2321 // Only apply the action if the top window did not change.
2322 if (getTopWindow() != view) {
2323 break;
2324 }
2325 switch (msg.arg1) {
2326 case R.id.open_context_menu_id:
2327 case R.id.view_image_context_menu_id:
2328 loadURL(getTopWindow(), url);
2329 break;
2330 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002331 final Tab parent = mTabControl.getCurrentTab();
2332 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002333 if (newTab != parent) {
2334 parent.addChildTab(newTab);
2335 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002336 break;
2337 case R.id.bookmark_context_menu_id:
2338 Intent intent = new Intent(BrowserActivity.this,
2339 AddBookmarkPage.class);
2340 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002341 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 startActivity(intent);
2343 break;
2344 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002345 // See if this site has been visited before
2346 StringBuilder sb = new StringBuilder(
2347 Browser.BookmarkColumns.URL + " = ");
2348 DatabaseUtils.appendEscapedSQLString(sb, url);
2349 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2350 Browser.HISTORY_PROJECTION,
2351 sb.toString(),
2352 null,
2353 null);
2354 if (c.moveToFirst()) {
2355 // The site has been visited before, so grab the
2356 // info from the database.
2357 Bitmap favicon = null;
2358 Bitmap thumbnail = null;
2359 String linkTitle = c.getString(Browser.
2360 HISTORY_PROJECTION_TITLE_INDEX);
2361 byte[] data = c.getBlob(Browser.
2362 HISTORY_PROJECTION_FAVICON_INDEX);
2363 if (data != null) {
2364 favicon = BitmapFactory.decodeByteArray(
2365 data, 0, data.length);
2366 }
2367 data = c.getBlob(Browser.
2368 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2369 if (data != null) {
2370 thumbnail = BitmapFactory.decodeByteArray(
2371 data, 0, data.length);
2372 }
2373 sharePage(BrowserActivity.this,
2374 linkTitle, url, favicon, thumbnail);
2375 } else {
2376 Browser.sendString(BrowserActivity.this, url,
2377 getString(
2378 R.string.choosertitle_sharevia));
2379 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002380 break;
2381 case R.id.copy_link_context_menu_id:
2382 copy(url);
2383 break;
2384 case R.id.save_link_context_menu_id:
2385 case R.id.download_context_menu_id:
2386 onDownloadStartNoStream(url, null, null, null, -1);
2387 break;
2388 }
2389 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002390 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391
2392 case LOAD_URL:
2393 loadURL(getTopWindow(), (String) msg.obj);
2394 break;
2395
2396 case STOP_LOAD:
2397 stopLoading();
2398 break;
2399
2400 case CANCEL_CREDS_REQUEST:
2401 resumeAfterCredentials();
2402 break;
2403
The Android Open Source Project0c908882009-03-03 19:32:16 -08002404 case RELEASE_WAKELOCK:
2405 if (mWakeLock.isHeld()) {
2406 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002407 // if we reach here, Browser should be still in the
2408 // background loading after WAKELOCK_TIMEOUT (5-min).
2409 // To avoid burning the battery, stop loading.
2410 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002411 }
2412 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002413
2414 case UPDATE_BOOKMARK_THUMBNAIL:
2415 WebView view = (WebView) msg.obj;
2416 if (view != null) {
2417 updateScreenshot(view);
2418 }
2419 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421 }
2422 };
2423
Leon Scroggins96afcb12009-12-10 12:35:56 -05002424 /**
2425 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2426 * an {@link Intent} to launch the Activity chooser.
2427 * @param c Context used to launch a new Activity.
2428 * @param title Title of the page. Stored in the Intent with
2429 * {@link Browser#EXTRA_SHARE_TITLE}
2430 * @param url URL of the page. Stored in the Intent with
2431 * {@link Intent#EXTRA_TEXT}
2432 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2433 * with {@link Browser#EXTRA_SHARE_FAVICON}
2434 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2435 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2436 */
2437 public static final void sharePage(Context c, String title, String url,
2438 Bitmap favicon, Bitmap screenshot) {
2439 Intent send = new Intent(Intent.ACTION_SEND);
2440 send.setType("text/plain");
2441 send.putExtra(Intent.EXTRA_TEXT, url);
2442 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2443 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2444 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2445 try {
2446 c.startActivity(Intent.createChooser(send, c.getString(
2447 R.string.choosertitle_sharevia)));
2448 } catch(android.content.ActivityNotFoundException ex) {
2449 // if no app handles it, do nothing
2450 }
2451 }
2452
Leon Scroggins89c6d362009-07-15 16:54:37 -04002453 private void updateScreenshot(WebView view) {
2454 // If this is a bookmarked site, add a screenshot to the database.
2455 // FIXME: When should we update? Every time?
2456 // FIXME: Would like to make sure there is actually something to
2457 // draw, but the API for that (WebViewCore.pictureReady()) is not
2458 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002459
Patrick Scott3918d442009-08-04 13:22:29 -04002460 ContentResolver cr = getContentResolver();
2461 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002462 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002463 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002464 boolean succeed = c.moveToFirst();
2465 ContentValues values = null;
2466 while (succeed) {
2467 if (values == null) {
2468 final ByteArrayOutputStream os
2469 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002470 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002471 if (bm == null) {
2472 c.close();
2473 return;
2474 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002475 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2476 values = new ContentValues();
2477 values.put(Browser.BookmarkColumns.THUMBNAIL,
2478 os.toByteArray());
2479 }
2480 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2481 c.getInt(0)), values, null, null);
2482 succeed = c.moveToNext();
2483 }
2484 c.close();
2485 }
2486 }
2487
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002488 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002489 * Values for the size of the thumbnail created when taking a screenshot.
2490 * Lazily initialized. Instead of using these directly, use
2491 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002492 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002493 private static int THUMBNAIL_WIDTH = 0;
2494 private static int THUMBNAIL_HEIGHT = 0;
2495
2496 /**
2497 * Return the desired width for thumbnail screenshots, which are stored in
2498 * the database, and used on the bookmarks screen.
2499 * @param context Context for finding out the density of the screen.
2500 * @return int desired width for thumbnail screenshot.
2501 */
2502 /* package */ static int getDesiredThumbnailWidth(Context context) {
2503 if (THUMBNAIL_WIDTH == 0) {
2504 float density = context.getResources().getDisplayMetrics().density;
2505 THUMBNAIL_WIDTH = (int) (90 * density);
2506 THUMBNAIL_HEIGHT = (int) (80 * density);
2507 }
2508 return THUMBNAIL_WIDTH;
2509 }
2510
2511 /**
2512 * Return the desired height for thumbnail screenshots, which are stored in
2513 * the database, and used on the bookmarks screen.
2514 * @param context Context for finding out the density of the screen.
2515 * @return int desired height for thumbnail screenshot.
2516 */
2517 /* package */ static int getDesiredThumbnailHeight(Context context) {
2518 // To ensure that they are both initialized.
2519 getDesiredThumbnailWidth(context);
2520 return THUMBNAIL_HEIGHT;
2521 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002522
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002523 private Bitmap createScreenshot(WebView view) {
2524 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002525 if (thumbnail == null) {
2526 return null;
2527 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002528 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2529 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002530 Canvas canvas = new Canvas(bm);
2531 // May need to tweak these values to determine what is the
2532 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002533 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002534 int thumbnailHeight = thumbnail.getHeight();
2535 float scaleFactorX = 1.0f;
2536 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002537 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002538 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002539 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002540 } else {
2541 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002542 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002543
2544 if (view.getWidth() > view.getHeight() &&
2545 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2546 // If the device is in landscape and the page is shorter
2547 // than the height of the view, stretch the thumbnail to fill the
2548 // space.
2549 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2550 (float)thumbnailHeight;
2551 } else {
2552 // In the portrait case, this looks nice.
2553 scaleFactorY = scaleFactorX;
2554 }
2555
2556 canvas.scale(scaleFactorX, scaleFactorY);
2557
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002558 thumbnail.draw(canvas);
2559 return bm;
2560 }
2561
The Android Open Source Project0c908882009-03-03 19:32:16 -08002562 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002563 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564 //-------------------------------------------------------------------------
2565
2566 // Use in overrideUrlLoading
2567 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2568 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2569 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2570 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2571
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 void onPageStarted(WebView view, String url, Bitmap favicon) {
2573 // when BrowserActivity just starts, onPageStarted may be called before
2574 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2575 // to start the timer. As we won't switch tabs while an activity is in
2576 // pause state, we can ensure calling resume and pause in pair.
2577 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002578
Grace Kloba22ac16e2009-10-07 18:00:23 -07002579 resetLockIcon(url);
2580 setUrlTitle(url, null);
2581 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002582 // Keep this initial progress in sync with initialProgressValue (* 100)
2583 // in ProgressTracker.cpp
2584 // Show some progress so that the user knows the page is beginning to
2585 // load
2586 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002587 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002589
Grace Kloba22ac16e2009-10-07 18:00:23 -07002590 if (mSettings.isTracing()) {
2591 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002592 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002593 WebAddress uri = new WebAddress(url);
2594 host = uri.mHost;
2595 } catch (android.net.ParseException ex) {
2596 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002597 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002598 host = host.replace('.', '_');
2599 host += ".trace";
2600 mInTrace = true;
2601 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2602 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 // Performance probe
2605 if (false) {
2606 mStart = SystemClock.uptimeMillis();
2607 mProcessStart = Process.getElapsedCpuTime();
2608 long[] sysCpu = new long[7];
2609 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2610 sysCpu, null)) {
2611 mUserStart = sysCpu[0] + sysCpu[1];
2612 mSystemStart = sysCpu[2];
2613 mIdleStart = sysCpu[3];
2614 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2615 }
2616 mUiStart = SystemClock.currentThreadTimeMillis();
2617 }
2618 }
2619
2620 void onPageFinished(WebView view, String url) {
2621 // Reset the title and icon in case we stopped a provisional load.
2622 resetTitleAndIcon(view);
2623 // Update the lock icon image only once we are done loading
2624 updateLockIconToLatest();
2625 // pause the WebView timer and release the wake lock if it is finished
2626 // while BrowserActivity is in pause state.
2627 if (mActivityInPause && pauseWebViewTimers()) {
2628 if (mWakeLock.isHeld()) {
2629 mHandler.removeMessages(RELEASE_WAKELOCK);
2630 mWakeLock.release();
2631 }
2632 }
2633
2634 // Performance probe
2635 if (false) {
2636 long[] sysCpu = new long[7];
2637 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2638 sysCpu, null)) {
2639 String uiInfo = "UI thread used "
2640 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2641 + " ms";
2642 if (LOGD_ENABLED) {
2643 Log.d(LOGTAG, uiInfo);
2644 }
2645 //The string that gets written to the log
2646 String performanceString = "It took total "
2647 + (SystemClock.uptimeMillis() - mStart)
2648 + " ms clock time to load the page."
2649 + "\nbrowser process used "
2650 + (Process.getElapsedCpuTime() - mProcessStart)
2651 + " ms, user processes used "
2652 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2653 + " ms, kernel used "
2654 + (sysCpu[2] - mSystemStart) * 10
2655 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2656 + " ms and irq took "
2657 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2658 * 10 + " ms, " + uiInfo;
2659 if (LOGD_ENABLED) {
2660 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2661 }
2662 if (url != null) {
2663 // strip the url to maintain consistency
2664 String newUrl = new String(url);
2665 if (newUrl.startsWith("http://www.")) {
2666 newUrl = newUrl.substring(11);
2667 } else if (newUrl.startsWith("http://")) {
2668 newUrl = newUrl.substring(7);
2669 } else if (newUrl.startsWith("https://www.")) {
2670 newUrl = newUrl.substring(12);
2671 } else if (newUrl.startsWith("https://")) {
2672 newUrl = newUrl.substring(8);
2673 }
2674 if (LOGD_ENABLED) {
2675 Log.d(LOGTAG, newUrl + " loaded");
2676 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002677 }
2678 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002679 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002680
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 if (mInTrace) {
2682 mInTrace = false;
2683 Debug.stopMethodTracing();
2684 }
2685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686
Grace Kloba22ac16e2009-10-07 18:00:23 -07002687 boolean shouldOverrideUrlLoading(WebView view, String url) {
2688 if (url.startsWith(SCHEME_WTAI)) {
2689 // wtai://wp/mc;number
2690 // number=string(phone-number)
2691 if (url.startsWith(SCHEME_WTAI_MC)) {
2692 Intent intent = new Intent(Intent.ACTION_VIEW,
2693 Uri.parse(WebView.SCHEME_TEL +
2694 url.substring(SCHEME_WTAI_MC.length())));
2695 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002696 return true;
2697 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 // wtai://wp/sd;dtmf
2699 // dtmf=string(dialstring)
2700 if (url.startsWith(SCHEME_WTAI_SD)) {
2701 // TODO: only send when there is active voice connection
2702 return false;
2703 }
2704 // wtai://wp/ap;number;name
2705 // number=string(phone-number)
2706 // name=string
2707 if (url.startsWith(SCHEME_WTAI_AP)) {
2708 // TODO
2709 return false;
2710 }
2711 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002712
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 // The "about:" schemes are internal to the browser; don't want these to
2714 // be dispatched to other apps.
2715 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716 return false;
2717 }
2718
Grace Kloba22ac16e2009-10-07 18:00:23 -07002719 Intent intent;
2720 // perform generic parsing of the URI to turn it into an Intent.
2721 try {
2722 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2723 } catch (URISyntaxException ex) {
2724 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2725 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002726 }
2727
Grace Kloba22ac16e2009-10-07 18:00:23 -07002728 // check whether the intent can be resolved. If not, we will see
2729 // whether we can download it from the Market.
2730 if (getPackageManager().resolveActivity(intent, 0) == null) {
2731 String packagename = intent.getPackage();
2732 if (packagename != null) {
2733 intent = new Intent(Intent.ACTION_VIEW, Uri
2734 .parse("market://search?q=pname:" + packagename));
2735 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2736 startActivity(intent);
2737 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002738 } else {
2739 return false;
2740 }
2741 }
2742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 // sanitize the Intent, ensuring web pages can not bypass browser
2744 // security (only access to BROWSABLE activities).
2745 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2746 intent.setComponent(null);
2747 try {
2748 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002749 return true;
2750 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 } catch (ActivityNotFoundException ex) {
2752 // ignore the error. If no application can handle the URL,
2753 // eg about:blank, assume the browser can handle it.
2754 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002755
Grace Kloba22ac16e2009-10-07 18:00:23 -07002756 if (mMenuIsDown) {
2757 openTab(url);
2758 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002759 return true;
2760 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002761 return false;
2762 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763
Grace Kloba22ac16e2009-10-07 18:00:23 -07002764 // -------------------------------------------------------------------------
2765 // Helper function for WebChromeClient
2766 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002767
Grace Kloba22ac16e2009-10-07 18:00:23 -07002768 void onProgressChanged(WebView view, int newProgress) {
2769 mTitleBar.setProgress(newProgress);
2770 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002771
Grace Kloba22ac16e2009-10-07 18:00:23 -07002772 if (newProgress == 100) {
2773 // onProgressChanged() may continue to be called after the main
2774 // frame has finished loading, as any remaining sub frames continue
2775 // to load. We'll only get called once though with newProgress as
2776 // 100 when everything is loaded. (onPageFinished is called once
2777 // when the main frame completes loading regardless of the state of
2778 // any sub frames so calls to onProgressChanges may continue after
2779 // onPageFinished has executed)
2780 if (mInLoad) {
2781 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002782 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002783 // If the options menu is open, leave the title bar
2784 if (!mOptionsMenuOpen || !mIconView) {
2785 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002786 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 } else if (!mInLoad) {
2789 // onPageFinished may have already been called but a subframe is
2790 // still loading and updating the progress. Reset mInLoad and update
2791 // the menu items.
2792 mInLoad = true;
2793 updateInLoadMenuItems();
2794 if (!mOptionsMenuOpen || mIconView) {
2795 // This page has begun to load, so show the title bar
2796 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002797 }
2798 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002799 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002800
Grace Kloba22ac16e2009-10-07 18:00:23 -07002801 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002802 // if a view already exists then immediately terminate the new one
2803 if (mCustomView != null) {
2804 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002805 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002806 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807
2808 // Add the custom view to its container.
2809 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2810 mCustomView = view;
2811 mCustomViewCallback = callback;
2812 // Save the menu state and set it to empty while the custom
2813 // view is showing.
2814 mOldMenuState = mMenuState;
2815 mMenuState = EMPTY_MENU;
2816 // Hide the content view.
2817 mContentView.setVisibility(View.GONE);
2818 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002819 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002820 mCustomViewContainer.setVisibility(View.VISIBLE);
2821 mCustomViewContainer.bringToFront();
2822 }
2823
2824 void onHideCustomView() {
2825 if (mCustomView == null)
2826 return;
2827
2828 // Hide the custom view.
2829 mCustomView.setVisibility(View.GONE);
2830 // Remove the custom view from its container.
2831 mCustomViewContainer.removeView(mCustomView);
2832 mCustomView = null;
2833 // Reset the old menu state.
2834 mMenuState = mOldMenuState;
2835 mOldMenuState = EMPTY_MENU;
2836 mCustomViewContainer.setVisibility(View.GONE);
2837 mCustomViewCallback.onCustomViewHidden();
2838 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002839 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002840 mContentView.setVisibility(View.VISIBLE);
2841 }
2842
2843 Bitmap getDefaultVideoPoster() {
2844 if (mDefaultVideoPoster == null) {
2845 mDefaultVideoPoster = BitmapFactory.decodeResource(
2846 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002847 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002848 return mDefaultVideoPoster;
2849 }
Patrick Scott3918d442009-08-04 13:22:29 -04002850
Grace Kloba22ac16e2009-10-07 18:00:23 -07002851 View getVideoLoadingProgressView() {
2852 if (mVideoProgressView == null) {
2853 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2854 mVideoProgressView = inflater.inflate(
2855 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002856 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857 return mVideoProgressView;
2858 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002860 /*
2861 * The Object used to inform the WebView of the file to upload.
2862 */
2863 private ValueCallback<Uri> mUploadMessage;
2864
Grace Kloba22ac16e2009-10-07 18:00:23 -07002865 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2866 if (mUploadMessage != null) return;
2867 mUploadMessage = uploadMsg;
2868 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2869 i.addCategory(Intent.CATEGORY_OPENABLE);
2870 i.setType("*/*");
2871 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2872 getString(R.string.choose_upload)), FILE_SELECTED);
2873 }
2874
2875 // -------------------------------------------------------------------------
2876 // Implement functions for DownloadListener
2877 // -------------------------------------------------------------------------
2878
The Android Open Source Project0c908882009-03-03 19:32:16 -08002879 /**
2880 * Notify the host application a download should be done, or that
2881 * the data should be streamed if a streaming viewer is available.
2882 * @param url The full url to the content that should be downloaded
2883 * @param contentDisposition Content-disposition http header, if
2884 * present.
2885 * @param mimetype The mimetype of the content reported by the server
2886 * @param contentLength The file size reported by the server
2887 */
2888 public void onDownloadStart(String url, String userAgent,
2889 String contentDisposition, String mimetype, long contentLength) {
2890 // if we're dealing wih A/V content that's not explicitly marked
2891 // for download, check if it's streamable.
2892 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002893 || !contentDisposition.regionMatches(
2894 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002895 // query the package manager to see if there's a registered handler
2896 // that matches.
2897 Intent intent = new Intent(Intent.ACTION_VIEW);
2898 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002899 ResolveInfo info = getPackageManager().resolveActivity(intent,
2900 PackageManager.MATCH_DEFAULT_ONLY);
2901 if (info != null) {
2902 ComponentName myName = getComponentName();
2903 // If we resolved to ourselves, we don't want to attempt to
2904 // load the url only to try and download it again.
2905 if (!myName.getPackageName().equals(
2906 info.activityInfo.packageName)
2907 || !myName.getClassName().equals(
2908 info.activityInfo.name)) {
2909 // someone (other than us) knows how to handle this mime
2910 // type with this scheme, don't download.
2911 try {
2912 startActivity(intent);
2913 return;
2914 } catch (ActivityNotFoundException ex) {
2915 if (LOGD_ENABLED) {
2916 Log.d(LOGTAG, "activity not found for " + mimetype
2917 + " over " + Uri.parse(url).getScheme(),
2918 ex);
2919 }
2920 // Best behavior is to fall back to a download in this
2921 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002922 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002923 }
2924 }
2925 }
2926 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2927 }
2928
2929 /**
2930 * Notify the host application a download should be done, even if there
2931 * is a streaming viewer available for thise type.
2932 * @param url The full url to the content that should be downloaded
2933 * @param contentDisposition Content-disposition http header, if
2934 * present.
2935 * @param mimetype The mimetype of the content reported by the server
2936 * @param contentLength The file size reported by the server
2937 */
2938 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2939 String contentDisposition, String mimetype, long contentLength) {
2940
2941 String filename = URLUtil.guessFileName(url,
2942 contentDisposition, mimetype);
2943
2944 // Check to see if we have an SDCard
2945 String status = Environment.getExternalStorageState();
2946 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2947 int title;
2948 String msg;
2949
2950 // Check to see if the SDCard is busy, same as the music app
2951 if (status.equals(Environment.MEDIA_SHARED)) {
2952 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2953 title = R.string.download_sdcard_busy_dlg_title;
2954 } else {
2955 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2956 title = R.string.download_no_sdcard_dlg_title;
2957 }
2958
2959 new AlertDialog.Builder(this)
2960 .setTitle(title)
2961 .setIcon(android.R.drawable.ic_dialog_alert)
2962 .setMessage(msg)
2963 .setPositiveButton(R.string.ok, null)
2964 .show();
2965 return;
2966 }
2967
2968 // java.net.URI is a lot stricter than KURL so we have to undo
2969 // KURL's percent-encoding and redo the encoding using java.net.URI.
2970 URI uri = null;
2971 try {
2972 // Undo the percent-encoding that KURL may have done.
2973 String newUrl = new String(URLUtil.decode(url.getBytes()));
2974 // Parse the url into pieces
2975 WebAddress w = new WebAddress(newUrl);
2976 String frag = null;
2977 String query = null;
2978 String path = w.mPath;
2979 // Break the path into path, query, and fragment
2980 if (path.length() > 0) {
2981 // Strip the fragment
2982 int idx = path.lastIndexOf('#');
2983 if (idx != -1) {
2984 frag = path.substring(idx + 1);
2985 path = path.substring(0, idx);
2986 }
2987 idx = path.lastIndexOf('?');
2988 if (idx != -1) {
2989 query = path.substring(idx + 1);
2990 path = path.substring(0, idx);
2991 }
2992 }
2993 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2994 query, frag);
2995 } catch (Exception e) {
2996 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2997 return;
2998 }
2999
3000 // XXX: Have to use the old url since the cookies were stored using the
3001 // old percent-encoded url.
3002 String cookies = CookieManager.getInstance().getCookie(url);
3003
3004 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003005 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3006 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3007 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3008 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003010 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003012 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3013 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3014 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3015 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3016 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003018 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003019 }
3020 if (mimetype == null) {
3021 // We must have long pressed on a link or image to download it. We
3022 // are not sure of the mimetype in this case, so do a head request
3023 new FetchUrlMimeType(this).execute(values);
3024 } else {
3025 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003026 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003027 }
3028
3029 }
3030
Grace Kloba22ac16e2009-10-07 18:00:23 -07003031 // -------------------------------------------------------------------------
3032
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 /**
3034 * Resets the lock icon. This method is called when we start a new load and
3035 * know the url to be loaded.
3036 */
3037 private void resetLockIcon(String url) {
3038 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003039 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003040 updateLockIconImage(LOCK_ICON_UNSECURE);
3041 }
3042
The Android Open Source Project0c908882009-03-03 19:32:16 -08003043 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003044 * Update the lock icon to correspond to our latest state.
3045 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003046 private void updateLockIconToLatest() {
3047 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003048 }
3049
3050 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 * Updates the lock-icon image in the title-bar.
3052 */
3053 private void updateLockIconImage(int lockIconType) {
3054 Drawable d = null;
3055 if (lockIconType == LOCK_ICON_SECURE) {
3056 d = mSecLockIcon;
3057 } else if (lockIconType == LOCK_ICON_MIXED) {
3058 d = mMixLockIcon;
3059 }
Leon Scroggins68579392009-09-15 15:31:54 -04003060 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003061 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 }
3063
3064 /**
3065 * Displays a page-info dialog.
3066 * @param tab The tab to show info about
3067 * @param fromShowSSLCertificateOnError The flag that indicates whether
3068 * this dialog was opened from the SSL-certificate-on-error dialog or
3069 * not. This is important, since we need to know whether to return to
3070 * the parent dialog or simply dismiss.
3071 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003072 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003073 final boolean fromShowSSLCertificateOnError) {
3074 final LayoutInflater factory = LayoutInflater
3075 .from(this);
3076
3077 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3078
3079 final WebView view = tab.getWebView();
3080
3081 String url = null;
3082 String title = null;
3083
3084 if (view == null) {
3085 url = tab.getUrl();
3086 title = tab.getTitle();
3087 } else if (view == mTabControl.getCurrentWebView()) {
3088 // Use the cached title and url if this is the current WebView
3089 url = mUrl;
3090 title = mTitle;
3091 } else {
3092 url = view.getUrl();
3093 title = view.getTitle();
3094 }
3095
3096 if (url == null) {
3097 url = "";
3098 }
3099 if (title == null) {
3100 title = "";
3101 }
3102
3103 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3104 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3105
3106 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003107 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108
3109 AlertDialog.Builder alertDialogBuilder =
3110 new AlertDialog.Builder(this)
3111 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3112 .setView(pageInfoView)
3113 .setPositiveButton(
3114 R.string.ok,
3115 new DialogInterface.OnClickListener() {
3116 public void onClick(DialogInterface dialog,
3117 int whichButton) {
3118 mPageInfoDialog = null;
3119 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003120
3121 // if we came here from the SSL error dialog
3122 if (fromShowSSLCertificateOnError) {
3123 // go back to the SSL error dialog
3124 showSSLCertificateOnError(
3125 mSSLCertificateOnErrorView,
3126 mSSLCertificateOnErrorHandler,
3127 mSSLCertificateOnErrorError);
3128 }
3129 }
3130 })
3131 .setOnCancelListener(
3132 new DialogInterface.OnCancelListener() {
3133 public void onCancel(DialogInterface dialog) {
3134 mPageInfoDialog = null;
3135 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003136
3137 // if we came here from the SSL error dialog
3138 if (fromShowSSLCertificateOnError) {
3139 // go back to the SSL error dialog
3140 showSSLCertificateOnError(
3141 mSSLCertificateOnErrorView,
3142 mSSLCertificateOnErrorHandler,
3143 mSSLCertificateOnErrorError);
3144 }
3145 }
3146 });
3147
3148 // if we have a main top-level page SSL certificate set or a certificate
3149 // error
3150 if (fromShowSSLCertificateOnError ||
3151 (view != null && view.getCertificate() != null)) {
3152 // add a 'View Certificate' button
3153 alertDialogBuilder.setNeutralButton(
3154 R.string.view_certificate,
3155 new DialogInterface.OnClickListener() {
3156 public void onClick(DialogInterface dialog,
3157 int whichButton) {
3158 mPageInfoDialog = null;
3159 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003160
3161 // if we came here from the SSL error dialog
3162 if (fromShowSSLCertificateOnError) {
3163 // go back to the SSL error dialog
3164 showSSLCertificateOnError(
3165 mSSLCertificateOnErrorView,
3166 mSSLCertificateOnErrorHandler,
3167 mSSLCertificateOnErrorError);
3168 } else {
3169 // otherwise, display the top-most certificate from
3170 // the chain
3171 if (view.getCertificate() != null) {
3172 showSSLCertificate(tab);
3173 }
3174 }
3175 }
3176 });
3177 }
3178
3179 mPageInfoDialog = alertDialogBuilder.show();
3180 }
3181
3182 /**
3183 * Displays the main top-level page SSL certificate dialog
3184 * (accessible from the Page-Info dialog).
3185 * @param tab The tab to show certificate for.
3186 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003187 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 final View certificateView =
3189 inflateCertificateView(tab.getWebView().getCertificate());
3190 if (certificateView == null) {
3191 return;
3192 }
3193
3194 LayoutInflater factory = LayoutInflater.from(this);
3195
3196 final LinearLayout placeholder =
3197 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3198
3199 LinearLayout ll = (LinearLayout) factory.inflate(
3200 R.layout.ssl_success, placeholder);
3201 ((TextView)ll.findViewById(R.id.success))
3202 .setText(R.string.ssl_certificate_is_valid);
3203
3204 mSSLCertificateView = tab;
3205 mSSLCertificateDialog =
3206 new AlertDialog.Builder(this)
3207 .setTitle(R.string.ssl_certificate).setIcon(
3208 R.drawable.ic_dialog_browser_certificate_secure)
3209 .setView(certificateView)
3210 .setPositiveButton(R.string.ok,
3211 new DialogInterface.OnClickListener() {
3212 public void onClick(DialogInterface dialog,
3213 int whichButton) {
3214 mSSLCertificateDialog = null;
3215 mSSLCertificateView = null;
3216
3217 showPageInfo(tab, false);
3218 }
3219 })
3220 .setOnCancelListener(
3221 new DialogInterface.OnCancelListener() {
3222 public void onCancel(DialogInterface dialog) {
3223 mSSLCertificateDialog = null;
3224 mSSLCertificateView = null;
3225
3226 showPageInfo(tab, false);
3227 }
3228 })
3229 .show();
3230 }
3231
3232 /**
3233 * Displays the SSL error certificate dialog.
3234 * @param view The target web-view.
3235 * @param handler The SSL error handler responsible for cancelling the
3236 * connection that resulted in an SSL error or proceeding per user request.
3237 * @param error The SSL error object.
3238 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003239 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003240 final WebView view, final SslErrorHandler handler, final SslError error) {
3241
3242 final View certificateView =
3243 inflateCertificateView(error.getCertificate());
3244 if (certificateView == null) {
3245 return;
3246 }
3247
3248 LayoutInflater factory = LayoutInflater.from(this);
3249
3250 final LinearLayout placeholder =
3251 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3252
3253 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3254 LinearLayout ll = (LinearLayout)factory
3255 .inflate(R.layout.ssl_warning, placeholder);
3256 ((TextView)ll.findViewById(R.id.warning))
3257 .setText(R.string.ssl_untrusted);
3258 }
3259
3260 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3261 LinearLayout ll = (LinearLayout)factory
3262 .inflate(R.layout.ssl_warning, placeholder);
3263 ((TextView)ll.findViewById(R.id.warning))
3264 .setText(R.string.ssl_mismatch);
3265 }
3266
3267 if (error.hasError(SslError.SSL_EXPIRED)) {
3268 LinearLayout ll = (LinearLayout)factory
3269 .inflate(R.layout.ssl_warning, placeholder);
3270 ((TextView)ll.findViewById(R.id.warning))
3271 .setText(R.string.ssl_expired);
3272 }
3273
3274 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3275 LinearLayout ll = (LinearLayout)factory
3276 .inflate(R.layout.ssl_warning, placeholder);
3277 ((TextView)ll.findViewById(R.id.warning))
3278 .setText(R.string.ssl_not_yet_valid);
3279 }
3280
3281 mSSLCertificateOnErrorHandler = handler;
3282 mSSLCertificateOnErrorView = view;
3283 mSSLCertificateOnErrorError = error;
3284 mSSLCertificateOnErrorDialog =
3285 new AlertDialog.Builder(this)
3286 .setTitle(R.string.ssl_certificate).setIcon(
3287 R.drawable.ic_dialog_browser_certificate_partially_secure)
3288 .setView(certificateView)
3289 .setPositiveButton(R.string.ok,
3290 new DialogInterface.OnClickListener() {
3291 public void onClick(DialogInterface dialog,
3292 int whichButton) {
3293 mSSLCertificateOnErrorDialog = null;
3294 mSSLCertificateOnErrorView = null;
3295 mSSLCertificateOnErrorHandler = null;
3296 mSSLCertificateOnErrorError = null;
3297
Grace Kloba22ac16e2009-10-07 18:00:23 -07003298 view.getWebViewClient().onReceivedSslError(
3299 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003300 }
3301 })
3302 .setNeutralButton(R.string.page_info_view,
3303 new DialogInterface.OnClickListener() {
3304 public void onClick(DialogInterface dialog,
3305 int whichButton) {
3306 mSSLCertificateOnErrorDialog = null;
3307
3308 // do not clear the dialog state: we will
3309 // need to show the dialog again once the
3310 // user is done exploring the page-info details
3311
3312 showPageInfo(mTabControl.getTabFromView(view),
3313 true);
3314 }
3315 })
3316 .setOnCancelListener(
3317 new DialogInterface.OnCancelListener() {
3318 public void onCancel(DialogInterface dialog) {
3319 mSSLCertificateOnErrorDialog = null;
3320 mSSLCertificateOnErrorView = null;
3321 mSSLCertificateOnErrorHandler = null;
3322 mSSLCertificateOnErrorError = null;
3323
Grace Kloba22ac16e2009-10-07 18:00:23 -07003324 view.getWebViewClient().onReceivedSslError(
3325 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003326 }
3327 })
3328 .show();
3329 }
3330
3331 /**
3332 * Inflates the SSL certificate view (helper method).
3333 * @param certificate The SSL certificate.
3334 * @return The resultant certificate view with issued-to, issued-by,
3335 * issued-on, expires-on, and possibly other fields set.
3336 * If the input certificate is null, returns null.
3337 */
3338 private View inflateCertificateView(SslCertificate certificate) {
3339 if (certificate == null) {
3340 return null;
3341 }
3342
3343 LayoutInflater factory = LayoutInflater.from(this);
3344
3345 View certificateView = factory.inflate(
3346 R.layout.ssl_certificate, null);
3347
3348 // issued to:
3349 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3350 if (issuedTo != null) {
3351 ((TextView) certificateView.findViewById(R.id.to_common))
3352 .setText(issuedTo.getCName());
3353 ((TextView) certificateView.findViewById(R.id.to_org))
3354 .setText(issuedTo.getOName());
3355 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3356 .setText(issuedTo.getUName());
3357 }
3358
3359 // issued by:
3360 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3361 if (issuedBy != null) {
3362 ((TextView) certificateView.findViewById(R.id.by_common))
3363 .setText(issuedBy.getCName());
3364 ((TextView) certificateView.findViewById(R.id.by_org))
3365 .setText(issuedBy.getOName());
3366 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3367 .setText(issuedBy.getUName());
3368 }
3369
3370 // issued on:
3371 String issuedOn = reformatCertificateDate(
3372 certificate.getValidNotBefore());
3373 ((TextView) certificateView.findViewById(R.id.issued_on))
3374 .setText(issuedOn);
3375
3376 // expires on:
3377 String expiresOn = reformatCertificateDate(
3378 certificate.getValidNotAfter());
3379 ((TextView) certificateView.findViewById(R.id.expires_on))
3380 .setText(expiresOn);
3381
3382 return certificateView;
3383 }
3384
3385 /**
3386 * Re-formats the certificate date (Date.toString()) string to
3387 * a properly localized date string.
3388 * @return Properly localized version of the certificate date string and
3389 * the original certificate date string if fails to localize.
3390 * If the original string is null, returns an empty string "".
3391 */
3392 private String reformatCertificateDate(String certificateDate) {
3393 String reformattedDate = null;
3394
3395 if (certificateDate != null) {
3396 Date date = null;
3397 try {
3398 date = java.text.DateFormat.getInstance().parse(certificateDate);
3399 } catch (ParseException e) {
3400 date = null;
3401 }
3402
3403 if (date != null) {
3404 reformattedDate =
3405 DateFormat.getDateFormat(this).format(date);
3406 }
3407 }
3408
3409 return reformattedDate != null ? reformattedDate :
3410 (certificateDate != null ? certificateDate : "");
3411 }
3412
3413 /**
3414 * Displays an http-authentication dialog.
3415 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003416 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003417 final String host, final String realm, final String title,
3418 final String name, final String password, int focusId) {
3419 LayoutInflater factory = LayoutInflater.from(this);
3420 final View v = factory
3421 .inflate(R.layout.http_authentication, null);
3422 if (name != null) {
3423 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3424 }
3425 if (password != null) {
3426 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3427 }
3428
3429 String titleText = title;
3430 if (titleText == null) {
3431 titleText = getText(R.string.sign_in_to).toString().replace(
3432 "%s1", host).replace("%s2", realm);
3433 }
3434
3435 mHttpAuthHandler = handler;
3436 AlertDialog dialog = new AlertDialog.Builder(this)
3437 .setTitle(titleText)
3438 .setIcon(android.R.drawable.ic_dialog_alert)
3439 .setView(v)
3440 .setPositiveButton(R.string.action,
3441 new DialogInterface.OnClickListener() {
3442 public void onClick(DialogInterface dialog,
3443 int whichButton) {
3444 String nm = ((EditText) v
3445 .findViewById(R.id.username_edit))
3446 .getText().toString();
3447 String pw = ((EditText) v
3448 .findViewById(R.id.password_edit))
3449 .getText().toString();
3450 BrowserActivity.this.setHttpAuthUsernamePassword
3451 (host, realm, nm, pw);
3452 handler.proceed(nm, pw);
3453 mHttpAuthenticationDialog = null;
3454 mHttpAuthHandler = null;
3455 }})
3456 .setNegativeButton(R.string.cancel,
3457 new DialogInterface.OnClickListener() {
3458 public void onClick(DialogInterface dialog,
3459 int whichButton) {
3460 handler.cancel();
3461 BrowserActivity.this.resetTitleAndRevertLockIcon();
3462 mHttpAuthenticationDialog = null;
3463 mHttpAuthHandler = null;
3464 }})
3465 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3466 public void onCancel(DialogInterface dialog) {
3467 handler.cancel();
3468 BrowserActivity.this.resetTitleAndRevertLockIcon();
3469 mHttpAuthenticationDialog = null;
3470 mHttpAuthHandler = null;
3471 }})
3472 .create();
3473 // Make the IME appear when the dialog is displayed if applicable.
3474 dialog.getWindow().setSoftInputMode(
3475 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3476 dialog.show();
3477 if (focusId != 0) {
3478 dialog.findViewById(focusId).requestFocus();
3479 } else {
3480 v.findViewById(R.id.username_edit).requestFocus();
3481 }
3482 mHttpAuthenticationDialog = dialog;
3483 }
3484
3485 public int getProgress() {
3486 WebView w = mTabControl.getCurrentWebView();
3487 if (w != null) {
3488 return w.getProgress();
3489 } else {
3490 return 100;
3491 }
3492 }
3493
3494 /**
3495 * Set HTTP authentication password.
3496 *
3497 * @param host The host for the password
3498 * @param realm The realm for the password
3499 * @param username The username for the password. If it is null, it means
3500 * password can't be saved.
3501 * @param password The password
3502 */
3503 public void setHttpAuthUsernamePassword(String host, String realm,
3504 String username,
3505 String password) {
3506 WebView w = mTabControl.getCurrentWebView();
3507 if (w != null) {
3508 w.setHttpAuthUsernamePassword(host, realm, username, password);
3509 }
3510 }
3511
3512 /**
3513 * connectivity manager says net has come or gone... inform the user
3514 * @param up true if net has come up, false if net has gone down
3515 */
3516 public void onNetworkToggle(boolean up) {
3517 if (up == mIsNetworkUp) {
3518 return;
3519 } else if (up) {
3520 mIsNetworkUp = true;
3521 if (mAlertDialog != null) {
3522 mAlertDialog.cancel();
3523 mAlertDialog = null;
3524 }
3525 } else {
3526 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003527 if (mInLoad) {
3528 createAndShowNetworkDialog();
3529 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003530 }
3531 WebView w = mTabControl.getCurrentWebView();
3532 if (w != null) {
3533 w.setNetworkAvailable(up);
3534 }
3535 }
3536
Grace Kloba22ac16e2009-10-07 18:00:23 -07003537 boolean isNetworkUp() {
3538 return mIsNetworkUp;
3539 }
3540
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003541 // This method shows the network dialog alerting the user that the net is
3542 // down. It will only show the dialog if mAlertDialog is null.
3543 private void createAndShowNetworkDialog() {
3544 if (mAlertDialog == null) {
3545 mAlertDialog = new AlertDialog.Builder(this)
3546 .setTitle(R.string.loadSuspendedTitle)
3547 .setMessage(R.string.loadSuspended)
3548 .setPositiveButton(R.string.ok, null)
3549 .show();
3550 }
3551 }
3552
The Android Open Source Project0c908882009-03-03 19:32:16 -08003553 @Override
3554 protected void onActivityResult(int requestCode, int resultCode,
3555 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003556 if (getTopWindow() == null) return;
3557
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 switch (requestCode) {
3559 case COMBO_PAGE:
3560 if (resultCode == RESULT_OK && intent != null) {
3561 String data = intent.getAction();
3562 Bundle extras = intent.getExtras();
3563 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003564 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003565 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003566 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003567 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003568 dismissSubWindow(currentTab);
3569 if (data != null && data.length() != 0) {
3570 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003571 }
3572 }
3573 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003574 // Deliberately fall through to PREFERENCES_PAGE, since the
3575 // same extra may be attached to the COMBO_PAGE
3576 case PREFERENCES_PAGE:
3577 if (resultCode == RESULT_OK && intent != null) {
3578 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3579 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3580 mTabControl.removeParentChildRelationShips();
3581 }
3582 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003584 // Choose a file from the file picker.
3585 case FILE_SELECTED:
3586 if (null == mUploadMessage) break;
3587 Uri result = intent == null || resultCode != RESULT_OK ? null
3588 : intent.getData();
3589 mUploadMessage.onReceiveValue(result);
3590 mUploadMessage = null;
3591 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 default:
3593 break;
3594 }
Leon Scroggins30444232009-09-04 18:36:20 -04003595 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003596 }
3597
3598 /*
3599 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003600 * menu to see the download window. It shows the download window on top of
3601 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003602 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003603 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 Intent intent = new Intent(this,
3605 BrowserDownloadPage.class);
3606 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003607 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608
3609 }
3610
Leon Scroggins160a7e72009-08-14 18:28:01 -04003611 /**
3612 * Open the Go page.
3613 * @param startWithHistory If true, open starting on the history tab.
3614 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003615 */
Leon Scroggins30444232009-09-04 18:36:20 -04003616 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 WebView current = mTabControl.getCurrentWebView();
3618 if (current == null) {
3619 return;
3620 }
3621 Intent intent = new Intent(this,
3622 CombinedBookmarkHistoryActivity.class);
3623 String title = current.getTitle();
3624 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003625 Bitmap thumbnail = createScreenshot(current);
3626
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 // Just in case the user opens bookmarks before a page finishes loading
3628 // so the current history item, and therefore the page, is null.
3629 if (null == url) {
3630 url = mLastEnteredUrl;
3631 // This can happen.
3632 if (null == url) {
3633 url = mSettings.getHomePage();
3634 }
3635 }
3636 // In case the web page has not yet received its associated title.
3637 if (title == null) {
3638 title = url;
3639 }
3640 intent.putExtra("title", title);
3641 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003642 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003643 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003644 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003645 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003646 if (startWithHistory) {
3647 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3648 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3649 }
3650 startActivityForResult(intent, COMBO_PAGE);
3651 }
3652
3653 // Called when loading from context menu or LOAD_URL message
3654 private void loadURL(WebView view, String url) {
3655 // In case the user enters nothing.
3656 if (url != null && url.length() != 0 && view != null) {
3657 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003658 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 view.loadUrl(url);
3660 }
3661 }
3662 }
3663
The Android Open Source Project0c908882009-03-03 19:32:16 -08003664 private String smartUrlFilter(Uri inUri) {
3665 if (inUri != null) {
3666 return smartUrlFilter(inUri.toString());
3667 }
3668 return null;
3669 }
3670
Feng Qianb34f87a2009-03-24 21:27:26 -07003671 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003672 "(?i)" + // switch on case insensitive matching
3673 "(" + // begin group for schema
3674 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003675 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003676 ")" +
3677 "(.*)" );
3678
3679 /**
3680 * Attempts to determine whether user input is a URL or search
3681 * terms. Anything with a space is passed to search.
3682 *
3683 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3684 * "Http://" converts to "http://"
3685 *
3686 * @return Original or modified URL
3687 *
3688 */
3689 String smartUrlFilter(String url) {
3690
3691 String inUrl = url.trim();
3692 boolean hasSpace = inUrl.indexOf(' ') != -1;
3693
3694 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3695 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 // force scheme to lowercase
3697 String scheme = matcher.group(1);
3698 String lcScheme = scheme.toLowerCase();
3699 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003700 inUrl = lcScheme + matcher.group(2);
3701 }
3702 if (hasSpace) {
3703 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003704 }
3705 return inUrl;
3706 }
3707 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003708 // FIXME: Is this the correct place to add to searches?
3709 // what if someone else calls this function?
3710 int shortcut = parseUrlShortcut(inUrl);
3711 if (shortcut != SHORTCUT_INVALID) {
3712 Browser.addSearchUrl(mResolver, inUrl);
3713 String query = inUrl.substring(2);
3714 switch (shortcut) {
3715 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003716 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003717 case SHORTCUT_WIKIPEDIA_SEARCH:
3718 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3719 case SHORTCUT_DICTIONARY_SEARCH:
3720 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3721 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003723 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724 }
3725 }
3726 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003727 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728 return URLUtil.guessUrl(inUrl);
3729 }
3730 }
3731
3732 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003733 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003734 }
3735
Ben Murdochbff2d602009-07-01 20:19:05 +01003736 /* package */ void setShouldShowErrorConsole(boolean flag) {
3737 if (flag == mShouldShowErrorConsole) {
3738 // Nothing to do.
3739 return;
3740 }
3741
3742 mShouldShowErrorConsole = flag;
3743
Grace Kloba22ac16e2009-10-07 18:00:23 -07003744 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3745 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003746
3747 if (flag) {
3748 // Setting the show state of the console will cause it's the layout to be inflated.
3749 if (errorConsole.numberOfErrors() > 0) {
3750 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3751 } else {
3752 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3753 }
3754
3755 // Now we can add it to the main view.
3756 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003757 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003758 ViewGroup.LayoutParams.WRAP_CONTENT));
3759 } else {
3760 mErrorConsoleContainer.removeView(errorConsole);
3761 }
3762
3763 }
3764
Grace Kloba22ac16e2009-10-07 18:00:23 -07003765 boolean shouldShowErrorConsole() {
3766 return mShouldShowErrorConsole;
3767 }
3768
Andrei Popescu163ab742009-10-20 17:58:23 +01003769 private void setStatusBarVisibility(boolean visible) {
3770 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3771 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3772 }
3773
Andrei Popescu56199cc2010-01-12 22:39:16 +00003774
3775 private void sendNetworkType(String type, String subtype) {
3776 WebView w = mTabControl.getCurrentWebView();
3777 if (w != null) {
3778 w.setNetworkType(type, subtype);
3779 }
3780 }
3781
Grace Klobaeb6eef42009-09-15 17:56:32 -07003782 final static int LOCK_ICON_UNSECURE = 0;
3783 final static int LOCK_ICON_SECURE = 1;
3784 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003785
The Android Open Source Project0c908882009-03-03 19:32:16 -08003786 private BrowserSettings mSettings;
3787 private TabControl mTabControl;
3788 private ContentResolver mResolver;
3789 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003790 private View mCustomView;
3791 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003792 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003793
3794 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3795 // view, we should rewrite this.
3796 private int mCurrentMenuState = 0;
3797 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003798 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003799 private static final int EMPTY_MENU = -1;
3800 private Menu mMenu;
3801
3802 private FindDialog mFindDialog;
3803 // Used to prevent chording to result in firing two shortcuts immediately
3804 // one after another. Fixes bug 1211714.
3805 boolean mCanChord;
3806
3807 private boolean mInLoad;
3808 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003809 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810
The Android Open Source Project0c908882009-03-03 19:32:16 -08003811 private boolean mActivityInPause = true;
3812
3813 private boolean mMenuIsDown;
3814
The Android Open Source Project0c908882009-03-03 19:32:16 -08003815 private static boolean mInTrace;
3816
3817 // Performance probe
3818 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3819 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3820 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3821 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3822 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3823 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3824 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3825 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3826 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3827 };
3828
3829 private long mStart;
3830 private long mProcessStart;
3831 private long mUserStart;
3832 private long mSystemStart;
3833 private long mIdleStart;
3834 private long mIrqStart;
3835
3836 private long mUiStart;
3837
3838 private Drawable mMixLockIcon;
3839 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003840
3841 /* hold a ref so we can auto-cancel if necessary */
3842 private AlertDialog mAlertDialog;
3843
3844 // Wait for credentials before loading google.com
3845 private ProgressDialog mCredsDlg;
3846
3847 // The up-to-date URL and title (these can be different from those stored
3848 // in WebView, since it takes some time for the information in WebView to
3849 // get updated)
3850 private String mUrl;
3851 private String mTitle;
3852
3853 // As PageInfo has different style for landscape / portrait, we have
3854 // to re-open it when configuration changed
3855 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003856 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003857 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3858 // dialog, we should not just dismiss it, but should get back to the
3859 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003860 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861
3862 // as SSLCertificateOnError has different style for landscape / portrait,
3863 // we have to re-open it when configuration changed
3864 private AlertDialog mSSLCertificateOnErrorDialog;
3865 private WebView mSSLCertificateOnErrorView;
3866 private SslErrorHandler mSSLCertificateOnErrorHandler;
3867 private SslError mSSLCertificateOnErrorError;
3868
3869 // as SSLCertificate has different style for landscape / portrait, we
3870 // have to re-open it when configuration changed
3871 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003872 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003873
3874 // as HttpAuthentication has different style for landscape / portrait, we
3875 // have to re-open it when configuration changed
3876 private AlertDialog mHttpAuthenticationDialog;
3877 private HttpAuthHandler mHttpAuthHandler;
3878
3879 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3880 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003881 ViewGroup.LayoutParams.MATCH_PARENT,
3882 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003883 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3884 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003885 ViewGroup.LayoutParams.MATCH_PARENT,
3886 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003887 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003888 // Google search
3889 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003890 // Wikipedia search
3891 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3892 // Dictionary search
3893 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3894 // Google Mobile Local search
3895 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3896
3897 final static String QUERY_PLACE_HOLDER = "%s";
3898
3899 // "source" parameter for Google search through search key
3900 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3901 // "source" parameter for Google search through goto menu
3902 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3903 // "source" parameter for Google search through simplily type
3904 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3905 // "source" parameter for Google search suggested by the browser
3906 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3907 // "source" parameter for Google search from unknown source
3908 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3909
3910 private final static String LOGTAG = "browser";
3911
The Android Open Source Project0c908882009-03-03 19:32:16 -08003912 private String mLastEnteredUrl;
3913
3914 private PowerManager.WakeLock mWakeLock;
3915 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3916
3917 private Toast mStopToast;
3918
Leon Scroggins68579392009-09-15 15:31:54 -04003919 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003920
Ben Murdochbff2d602009-07-01 20:19:05 +01003921 private LinearLayout mErrorConsoleContainer = null;
3922 private boolean mShouldShowErrorConsole = false;
3923
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 // As the ids are dynamically created, we can't guarantee that they will
3925 // be in sequence, so this static array maps ids to a window number.
3926 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3927 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3928 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3929 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3930
3931 // monitor platform changes
3932 private IntentFilter mNetworkStateChangedFilter;
3933 private BroadcastReceiver mNetworkStateIntentReceiver;
3934
Grace Klobab4da0ad2009-05-14 14:45:40 -07003935 private BroadcastReceiver mPackageInstallationReceiver;
3936
The Android Open Source Project0c908882009-03-03 19:32:16 -08003937 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003938 final static int COMBO_PAGE = 1;
3939 final static int DOWNLOAD_PAGE = 2;
3940 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003941 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003942
Andrei Popescu540035d2009-09-18 18:59:20 +01003943 // the default <video> poster
3944 private Bitmap mDefaultVideoPoster;
3945 // the video progress view
3946 private View mVideoProgressView;
3947
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003948 /**
3949 * A UrlData class to abstract how the content will be set to WebView.
3950 * This base class uses loadUrl to show the content.
3951 */
3952 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003953 final String mUrl;
3954 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003955 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003956
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003957 UrlData(String url) {
3958 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003959 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003960 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003961 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003962
Leon Scroggins58d56c62010-01-28 15:12:40 -05003963 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003964 this.mUrl = url;
3965 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003966 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3967 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003968 this.mVoiceIntent = intent;
3969 } else {
3970 this.mVoiceIntent = null;
3971 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003972 }
3973
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003974 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003975 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003976 }
3977
Leon Scroggins58d56c62010-01-28 15:12:40 -05003978 public void loadIn(Tab t) {
3979 if (mVoiceIntent != null) {
3980 t.activateVoiceSearchMode(mVoiceIntent);
3981 } else {
3982 t.getWebView().loadUrl(mUrl, mHeaders);
3983 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003984 }
3985 };
3986
Leon Scroggins1f005d32009-08-10 17:36:42 -04003987 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003988}