blob: 6167b9a7f2a549867ad9244e67ab6a31d5f5a542 [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
1541 case R.id.zoom_in_menu_id:
1542 getTopWindow().zoomIn();
1543 break;
1544
1545 case R.id.zoom_out_menu_id:
1546 getTopWindow().zoomOut();
1547 break;
1548
1549 case R.id.view_downloads_menu_id:
1550 viewDownloads(null);
1551 break;
1552
The Android Open Source Project0c908882009-03-03 19:32:16 -08001553 case R.id.window_one_menu_id:
1554 case R.id.window_two_menu_id:
1555 case R.id.window_three_menu_id:
1556 case R.id.window_four_menu_id:
1557 case R.id.window_five_menu_id:
1558 case R.id.window_six_menu_id:
1559 case R.id.window_seven_menu_id:
1560 case R.id.window_eight_menu_id:
1561 {
1562 int menuid = item.getItemId();
1563 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1564 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001565 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 if (desiredTab != null &&
1567 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001568 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 }
1570 break;
1571 }
1572 }
1573 }
1574 break;
1575
1576 default:
1577 if (!super.onOptionsItemSelected(item)) {
1578 return false;
1579 }
1580 // Otherwise fall through.
1581 }
1582 mCanChord = false;
1583 return true;
1584 }
1585
1586 public void closeFind() {
1587 mMenuState = R.id.MAIN_MENU;
1588 }
1589
Grace Kloba22ac16e2009-10-07 18:00:23 -07001590 @Override
1591 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001592 // This happens when the user begins to hold down the menu key, so
1593 // allow them to chord to get a shortcut.
1594 mCanChord = true;
1595 // Note: setVisible will decide whether an item is visible; while
1596 // setEnabled() will decide whether an item is enabled, which also means
1597 // whether the matching shortcut key will function.
1598 super.onPrepareOptionsMenu(menu);
1599 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 case EMPTY_MENU:
1601 if (mCurrentMenuState != mMenuState) {
1602 menu.setGroupVisible(R.id.MAIN_MENU, false);
1603 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1604 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 }
1606 break;
1607 default:
1608 if (mCurrentMenuState != mMenuState) {
1609 menu.setGroupVisible(R.id.MAIN_MENU, true);
1610 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1611 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001612 }
1613 final WebView w = getTopWindow();
1614 boolean canGoBack = false;
1615 boolean canGoForward = false;
1616 boolean isHome = false;
1617 if (w != null) {
1618 canGoBack = w.canGoBack();
1619 canGoForward = w.canGoForward();
1620 isHome = mSettings.getHomePage().equals(w.getUrl());
1621 }
1622 final MenuItem back = menu.findItem(R.id.back_menu_id);
1623 back.setEnabled(canGoBack);
1624
1625 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1626 home.setEnabled(!isHome);
1627
1628 menu.findItem(R.id.forward_menu_id)
1629 .setEnabled(canGoForward);
1630
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001631 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001632 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001633
The Android Open Source Project0c908882009-03-03 19:32:16 -08001634 // decide whether to show the share link option
1635 PackageManager pm = getPackageManager();
1636 Intent send = new Intent(Intent.ACTION_SEND);
1637 send.setType("text/plain");
1638 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1639 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1640
The Android Open Source Project0c908882009-03-03 19:32:16 -08001641 boolean isNavDump = mSettings.isNavDump();
1642 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1643 nav.setVisible(isNavDump);
1644 nav.setEnabled(isNavDump);
1645 break;
1646 }
1647 mCurrentMenuState = mMenuState;
1648 return true;
1649 }
1650
1651 @Override
1652 public void onCreateContextMenu(ContextMenu menu, View v,
1653 ContextMenuInfo menuInfo) {
1654 WebView webview = (WebView) v;
1655 WebView.HitTestResult result = webview.getHitTestResult();
1656 if (result == null) {
1657 return;
1658 }
1659
1660 int type = result.getType();
1661 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1662 Log.w(LOGTAG,
1663 "We should not show context menu when nothing is touched");
1664 return;
1665 }
1666 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1667 // let TextView handles context menu
1668 return;
1669 }
1670
1671 // Note, http://b/issue?id=1106666 is requesting that
1672 // an inflated menu can be used again. This is not available
1673 // yet, so inflate each time (yuk!)
1674 MenuInflater inflater = getMenuInflater();
1675 inflater.inflate(R.menu.browsercontext, menu);
1676
1677 // Show the correct menu group
1678 String extra = result.getExtra();
1679 menu.setGroupVisible(R.id.PHONE_MENU,
1680 type == WebView.HitTestResult.PHONE_TYPE);
1681 menu.setGroupVisible(R.id.EMAIL_MENU,
1682 type == WebView.HitTestResult.EMAIL_TYPE);
1683 menu.setGroupVisible(R.id.GEO_MENU,
1684 type == WebView.HitTestResult.GEO_TYPE);
1685 menu.setGroupVisible(R.id.IMAGE_MENU,
1686 type == WebView.HitTestResult.IMAGE_TYPE
1687 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1688 menu.setGroupVisible(R.id.ANCHOR_MENU,
1689 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1690 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1691
1692 // Setup custom handling depending on the type
1693 switch (type) {
1694 case WebView.HitTestResult.PHONE_TYPE:
1695 menu.setHeaderTitle(Uri.decode(extra));
1696 menu.findItem(R.id.dial_context_menu_id).setIntent(
1697 new Intent(Intent.ACTION_VIEW, Uri
1698 .parse(WebView.SCHEME_TEL + extra)));
1699 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1700 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001701 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1703 addIntent);
1704 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1705 new Copy(extra));
1706 break;
1707
1708 case WebView.HitTestResult.EMAIL_TYPE:
1709 menu.setHeaderTitle(extra);
1710 menu.findItem(R.id.email_context_menu_id).setIntent(
1711 new Intent(Intent.ACTION_VIEW, Uri
1712 .parse(WebView.SCHEME_MAILTO + extra)));
1713 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1714 new Copy(extra));
1715 break;
1716
1717 case WebView.HitTestResult.GEO_TYPE:
1718 menu.setHeaderTitle(extra);
1719 menu.findItem(R.id.map_context_menu_id).setIntent(
1720 new Intent(Intent.ACTION_VIEW, Uri
1721 .parse(WebView.SCHEME_GEO
1722 + URLEncoder.encode(extra))));
1723 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1724 new Copy(extra));
1725 break;
1726
1727 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1728 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1729 TextView titleView = (TextView) LayoutInflater.from(this)
1730 .inflate(android.R.layout.browser_link_context_header,
1731 null);
1732 titleView.setText(extra);
1733 menu.setHeaderView(titleView);
1734 // decide whether to show the open link in new tab option
1735 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001736 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001737 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1738 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 PackageManager pm = getPackageManager();
1740 Intent send = new Intent(Intent.ACTION_SEND);
1741 send.setType("text/plain");
1742 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1743 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1744 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1745 break;
1746 }
1747 // otherwise fall through to handle image part
1748 case WebView.HitTestResult.IMAGE_TYPE:
1749 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1750 menu.setHeaderTitle(extra);
1751 }
1752 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1753 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1754 menu.findItem(R.id.download_context_menu_id).
1755 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001756 menu.findItem(R.id.set_wallpaper_context_menu_id).
1757 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 break;
1759
1760 default:
1761 Log.w(LOGTAG, "We should not get here.");
1762 break;
1763 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001764 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001765 }
1766
The Android Open Source Project0c908882009-03-03 19:32:16 -08001767 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001768 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001769 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001770 // Attach the container that contains the main WebView and any other UI
1771 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001772 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001773
1774 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001775 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001776 if (errorConsole.numberOfErrors() == 0) {
1777 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1778 } else {
1779 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1780 }
1781
1782 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001783 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001784 ViewGroup.LayoutParams.WRAP_CONTENT));
1785 }
1786
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001787 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001788 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001789 if (t.isInVoiceSearchMode()) {
1790 showVoiceTitleBar(t.getVoiceDisplayTitle());
1791 } else {
1792 revertVoiceTitleBar();
1793 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 // Request focus on the top window.
1795 t.getTopWindow().requestFocus();
1796 }
1797
1798 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001799 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001800 t.attachSubWindow(mContentView);
1801 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001802 }
1803
1804 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001805 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001806 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001807 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001808
Grace Kloba22ac16e2009-10-07 18:00:23 -07001809 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1810 if (errorConsole != null) {
1811 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001812 }
1813
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001814 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001815 if (view != null) {
1816 view.setEmbeddedTitleBar(null);
1817 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 }
1819
1820 // Remove the sub window if it exists. Also called by TabControl when the
1821 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001822 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001823 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001824 // dismiss the subwindow. This will destroy the WebView.
1825 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001826 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001827 }
1828
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001830 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001831 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001832 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001833 }
1834
1835 // This method does a ton of stuff. It will attempt to create a new tab
1836 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001837 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001838 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1839 String appId) {
1840 final Tab currentTab = mTabControl.getCurrentTab();
1841 if (mTabControl.canCreateNewTab()) {
1842 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1843 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001844 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001845 // If the last tab was removed from the active tabs page, currentTab
1846 // will be null.
1847 if (currentTab != null) {
1848 removeTabFromContentView(currentTab);
1849 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001850 // We must set the new tab as the current tab to reflect the old
1851 // animation behavior.
1852 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001853 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001854 if (!urlData.isEmpty()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05001855 urlData.loadIn(tab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 }
1857 return tab;
1858 } else {
1859 // Get rid of the subwindow if it exists
1860 dismissSubWindow(currentTab);
1861 if (!urlData.isEmpty()) {
1862 // Load the given url.
Leon Scroggins58d56c62010-01-28 15:12:40 -05001863 urlData.loadIn(currentTab);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001864 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001865 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001866 }
1867 }
1868
Grace Kloba22ac16e2009-10-07 18:00:23 -07001869 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001870 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001871 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001873 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001874 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001875 }
Grace Klobac9181842009-04-14 08:53:22 -07001876 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001877 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001878 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001879 }
1880 }
1881
1882 private class Copy implements OnMenuItemClickListener {
1883 private CharSequence mText;
1884
1885 public boolean onMenuItemClick(MenuItem item) {
1886 copy(mText);
1887 return true;
1888 }
1889
1890 public Copy(CharSequence toCopy) {
1891 mText = toCopy;
1892 }
1893 }
1894
1895 private class Download implements OnMenuItemClickListener {
1896 private String mText;
1897
1898 public boolean onMenuItemClick(MenuItem item) {
1899 onDownloadStartNoStream(mText, null, null, null, -1);
1900 return true;
1901 }
1902
1903 public Download(String toDownload) {
1904 mText = toDownload;
1905 }
1906 }
1907
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001908 private class SetAsWallpaper extends Thread implements
1909 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1910 private URL mUrl;
1911 private ProgressDialog mWallpaperProgress;
1912 private boolean mCanceled = false;
1913
1914 public SetAsWallpaper(String url) {
1915 try {
1916 mUrl = new URL(url);
1917 } catch (MalformedURLException e) {
1918 mUrl = null;
1919 }
1920 }
1921
1922 public void onCancel(DialogInterface dialog) {
1923 mCanceled = true;
1924 }
1925
1926 public boolean onMenuItemClick(MenuItem item) {
1927 if (mUrl != null) {
1928 // The user may have tried to set a image with a large file size as their
1929 // background so it may take a few moments to perform the operation. Display
1930 // a progress spinner while it is working.
1931 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1932 mWallpaperProgress.setIndeterminate(true);
1933 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1934 mWallpaperProgress.setCancelable(true);
1935 mWallpaperProgress.setOnCancelListener(this);
1936 mWallpaperProgress.show();
1937 start();
1938 }
1939 return true;
1940 }
1941
1942 public void run() {
1943 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1944 try {
1945 // TODO: This will cause the resource to be downloaded again, when we
1946 // should in most cases be able to grab it from the cache. To fix this
1947 // we should query WebCore to see if we can access a cached version and
1948 // instead open an input stream on that. This pattern could also be used
1949 // in the download manager where the same problem exists.
1950 InputStream inputstream = mUrl.openStream();
1951 if (inputstream != null) {
1952 setWallpaper(inputstream);
1953 }
1954 } catch (IOException e) {
1955 Log.e(LOGTAG, "Unable to set new wallpaper");
1956 // Act as though the user canceled the operation so we try to
1957 // restore the old wallpaper.
1958 mCanceled = true;
1959 }
1960
1961 if (mCanceled) {
1962 // Restore the old wallpaper if the user cancelled whilst we were setting
1963 // the new wallpaper.
1964 int width = oldWallpaper.getIntrinsicWidth();
1965 int height = oldWallpaper.getIntrinsicHeight();
1966 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1967 Canvas canvas = new Canvas(bm);
1968 oldWallpaper.setBounds(0, 0, width, height);
1969 oldWallpaper.draw(canvas);
1970 try {
1971 setWallpaper(bm);
1972 } catch (IOException e) {
1973 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1974 }
1975 mCanceled = false;
1976 }
1977
1978 if (mWallpaperProgress.isShowing()) {
1979 mWallpaperProgress.dismiss();
1980 }
1981 }
1982 }
1983
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 private void copy(CharSequence text) {
1985 try {
1986 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1987 if (clip != null) {
1988 clip.setClipboardText(text);
1989 }
1990 } catch (android.os.RemoteException e) {
1991 Log.e(LOGTAG, "Copy failed", e);
1992 }
1993 }
1994
1995 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001996 * Resets the browser title-view to whatever it must be
1997 * (for example, if we had a loading error)
1998 * When we have a new page, we call resetTitle, when we
1999 * have to reset the titlebar to whatever it used to be
2000 * (for example, if the user chose to stop loading), we
2001 * call resetTitleAndRevertLockIcon.
2002 */
2003 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002004 mTabControl.getCurrentTab().revertLockIcon();
2005 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 resetTitleIconAndProgress();
2007 }
2008
2009 /**
2010 * Reset the title, favicon, and progress.
2011 */
2012 private void resetTitleIconAndProgress() {
2013 WebView current = mTabControl.getCurrentWebView();
2014 if (current == null) {
2015 return;
2016 }
2017 resetTitleAndIcon(current);
2018 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002019 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002020 }
2021
2022 // Reset the title and the icon based on the given item.
2023 private void resetTitleAndIcon(WebView view) {
2024 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2025 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002026 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 setFavicon(item.getFavicon());
2028 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002029 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002030 setFavicon(null);
2031 }
2032 }
2033
2034 /**
2035 * Sets a title composed of the URL and the title string.
2036 * @param url The URL of the site being loaded.
2037 * @param title The title of the site being loaded.
2038 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002039 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 mUrl = url;
2041 mTitle = title;
2042
Leon Scroggins58d56c62010-01-28 15:12:40 -05002043 // If we are in voice search mode, the title has already been set.
2044 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2045 mTitleBar.setDisplayTitle(url);
2046 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 }
2048
2049 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 * @param url The URL to build a title version of the URL from.
2051 * @return The title version of the URL or null if fails.
2052 * The title version of the URL can be either the URL hostname,
2053 * or the hostname with an "https://" prefix (for secure URLs),
2054 * or an empty string if, for example, the URL in question is a
2055 * file:// URL with no hostname.
2056 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002057 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002058 String titleUrl = null;
2059
2060 if (url != null) {
2061 try {
2062 // parse the url string
2063 URL urlObj = new URL(url);
2064 if (urlObj != null) {
2065 titleUrl = "";
2066
2067 String protocol = urlObj.getProtocol();
2068 String host = urlObj.getHost();
2069
2070 if (host != null && 0 < host.length()) {
2071 titleUrl = host;
2072 if (protocol != null) {
2073 // if a secure site, add an "https://" prefix!
2074 if (protocol.equalsIgnoreCase("https")) {
2075 titleUrl = protocol + "://" + host;
2076 }
2077 }
2078 }
2079 }
2080 } catch (MalformedURLException e) {}
2081 }
2082
2083 return titleUrl;
2084 }
2085
2086 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002087 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002088 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002089 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002090 }
2091
2092 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002093 * Close the tab, remove its associated title bar, and adjust mTabControl's
2094 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002095 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002096 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002097 int currentIndex = mTabControl.getCurrentIndex();
2098 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002099 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002100 if (currentIndex >= removeIndex && currentIndex != 0) {
2101 currentIndex--;
2102 }
2103 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002104 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105 }
2106
2107 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002108 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002109 if (current == null) {
2110 /*
2111 * Instead of finishing the activity, simply push this to the back
2112 * of the stack and let ActivityManager to choose the foreground
2113 * activity. As BrowserActivity is singleTask, it will be always the
2114 * root of the task. So we can use either true or false for
2115 * moveTaskToBack().
2116 */
2117 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002118 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002119 }
2120 WebView w = current.getWebView();
2121 if (w.canGoBack()) {
2122 w.goBack();
2123 } else {
2124 // Check to see if we are closing a window that was created by
2125 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002126 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002128 switchToTab(mTabControl.getTabIndex(parent));
2129 // Now we close the other tab
2130 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 } else {
2132 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002133 // force the tab's inLoad() to be false as we are going to
2134 // either finish the activity or remove the tab. This will
2135 // ensure pauseWebViewTimers() taking action.
2136 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 if (mTabControl.getTabCount() == 1) {
2138 finish();
2139 return;
2140 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002141 // call pauseWebViewTimers() now, we won't be able to call
2142 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002143 // Temporarily change mActivityInPause to be true as
2144 // pauseWebViewTimers() will do nothing if mActivityInPause
2145 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002146 boolean savedState = mActivityInPause;
2147 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002148 Log.e(LOGTAG, "BrowserActivity is already paused "
2149 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002150 }
2151 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002152 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002153 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 removeTabFromContentView(current);
2155 mTabControl.removeTab(current);
2156 }
2157 /*
2158 * Instead of finishing the activity, simply push this to the back
2159 * of the stack and let ActivityManager to choose the foreground
2160 * activity. As BrowserActivity is singleTask, it will be always the
2161 * root of the task. So we can use either true or false for
2162 * moveTaskToBack().
2163 */
2164 moveTaskToBack(true);
2165 }
2166 }
2167 }
2168
Grace Kloba22ac16e2009-10-07 18:00:23 -07002169 boolean isMenuDown() {
2170 return mMenuIsDown;
2171 }
2172
Grace Kloba5942df02009-09-18 11:48:29 -07002173 @Override
2174 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002175 // Even if MENU is already held down, we need to call to super to open
2176 // the IME on long press.
2177 if (KeyEvent.KEYCODE_MENU == keyCode) {
2178 mMenuIsDown = true;
2179 return super.onKeyDown(keyCode, event);
2180 }
Grace Kloba5942df02009-09-18 11:48:29 -07002181 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2182 // still down, we don't want to trigger the search. Pretend to consume
2183 // the key and do nothing.
2184 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002185
Grace Kloba5942df02009-09-18 11:48:29 -07002186 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002187 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002188 // WebView/WebTextView handle the keys in the KeyDown. As
2189 // the Activity's shortcut keys are only handled when WebView
2190 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2191 if (event.isShiftPressed()) {
2192 getTopWindow().pageUp(false);
2193 } else {
2194 getTopWindow().pageDown(false);
2195 }
Grace Kloba5942df02009-09-18 11:48:29 -07002196 return true;
2197 case KeyEvent.KEYCODE_BACK:
2198 if (event.getRepeatCount() == 0) {
2199 event.startTracking();
2200 return true;
2201 } else if (mCustomView == null && mActiveTabsPage == null
2202 && event.isLongPress()) {
2203 bookmarksOrHistoryPicker(true);
2204 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002205 }
Grace Kloba5942df02009-09-18 11:48:29 -07002206 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207 }
Grace Kloba5942df02009-09-18 11:48:29 -07002208 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002209 }
2210
Grace Kloba5942df02009-09-18 11:48:29 -07002211 @Override
2212 public boolean onKeyUp(int keyCode, KeyEvent event) {
2213 switch(keyCode) {
2214 case KeyEvent.KEYCODE_MENU:
2215 mMenuIsDown = false;
2216 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002217 case KeyEvent.KEYCODE_BACK:
2218 if (event.isTracking() && !event.isCanceled()) {
2219 if (mCustomView != null) {
2220 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002221 mTabControl.getCurrentWebView().getWebChromeClient()
2222 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002223 } else if (mActiveTabsPage != null) {
2224 // if tab page is showing, hide it
2225 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002227 WebView subwindow = mTabControl.getCurrentSubWindow();
2228 if (subwindow != null) {
2229 if (subwindow.canGoBack()) {
2230 subwindow.goBack();
2231 } else {
2232 dismissSubWindow(mTabControl.getCurrentTab());
2233 }
2234 } else {
2235 goBackOnePageOrQuit();
2236 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002237 }
Grace Kloba5942df02009-09-18 11:48:29 -07002238 return true;
2239 }
2240 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241 }
Grace Kloba5942df02009-09-18 11:48:29 -07002242 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 }
2244
Leon Scroggins68579392009-09-15 15:31:54 -04002245 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002246 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 resetTitleAndRevertLockIcon();
2248 WebView w = getTopWindow();
2249 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002250 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2251 // same logic here. But for subwindow case, should we call into the main
2252 // WebView's onPageFinished as we never call its onPageStarted and if
2253 // the page finishes itself, we don't call onPageFinished.
2254 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2255 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256
2257 cancelStopToast();
2258 mStopToast = Toast
2259 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2260 mStopToast.show();
2261 }
2262
Grace Kloba22ac16e2009-10-07 18:00:23 -07002263 boolean didUserStopLoading() {
2264 return mDidStopLoad;
2265 }
2266
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 private void cancelStopToast() {
2268 if (mStopToast != null) {
2269 mStopToast.cancel();
2270 mStopToast = null;
2271 }
2272 }
2273
Grace Kloba22ac16e2009-10-07 18:00:23 -07002274 // called by a UI or non-UI thread to post the message
2275 public void postMessage(int what, int arg1, int arg2, Object obj,
2276 long delayMillis) {
2277 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2278 obj), delayMillis);
2279 }
2280
2281 // called by a UI or non-UI thread to remove the message
2282 void removeMessages(int what, Object object) {
2283 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002284 }
2285
2286 // public message ids
2287 public final static int LOAD_URL = 1001;
2288 public final static int STOP_LOAD = 1002;
2289
2290 // Message Ids
2291 private static final int FOCUS_NODE_HREF = 102;
2292 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002293 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294
Grace Kloba22ac16e2009-10-07 18:00:23 -07002295 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002296
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 // Private handler for handling javascript and saving passwords
2298 private Handler mHandler = new Handler() {
2299
2300 public void handleMessage(Message msg) {
2301 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002302 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002303 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002304 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002305 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002306 if (url == null || url.length() == 0) {
2307 break;
2308 }
2309 HashMap focusNodeMap = (HashMap) msg.obj;
2310 WebView view = (WebView) focusNodeMap.get("webview");
2311 // Only apply the action if the top window did not change.
2312 if (getTopWindow() != view) {
2313 break;
2314 }
2315 switch (msg.arg1) {
2316 case R.id.open_context_menu_id:
2317 case R.id.view_image_context_menu_id:
2318 loadURL(getTopWindow(), url);
2319 break;
2320 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002321 final Tab parent = mTabControl.getCurrentTab();
2322 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002323 if (newTab != parent) {
2324 parent.addChildTab(newTab);
2325 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002326 break;
2327 case R.id.bookmark_context_menu_id:
2328 Intent intent = new Intent(BrowserActivity.this,
2329 AddBookmarkPage.class);
2330 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002331 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002332 startActivity(intent);
2333 break;
2334 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002335 // See if this site has been visited before
2336 StringBuilder sb = new StringBuilder(
2337 Browser.BookmarkColumns.URL + " = ");
2338 DatabaseUtils.appendEscapedSQLString(sb, url);
2339 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2340 Browser.HISTORY_PROJECTION,
2341 sb.toString(),
2342 null,
2343 null);
2344 if (c.moveToFirst()) {
2345 // The site has been visited before, so grab the
2346 // info from the database.
2347 Bitmap favicon = null;
2348 Bitmap thumbnail = null;
2349 String linkTitle = c.getString(Browser.
2350 HISTORY_PROJECTION_TITLE_INDEX);
2351 byte[] data = c.getBlob(Browser.
2352 HISTORY_PROJECTION_FAVICON_INDEX);
2353 if (data != null) {
2354 favicon = BitmapFactory.decodeByteArray(
2355 data, 0, data.length);
2356 }
2357 data = c.getBlob(Browser.
2358 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2359 if (data != null) {
2360 thumbnail = BitmapFactory.decodeByteArray(
2361 data, 0, data.length);
2362 }
2363 sharePage(BrowserActivity.this,
2364 linkTitle, url, favicon, thumbnail);
2365 } else {
2366 Browser.sendString(BrowserActivity.this, url,
2367 getString(
2368 R.string.choosertitle_sharevia));
2369 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002370 break;
2371 case R.id.copy_link_context_menu_id:
2372 copy(url);
2373 break;
2374 case R.id.save_link_context_menu_id:
2375 case R.id.download_context_menu_id:
2376 onDownloadStartNoStream(url, null, null, null, -1);
2377 break;
2378 }
2379 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002380 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002381
2382 case LOAD_URL:
2383 loadURL(getTopWindow(), (String) msg.obj);
2384 break;
2385
2386 case STOP_LOAD:
2387 stopLoading();
2388 break;
2389
2390 case CANCEL_CREDS_REQUEST:
2391 resumeAfterCredentials();
2392 break;
2393
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 case RELEASE_WAKELOCK:
2395 if (mWakeLock.isHeld()) {
2396 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002397 // if we reach here, Browser should be still in the
2398 // background loading after WAKELOCK_TIMEOUT (5-min).
2399 // To avoid burning the battery, stop loading.
2400 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002401 }
2402 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002403
2404 case UPDATE_BOOKMARK_THUMBNAIL:
2405 WebView view = (WebView) msg.obj;
2406 if (view != null) {
2407 updateScreenshot(view);
2408 }
2409 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 }
2411 }
2412 };
2413
Leon Scroggins96afcb12009-12-10 12:35:56 -05002414 /**
2415 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2416 * an {@link Intent} to launch the Activity chooser.
2417 * @param c Context used to launch a new Activity.
2418 * @param title Title of the page. Stored in the Intent with
2419 * {@link Browser#EXTRA_SHARE_TITLE}
2420 * @param url URL of the page. Stored in the Intent with
2421 * {@link Intent#EXTRA_TEXT}
2422 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2423 * with {@link Browser#EXTRA_SHARE_FAVICON}
2424 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2425 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2426 */
2427 public static final void sharePage(Context c, String title, String url,
2428 Bitmap favicon, Bitmap screenshot) {
2429 Intent send = new Intent(Intent.ACTION_SEND);
2430 send.setType("text/plain");
2431 send.putExtra(Intent.EXTRA_TEXT, url);
2432 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2433 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2434 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2435 try {
2436 c.startActivity(Intent.createChooser(send, c.getString(
2437 R.string.choosertitle_sharevia)));
2438 } catch(android.content.ActivityNotFoundException ex) {
2439 // if no app handles it, do nothing
2440 }
2441 }
2442
Leon Scroggins89c6d362009-07-15 16:54:37 -04002443 private void updateScreenshot(WebView view) {
2444 // If this is a bookmarked site, add a screenshot to the database.
2445 // FIXME: When should we update? Every time?
2446 // FIXME: Would like to make sure there is actually something to
2447 // draw, but the API for that (WebViewCore.pictureReady()) is not
2448 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002449
Patrick Scott3918d442009-08-04 13:22:29 -04002450 ContentResolver cr = getContentResolver();
2451 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002452 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002453 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002454 boolean succeed = c.moveToFirst();
2455 ContentValues values = null;
2456 while (succeed) {
2457 if (values == null) {
2458 final ByteArrayOutputStream os
2459 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002460 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002461 if (bm == null) {
2462 c.close();
2463 return;
2464 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002465 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2466 values = new ContentValues();
2467 values.put(Browser.BookmarkColumns.THUMBNAIL,
2468 os.toByteArray());
2469 }
2470 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2471 c.getInt(0)), values, null, null);
2472 succeed = c.moveToNext();
2473 }
2474 c.close();
2475 }
2476 }
2477
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002478 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002479 * Values for the size of the thumbnail created when taking a screenshot.
2480 * Lazily initialized. Instead of using these directly, use
2481 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002482 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002483 private static int THUMBNAIL_WIDTH = 0;
2484 private static int THUMBNAIL_HEIGHT = 0;
2485
2486 /**
2487 * Return the desired width for thumbnail screenshots, which are stored in
2488 * the database, and used on the bookmarks screen.
2489 * @param context Context for finding out the density of the screen.
2490 * @return int desired width for thumbnail screenshot.
2491 */
2492 /* package */ static int getDesiredThumbnailWidth(Context context) {
2493 if (THUMBNAIL_WIDTH == 0) {
2494 float density = context.getResources().getDisplayMetrics().density;
2495 THUMBNAIL_WIDTH = (int) (90 * density);
2496 THUMBNAIL_HEIGHT = (int) (80 * density);
2497 }
2498 return THUMBNAIL_WIDTH;
2499 }
2500
2501 /**
2502 * Return the desired height for thumbnail screenshots, which are stored in
2503 * the database, and used on the bookmarks screen.
2504 * @param context Context for finding out the density of the screen.
2505 * @return int desired height for thumbnail screenshot.
2506 */
2507 /* package */ static int getDesiredThumbnailHeight(Context context) {
2508 // To ensure that they are both initialized.
2509 getDesiredThumbnailWidth(context);
2510 return THUMBNAIL_HEIGHT;
2511 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002512
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002513 private Bitmap createScreenshot(WebView view) {
2514 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002515 if (thumbnail == null) {
2516 return null;
2517 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002518 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2519 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002520 Canvas canvas = new Canvas(bm);
2521 // May need to tweak these values to determine what is the
2522 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002523 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002524 int thumbnailHeight = thumbnail.getHeight();
2525 float scaleFactorX = 1.0f;
2526 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002527 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002528 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002529 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002530 } else {
2531 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002532 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002533
2534 if (view.getWidth() > view.getHeight() &&
2535 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2536 // If the device is in landscape and the page is shorter
2537 // than the height of the view, stretch the thumbnail to fill the
2538 // space.
2539 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2540 (float)thumbnailHeight;
2541 } else {
2542 // In the portrait case, this looks nice.
2543 scaleFactorY = scaleFactorX;
2544 }
2545
2546 canvas.scale(scaleFactorX, scaleFactorY);
2547
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002548 thumbnail.draw(canvas);
2549 return bm;
2550 }
2551
The Android Open Source Project0c908882009-03-03 19:32:16 -08002552 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002553 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002554 //-------------------------------------------------------------------------
2555
2556 // Use in overrideUrlLoading
2557 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2558 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2559 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2560 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2561
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 void onPageStarted(WebView view, String url, Bitmap favicon) {
2563 // when BrowserActivity just starts, onPageStarted may be called before
2564 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2565 // to start the timer. As we won't switch tabs while an activity is in
2566 // pause state, we can ensure calling resume and pause in pair.
2567 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 resetLockIcon(url);
2570 setUrlTitle(url, null);
2571 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002572 // Keep this initial progress in sync with initialProgressValue (* 100)
2573 // in ProgressTracker.cpp
2574 // Show some progress so that the user knows the page is beginning to
2575 // load
2576 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002578 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002579
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 if (mSettings.isTracing()) {
2581 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002582 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002583 WebAddress uri = new WebAddress(url);
2584 host = uri.mHost;
2585 } catch (android.net.ParseException ex) {
2586 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 host = host.replace('.', '_');
2589 host += ".trace";
2590 mInTrace = true;
2591 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2592 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002593
Grace Kloba22ac16e2009-10-07 18:00:23 -07002594 // Performance probe
2595 if (false) {
2596 mStart = SystemClock.uptimeMillis();
2597 mProcessStart = Process.getElapsedCpuTime();
2598 long[] sysCpu = new long[7];
2599 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2600 sysCpu, null)) {
2601 mUserStart = sysCpu[0] + sysCpu[1];
2602 mSystemStart = sysCpu[2];
2603 mIdleStart = sysCpu[3];
2604 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2605 }
2606 mUiStart = SystemClock.currentThreadTimeMillis();
2607 }
2608 }
2609
2610 void onPageFinished(WebView view, String url) {
2611 // Reset the title and icon in case we stopped a provisional load.
2612 resetTitleAndIcon(view);
2613 // Update the lock icon image only once we are done loading
2614 updateLockIconToLatest();
2615 // pause the WebView timer and release the wake lock if it is finished
2616 // while BrowserActivity is in pause state.
2617 if (mActivityInPause && pauseWebViewTimers()) {
2618 if (mWakeLock.isHeld()) {
2619 mHandler.removeMessages(RELEASE_WAKELOCK);
2620 mWakeLock.release();
2621 }
2622 }
2623
2624 // Performance probe
2625 if (false) {
2626 long[] sysCpu = new long[7];
2627 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2628 sysCpu, null)) {
2629 String uiInfo = "UI thread used "
2630 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2631 + " ms";
2632 if (LOGD_ENABLED) {
2633 Log.d(LOGTAG, uiInfo);
2634 }
2635 //The string that gets written to the log
2636 String performanceString = "It took total "
2637 + (SystemClock.uptimeMillis() - mStart)
2638 + " ms clock time to load the page."
2639 + "\nbrowser process used "
2640 + (Process.getElapsedCpuTime() - mProcessStart)
2641 + " ms, user processes used "
2642 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2643 + " ms, kernel used "
2644 + (sysCpu[2] - mSystemStart) * 10
2645 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2646 + " ms and irq took "
2647 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2648 * 10 + " ms, " + uiInfo;
2649 if (LOGD_ENABLED) {
2650 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2651 }
2652 if (url != null) {
2653 // strip the url to maintain consistency
2654 String newUrl = new String(url);
2655 if (newUrl.startsWith("http://www.")) {
2656 newUrl = newUrl.substring(11);
2657 } else if (newUrl.startsWith("http://")) {
2658 newUrl = newUrl.substring(7);
2659 } else if (newUrl.startsWith("https://www.")) {
2660 newUrl = newUrl.substring(12);
2661 } else if (newUrl.startsWith("https://")) {
2662 newUrl = newUrl.substring(8);
2663 }
2664 if (LOGD_ENABLED) {
2665 Log.d(LOGTAG, newUrl + " loaded");
2666 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002667 }
2668 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002669 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002670
Grace Kloba22ac16e2009-10-07 18:00:23 -07002671 if (mInTrace) {
2672 mInTrace = false;
2673 Debug.stopMethodTracing();
2674 }
2675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002676
Grace Kloba22ac16e2009-10-07 18:00:23 -07002677 boolean shouldOverrideUrlLoading(WebView view, String url) {
2678 if (url.startsWith(SCHEME_WTAI)) {
2679 // wtai://wp/mc;number
2680 // number=string(phone-number)
2681 if (url.startsWith(SCHEME_WTAI_MC)) {
2682 Intent intent = new Intent(Intent.ACTION_VIEW,
2683 Uri.parse(WebView.SCHEME_TEL +
2684 url.substring(SCHEME_WTAI_MC.length())));
2685 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 return true;
2687 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 // wtai://wp/sd;dtmf
2689 // dtmf=string(dialstring)
2690 if (url.startsWith(SCHEME_WTAI_SD)) {
2691 // TODO: only send when there is active voice connection
2692 return false;
2693 }
2694 // wtai://wp/ap;number;name
2695 // number=string(phone-number)
2696 // name=string
2697 if (url.startsWith(SCHEME_WTAI_AP)) {
2698 // TODO
2699 return false;
2700 }
2701 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 // The "about:" schemes are internal to the browser; don't want these to
2704 // be dispatched to other apps.
2705 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002706 return false;
2707 }
2708
Grace Kloba22ac16e2009-10-07 18:00:23 -07002709 Intent intent;
2710 // perform generic parsing of the URI to turn it into an Intent.
2711 try {
2712 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2713 } catch (URISyntaxException ex) {
2714 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2715 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716 }
2717
Grace Kloba22ac16e2009-10-07 18:00:23 -07002718 // check whether the intent can be resolved. If not, we will see
2719 // whether we can download it from the Market.
2720 if (getPackageManager().resolveActivity(intent, 0) == null) {
2721 String packagename = intent.getPackage();
2722 if (packagename != null) {
2723 intent = new Intent(Intent.ACTION_VIEW, Uri
2724 .parse("market://search?q=pname:" + packagename));
2725 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2726 startActivity(intent);
2727 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 } else {
2729 return false;
2730 }
2731 }
2732
Grace Kloba22ac16e2009-10-07 18:00:23 -07002733 // sanitize the Intent, ensuring web pages can not bypass browser
2734 // security (only access to BROWSABLE activities).
2735 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2736 intent.setComponent(null);
2737 try {
2738 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002739 return true;
2740 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002741 } catch (ActivityNotFoundException ex) {
2742 // ignore the error. If no application can handle the URL,
2743 // eg about:blank, assume the browser can handle it.
2744 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002745
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 if (mMenuIsDown) {
2747 openTab(url);
2748 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002749 return true;
2750 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 return false;
2752 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002753
Grace Kloba22ac16e2009-10-07 18:00:23 -07002754 // -------------------------------------------------------------------------
2755 // Helper function for WebChromeClient
2756 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002757
Grace Kloba22ac16e2009-10-07 18:00:23 -07002758 void onProgressChanged(WebView view, int newProgress) {
2759 mTitleBar.setProgress(newProgress);
2760 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002761
Grace Kloba22ac16e2009-10-07 18:00:23 -07002762 if (newProgress == 100) {
2763 // onProgressChanged() may continue to be called after the main
2764 // frame has finished loading, as any remaining sub frames continue
2765 // to load. We'll only get called once though with newProgress as
2766 // 100 when everything is loaded. (onPageFinished is called once
2767 // when the main frame completes loading regardless of the state of
2768 // any sub frames so calls to onProgressChanges may continue after
2769 // onPageFinished has executed)
2770 if (mInLoad) {
2771 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002772 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773 // If the options menu is open, leave the title bar
2774 if (!mOptionsMenuOpen || !mIconView) {
2775 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002776 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002777 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002778 } else if (!mInLoad) {
2779 // onPageFinished may have already been called but a subframe is
2780 // still loading and updating the progress. Reset mInLoad and update
2781 // the menu items.
2782 mInLoad = true;
2783 updateInLoadMenuItems();
2784 if (!mOptionsMenuOpen || mIconView) {
2785 // This page has begun to load, so show the title bar
2786 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 }
2788 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002789 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790
Grace Kloba22ac16e2009-10-07 18:00:23 -07002791 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002792 // if a view already exists then immediately terminate the new one
2793 if (mCustomView != null) {
2794 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002795 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002796 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797
2798 // Add the custom view to its container.
2799 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2800 mCustomView = view;
2801 mCustomViewCallback = callback;
2802 // Save the menu state and set it to empty while the custom
2803 // view is showing.
2804 mOldMenuState = mMenuState;
2805 mMenuState = EMPTY_MENU;
2806 // Hide the content view.
2807 mContentView.setVisibility(View.GONE);
2808 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002809 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 mCustomViewContainer.setVisibility(View.VISIBLE);
2811 mCustomViewContainer.bringToFront();
2812 }
2813
2814 void onHideCustomView() {
2815 if (mCustomView == null)
2816 return;
2817
2818 // Hide the custom view.
2819 mCustomView.setVisibility(View.GONE);
2820 // Remove the custom view from its container.
2821 mCustomViewContainer.removeView(mCustomView);
2822 mCustomView = null;
2823 // Reset the old menu state.
2824 mMenuState = mOldMenuState;
2825 mOldMenuState = EMPTY_MENU;
2826 mCustomViewContainer.setVisibility(View.GONE);
2827 mCustomViewCallback.onCustomViewHidden();
2828 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002829 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002830 mContentView.setVisibility(View.VISIBLE);
2831 }
2832
2833 Bitmap getDefaultVideoPoster() {
2834 if (mDefaultVideoPoster == null) {
2835 mDefaultVideoPoster = BitmapFactory.decodeResource(
2836 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002837 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 return mDefaultVideoPoster;
2839 }
Patrick Scott3918d442009-08-04 13:22:29 -04002840
Grace Kloba22ac16e2009-10-07 18:00:23 -07002841 View getVideoLoadingProgressView() {
2842 if (mVideoProgressView == null) {
2843 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2844 mVideoProgressView = inflater.inflate(
2845 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002846 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002847 return mVideoProgressView;
2848 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002849
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002850 /*
2851 * The Object used to inform the WebView of the file to upload.
2852 */
2853 private ValueCallback<Uri> mUploadMessage;
2854
Grace Kloba22ac16e2009-10-07 18:00:23 -07002855 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2856 if (mUploadMessage != null) return;
2857 mUploadMessage = uploadMsg;
2858 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2859 i.addCategory(Intent.CATEGORY_OPENABLE);
2860 i.setType("*/*");
2861 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2862 getString(R.string.choose_upload)), FILE_SELECTED);
2863 }
2864
2865 // -------------------------------------------------------------------------
2866 // Implement functions for DownloadListener
2867 // -------------------------------------------------------------------------
2868
The Android Open Source Project0c908882009-03-03 19:32:16 -08002869 /**
2870 * Notify the host application a download should be done, or that
2871 * the data should be streamed if a streaming viewer is available.
2872 * @param url The full url to the content that should be downloaded
2873 * @param contentDisposition Content-disposition http header, if
2874 * present.
2875 * @param mimetype The mimetype of the content reported by the server
2876 * @param contentLength The file size reported by the server
2877 */
2878 public void onDownloadStart(String url, String userAgent,
2879 String contentDisposition, String mimetype, long contentLength) {
2880 // if we're dealing wih A/V content that's not explicitly marked
2881 // for download, check if it's streamable.
2882 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002883 || !contentDisposition.regionMatches(
2884 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885 // query the package manager to see if there's a registered handler
2886 // that matches.
2887 Intent intent = new Intent(Intent.ACTION_VIEW);
2888 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002889 ResolveInfo info = getPackageManager().resolveActivity(intent,
2890 PackageManager.MATCH_DEFAULT_ONLY);
2891 if (info != null) {
2892 ComponentName myName = getComponentName();
2893 // If we resolved to ourselves, we don't want to attempt to
2894 // load the url only to try and download it again.
2895 if (!myName.getPackageName().equals(
2896 info.activityInfo.packageName)
2897 || !myName.getClassName().equals(
2898 info.activityInfo.name)) {
2899 // someone (other than us) knows how to handle this mime
2900 // type with this scheme, don't download.
2901 try {
2902 startActivity(intent);
2903 return;
2904 } catch (ActivityNotFoundException ex) {
2905 if (LOGD_ENABLED) {
2906 Log.d(LOGTAG, "activity not found for " + mimetype
2907 + " over " + Uri.parse(url).getScheme(),
2908 ex);
2909 }
2910 // Best behavior is to fall back to a download in this
2911 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002912 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002913 }
2914 }
2915 }
2916 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2917 }
2918
2919 /**
2920 * Notify the host application a download should be done, even if there
2921 * is a streaming viewer available for thise type.
2922 * @param url The full url to the content that should be downloaded
2923 * @param contentDisposition Content-disposition http header, if
2924 * present.
2925 * @param mimetype The mimetype of the content reported by the server
2926 * @param contentLength The file size reported by the server
2927 */
2928 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2929 String contentDisposition, String mimetype, long contentLength) {
2930
2931 String filename = URLUtil.guessFileName(url,
2932 contentDisposition, mimetype);
2933
2934 // Check to see if we have an SDCard
2935 String status = Environment.getExternalStorageState();
2936 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2937 int title;
2938 String msg;
2939
2940 // Check to see if the SDCard is busy, same as the music app
2941 if (status.equals(Environment.MEDIA_SHARED)) {
2942 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2943 title = R.string.download_sdcard_busy_dlg_title;
2944 } else {
2945 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2946 title = R.string.download_no_sdcard_dlg_title;
2947 }
2948
2949 new AlertDialog.Builder(this)
2950 .setTitle(title)
2951 .setIcon(android.R.drawable.ic_dialog_alert)
2952 .setMessage(msg)
2953 .setPositiveButton(R.string.ok, null)
2954 .show();
2955 return;
2956 }
2957
2958 // java.net.URI is a lot stricter than KURL so we have to undo
2959 // KURL's percent-encoding and redo the encoding using java.net.URI.
2960 URI uri = null;
2961 try {
2962 // Undo the percent-encoding that KURL may have done.
2963 String newUrl = new String(URLUtil.decode(url.getBytes()));
2964 // Parse the url into pieces
2965 WebAddress w = new WebAddress(newUrl);
2966 String frag = null;
2967 String query = null;
2968 String path = w.mPath;
2969 // Break the path into path, query, and fragment
2970 if (path.length() > 0) {
2971 // Strip the fragment
2972 int idx = path.lastIndexOf('#');
2973 if (idx != -1) {
2974 frag = path.substring(idx + 1);
2975 path = path.substring(0, idx);
2976 }
2977 idx = path.lastIndexOf('?');
2978 if (idx != -1) {
2979 query = path.substring(idx + 1);
2980 path = path.substring(0, idx);
2981 }
2982 }
2983 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2984 query, frag);
2985 } catch (Exception e) {
2986 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2987 return;
2988 }
2989
2990 // XXX: Have to use the old url since the cookies were stored using the
2991 // old percent-encoded url.
2992 String cookies = CookieManager.getInstance().getCookie(url);
2993
2994 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002995 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2996 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2997 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2998 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002999 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003000 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003001 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003002 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3003 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3004 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3005 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3006 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003007 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003008 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003009 }
3010 if (mimetype == null) {
3011 // We must have long pressed on a link or image to download it. We
3012 // are not sure of the mimetype in this case, so do a head request
3013 new FetchUrlMimeType(this).execute(values);
3014 } else {
3015 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003016 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 }
3018
3019 }
3020
Grace Kloba22ac16e2009-10-07 18:00:23 -07003021 // -------------------------------------------------------------------------
3022
The Android Open Source Project0c908882009-03-03 19:32:16 -08003023 /**
3024 * Resets the lock icon. This method is called when we start a new load and
3025 * know the url to be loaded.
3026 */
3027 private void resetLockIcon(String url) {
3028 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003029 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 updateLockIconImage(LOCK_ICON_UNSECURE);
3031 }
3032
The Android Open Source Project0c908882009-03-03 19:32:16 -08003033 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003034 * Update the lock icon to correspond to our latest state.
3035 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003036 private void updateLockIconToLatest() {
3037 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003038 }
3039
3040 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003041 * Updates the lock-icon image in the title-bar.
3042 */
3043 private void updateLockIconImage(int lockIconType) {
3044 Drawable d = null;
3045 if (lockIconType == LOCK_ICON_SECURE) {
3046 d = mSecLockIcon;
3047 } else if (lockIconType == LOCK_ICON_MIXED) {
3048 d = mMixLockIcon;
3049 }
Leon Scroggins68579392009-09-15 15:31:54 -04003050 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003051 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 }
3053
3054 /**
3055 * Displays a page-info dialog.
3056 * @param tab The tab to show info about
3057 * @param fromShowSSLCertificateOnError The flag that indicates whether
3058 * this dialog was opened from the SSL-certificate-on-error dialog or
3059 * not. This is important, since we need to know whether to return to
3060 * the parent dialog or simply dismiss.
3061 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003062 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003063 final boolean fromShowSSLCertificateOnError) {
3064 final LayoutInflater factory = LayoutInflater
3065 .from(this);
3066
3067 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3068
3069 final WebView view = tab.getWebView();
3070
3071 String url = null;
3072 String title = null;
3073
3074 if (view == null) {
3075 url = tab.getUrl();
3076 title = tab.getTitle();
3077 } else if (view == mTabControl.getCurrentWebView()) {
3078 // Use the cached title and url if this is the current WebView
3079 url = mUrl;
3080 title = mTitle;
3081 } else {
3082 url = view.getUrl();
3083 title = view.getTitle();
3084 }
3085
3086 if (url == null) {
3087 url = "";
3088 }
3089 if (title == null) {
3090 title = "";
3091 }
3092
3093 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3094 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3095
3096 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003097 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003098
3099 AlertDialog.Builder alertDialogBuilder =
3100 new AlertDialog.Builder(this)
3101 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3102 .setView(pageInfoView)
3103 .setPositiveButton(
3104 R.string.ok,
3105 new DialogInterface.OnClickListener() {
3106 public void onClick(DialogInterface dialog,
3107 int whichButton) {
3108 mPageInfoDialog = null;
3109 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003110
3111 // if we came here from the SSL error dialog
3112 if (fromShowSSLCertificateOnError) {
3113 // go back to the SSL error dialog
3114 showSSLCertificateOnError(
3115 mSSLCertificateOnErrorView,
3116 mSSLCertificateOnErrorHandler,
3117 mSSLCertificateOnErrorError);
3118 }
3119 }
3120 })
3121 .setOnCancelListener(
3122 new DialogInterface.OnCancelListener() {
3123 public void onCancel(DialogInterface dialog) {
3124 mPageInfoDialog = null;
3125 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003126
3127 // if we came here from the SSL error dialog
3128 if (fromShowSSLCertificateOnError) {
3129 // go back to the SSL error dialog
3130 showSSLCertificateOnError(
3131 mSSLCertificateOnErrorView,
3132 mSSLCertificateOnErrorHandler,
3133 mSSLCertificateOnErrorError);
3134 }
3135 }
3136 });
3137
3138 // if we have a main top-level page SSL certificate set or a certificate
3139 // error
3140 if (fromShowSSLCertificateOnError ||
3141 (view != null && view.getCertificate() != null)) {
3142 // add a 'View Certificate' button
3143 alertDialogBuilder.setNeutralButton(
3144 R.string.view_certificate,
3145 new DialogInterface.OnClickListener() {
3146 public void onClick(DialogInterface dialog,
3147 int whichButton) {
3148 mPageInfoDialog = null;
3149 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003150
3151 // if we came here from the SSL error dialog
3152 if (fromShowSSLCertificateOnError) {
3153 // go back to the SSL error dialog
3154 showSSLCertificateOnError(
3155 mSSLCertificateOnErrorView,
3156 mSSLCertificateOnErrorHandler,
3157 mSSLCertificateOnErrorError);
3158 } else {
3159 // otherwise, display the top-most certificate from
3160 // the chain
3161 if (view.getCertificate() != null) {
3162 showSSLCertificate(tab);
3163 }
3164 }
3165 }
3166 });
3167 }
3168
3169 mPageInfoDialog = alertDialogBuilder.show();
3170 }
3171
3172 /**
3173 * Displays the main top-level page SSL certificate dialog
3174 * (accessible from the Page-Info dialog).
3175 * @param tab The tab to show certificate for.
3176 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003177 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003178 final View certificateView =
3179 inflateCertificateView(tab.getWebView().getCertificate());
3180 if (certificateView == null) {
3181 return;
3182 }
3183
3184 LayoutInflater factory = LayoutInflater.from(this);
3185
3186 final LinearLayout placeholder =
3187 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3188
3189 LinearLayout ll = (LinearLayout) factory.inflate(
3190 R.layout.ssl_success, placeholder);
3191 ((TextView)ll.findViewById(R.id.success))
3192 .setText(R.string.ssl_certificate_is_valid);
3193
3194 mSSLCertificateView = tab;
3195 mSSLCertificateDialog =
3196 new AlertDialog.Builder(this)
3197 .setTitle(R.string.ssl_certificate).setIcon(
3198 R.drawable.ic_dialog_browser_certificate_secure)
3199 .setView(certificateView)
3200 .setPositiveButton(R.string.ok,
3201 new DialogInterface.OnClickListener() {
3202 public void onClick(DialogInterface dialog,
3203 int whichButton) {
3204 mSSLCertificateDialog = null;
3205 mSSLCertificateView = null;
3206
3207 showPageInfo(tab, false);
3208 }
3209 })
3210 .setOnCancelListener(
3211 new DialogInterface.OnCancelListener() {
3212 public void onCancel(DialogInterface dialog) {
3213 mSSLCertificateDialog = null;
3214 mSSLCertificateView = null;
3215
3216 showPageInfo(tab, false);
3217 }
3218 })
3219 .show();
3220 }
3221
3222 /**
3223 * Displays the SSL error certificate dialog.
3224 * @param view The target web-view.
3225 * @param handler The SSL error handler responsible for cancelling the
3226 * connection that resulted in an SSL error or proceeding per user request.
3227 * @param error The SSL error object.
3228 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003229 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003230 final WebView view, final SslErrorHandler handler, final SslError error) {
3231
3232 final View certificateView =
3233 inflateCertificateView(error.getCertificate());
3234 if (certificateView == null) {
3235 return;
3236 }
3237
3238 LayoutInflater factory = LayoutInflater.from(this);
3239
3240 final LinearLayout placeholder =
3241 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3242
3243 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3244 LinearLayout ll = (LinearLayout)factory
3245 .inflate(R.layout.ssl_warning, placeholder);
3246 ((TextView)ll.findViewById(R.id.warning))
3247 .setText(R.string.ssl_untrusted);
3248 }
3249
3250 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3251 LinearLayout ll = (LinearLayout)factory
3252 .inflate(R.layout.ssl_warning, placeholder);
3253 ((TextView)ll.findViewById(R.id.warning))
3254 .setText(R.string.ssl_mismatch);
3255 }
3256
3257 if (error.hasError(SslError.SSL_EXPIRED)) {
3258 LinearLayout ll = (LinearLayout)factory
3259 .inflate(R.layout.ssl_warning, placeholder);
3260 ((TextView)ll.findViewById(R.id.warning))
3261 .setText(R.string.ssl_expired);
3262 }
3263
3264 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3265 LinearLayout ll = (LinearLayout)factory
3266 .inflate(R.layout.ssl_warning, placeholder);
3267 ((TextView)ll.findViewById(R.id.warning))
3268 .setText(R.string.ssl_not_yet_valid);
3269 }
3270
3271 mSSLCertificateOnErrorHandler = handler;
3272 mSSLCertificateOnErrorView = view;
3273 mSSLCertificateOnErrorError = error;
3274 mSSLCertificateOnErrorDialog =
3275 new AlertDialog.Builder(this)
3276 .setTitle(R.string.ssl_certificate).setIcon(
3277 R.drawable.ic_dialog_browser_certificate_partially_secure)
3278 .setView(certificateView)
3279 .setPositiveButton(R.string.ok,
3280 new DialogInterface.OnClickListener() {
3281 public void onClick(DialogInterface dialog,
3282 int whichButton) {
3283 mSSLCertificateOnErrorDialog = null;
3284 mSSLCertificateOnErrorView = null;
3285 mSSLCertificateOnErrorHandler = null;
3286 mSSLCertificateOnErrorError = null;
3287
Grace Kloba22ac16e2009-10-07 18:00:23 -07003288 view.getWebViewClient().onReceivedSslError(
3289 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003290 }
3291 })
3292 .setNeutralButton(R.string.page_info_view,
3293 new DialogInterface.OnClickListener() {
3294 public void onClick(DialogInterface dialog,
3295 int whichButton) {
3296 mSSLCertificateOnErrorDialog = null;
3297
3298 // do not clear the dialog state: we will
3299 // need to show the dialog again once the
3300 // user is done exploring the page-info details
3301
3302 showPageInfo(mTabControl.getTabFromView(view),
3303 true);
3304 }
3305 })
3306 .setOnCancelListener(
3307 new DialogInterface.OnCancelListener() {
3308 public void onCancel(DialogInterface dialog) {
3309 mSSLCertificateOnErrorDialog = null;
3310 mSSLCertificateOnErrorView = null;
3311 mSSLCertificateOnErrorHandler = null;
3312 mSSLCertificateOnErrorError = null;
3313
Grace Kloba22ac16e2009-10-07 18:00:23 -07003314 view.getWebViewClient().onReceivedSslError(
3315 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003316 }
3317 })
3318 .show();
3319 }
3320
3321 /**
3322 * Inflates the SSL certificate view (helper method).
3323 * @param certificate The SSL certificate.
3324 * @return The resultant certificate view with issued-to, issued-by,
3325 * issued-on, expires-on, and possibly other fields set.
3326 * If the input certificate is null, returns null.
3327 */
3328 private View inflateCertificateView(SslCertificate certificate) {
3329 if (certificate == null) {
3330 return null;
3331 }
3332
3333 LayoutInflater factory = LayoutInflater.from(this);
3334
3335 View certificateView = factory.inflate(
3336 R.layout.ssl_certificate, null);
3337
3338 // issued to:
3339 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3340 if (issuedTo != null) {
3341 ((TextView) certificateView.findViewById(R.id.to_common))
3342 .setText(issuedTo.getCName());
3343 ((TextView) certificateView.findViewById(R.id.to_org))
3344 .setText(issuedTo.getOName());
3345 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3346 .setText(issuedTo.getUName());
3347 }
3348
3349 // issued by:
3350 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3351 if (issuedBy != null) {
3352 ((TextView) certificateView.findViewById(R.id.by_common))
3353 .setText(issuedBy.getCName());
3354 ((TextView) certificateView.findViewById(R.id.by_org))
3355 .setText(issuedBy.getOName());
3356 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3357 .setText(issuedBy.getUName());
3358 }
3359
3360 // issued on:
3361 String issuedOn = reformatCertificateDate(
3362 certificate.getValidNotBefore());
3363 ((TextView) certificateView.findViewById(R.id.issued_on))
3364 .setText(issuedOn);
3365
3366 // expires on:
3367 String expiresOn = reformatCertificateDate(
3368 certificate.getValidNotAfter());
3369 ((TextView) certificateView.findViewById(R.id.expires_on))
3370 .setText(expiresOn);
3371
3372 return certificateView;
3373 }
3374
3375 /**
3376 * Re-formats the certificate date (Date.toString()) string to
3377 * a properly localized date string.
3378 * @return Properly localized version of the certificate date string and
3379 * the original certificate date string if fails to localize.
3380 * If the original string is null, returns an empty string "".
3381 */
3382 private String reformatCertificateDate(String certificateDate) {
3383 String reformattedDate = null;
3384
3385 if (certificateDate != null) {
3386 Date date = null;
3387 try {
3388 date = java.text.DateFormat.getInstance().parse(certificateDate);
3389 } catch (ParseException e) {
3390 date = null;
3391 }
3392
3393 if (date != null) {
3394 reformattedDate =
3395 DateFormat.getDateFormat(this).format(date);
3396 }
3397 }
3398
3399 return reformattedDate != null ? reformattedDate :
3400 (certificateDate != null ? certificateDate : "");
3401 }
3402
3403 /**
3404 * Displays an http-authentication dialog.
3405 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003406 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003407 final String host, final String realm, final String title,
3408 final String name, final String password, int focusId) {
3409 LayoutInflater factory = LayoutInflater.from(this);
3410 final View v = factory
3411 .inflate(R.layout.http_authentication, null);
3412 if (name != null) {
3413 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3414 }
3415 if (password != null) {
3416 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3417 }
3418
3419 String titleText = title;
3420 if (titleText == null) {
3421 titleText = getText(R.string.sign_in_to).toString().replace(
3422 "%s1", host).replace("%s2", realm);
3423 }
3424
3425 mHttpAuthHandler = handler;
3426 AlertDialog dialog = new AlertDialog.Builder(this)
3427 .setTitle(titleText)
3428 .setIcon(android.R.drawable.ic_dialog_alert)
3429 .setView(v)
3430 .setPositiveButton(R.string.action,
3431 new DialogInterface.OnClickListener() {
3432 public void onClick(DialogInterface dialog,
3433 int whichButton) {
3434 String nm = ((EditText) v
3435 .findViewById(R.id.username_edit))
3436 .getText().toString();
3437 String pw = ((EditText) v
3438 .findViewById(R.id.password_edit))
3439 .getText().toString();
3440 BrowserActivity.this.setHttpAuthUsernamePassword
3441 (host, realm, nm, pw);
3442 handler.proceed(nm, pw);
3443 mHttpAuthenticationDialog = null;
3444 mHttpAuthHandler = null;
3445 }})
3446 .setNegativeButton(R.string.cancel,
3447 new DialogInterface.OnClickListener() {
3448 public void onClick(DialogInterface dialog,
3449 int whichButton) {
3450 handler.cancel();
3451 BrowserActivity.this.resetTitleAndRevertLockIcon();
3452 mHttpAuthenticationDialog = null;
3453 mHttpAuthHandler = null;
3454 }})
3455 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3456 public void onCancel(DialogInterface dialog) {
3457 handler.cancel();
3458 BrowserActivity.this.resetTitleAndRevertLockIcon();
3459 mHttpAuthenticationDialog = null;
3460 mHttpAuthHandler = null;
3461 }})
3462 .create();
3463 // Make the IME appear when the dialog is displayed if applicable.
3464 dialog.getWindow().setSoftInputMode(
3465 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3466 dialog.show();
3467 if (focusId != 0) {
3468 dialog.findViewById(focusId).requestFocus();
3469 } else {
3470 v.findViewById(R.id.username_edit).requestFocus();
3471 }
3472 mHttpAuthenticationDialog = dialog;
3473 }
3474
3475 public int getProgress() {
3476 WebView w = mTabControl.getCurrentWebView();
3477 if (w != null) {
3478 return w.getProgress();
3479 } else {
3480 return 100;
3481 }
3482 }
3483
3484 /**
3485 * Set HTTP authentication password.
3486 *
3487 * @param host The host for the password
3488 * @param realm The realm for the password
3489 * @param username The username for the password. If it is null, it means
3490 * password can't be saved.
3491 * @param password The password
3492 */
3493 public void setHttpAuthUsernamePassword(String host, String realm,
3494 String username,
3495 String password) {
3496 WebView w = mTabControl.getCurrentWebView();
3497 if (w != null) {
3498 w.setHttpAuthUsernamePassword(host, realm, username, password);
3499 }
3500 }
3501
3502 /**
3503 * connectivity manager says net has come or gone... inform the user
3504 * @param up true if net has come up, false if net has gone down
3505 */
3506 public void onNetworkToggle(boolean up) {
3507 if (up == mIsNetworkUp) {
3508 return;
3509 } else if (up) {
3510 mIsNetworkUp = true;
3511 if (mAlertDialog != null) {
3512 mAlertDialog.cancel();
3513 mAlertDialog = null;
3514 }
3515 } else {
3516 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003517 if (mInLoad) {
3518 createAndShowNetworkDialog();
3519 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 }
3521 WebView w = mTabControl.getCurrentWebView();
3522 if (w != null) {
3523 w.setNetworkAvailable(up);
3524 }
3525 }
3526
Grace Kloba22ac16e2009-10-07 18:00:23 -07003527 boolean isNetworkUp() {
3528 return mIsNetworkUp;
3529 }
3530
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003531 // This method shows the network dialog alerting the user that the net is
3532 // down. It will only show the dialog if mAlertDialog is null.
3533 private void createAndShowNetworkDialog() {
3534 if (mAlertDialog == null) {
3535 mAlertDialog = new AlertDialog.Builder(this)
3536 .setTitle(R.string.loadSuspendedTitle)
3537 .setMessage(R.string.loadSuspended)
3538 .setPositiveButton(R.string.ok, null)
3539 .show();
3540 }
3541 }
3542
The Android Open Source Project0c908882009-03-03 19:32:16 -08003543 @Override
3544 protected void onActivityResult(int requestCode, int resultCode,
3545 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003546 if (getTopWindow() == null) return;
3547
The Android Open Source Project0c908882009-03-03 19:32:16 -08003548 switch (requestCode) {
3549 case COMBO_PAGE:
3550 if (resultCode == RESULT_OK && intent != null) {
3551 String data = intent.getAction();
3552 Bundle extras = intent.getExtras();
3553 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003554 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003555 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003556 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003558 dismissSubWindow(currentTab);
3559 if (data != null && data.length() != 0) {
3560 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003561 }
3562 }
3563 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003564 // Deliberately fall through to PREFERENCES_PAGE, since the
3565 // same extra may be attached to the COMBO_PAGE
3566 case PREFERENCES_PAGE:
3567 if (resultCode == RESULT_OK && intent != null) {
3568 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3569 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3570 mTabControl.removeParentChildRelationShips();
3571 }
3572 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003573 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003574 // Choose a file from the file picker.
3575 case FILE_SELECTED:
3576 if (null == mUploadMessage) break;
3577 Uri result = intent == null || resultCode != RESULT_OK ? null
3578 : intent.getData();
3579 mUploadMessage.onReceiveValue(result);
3580 mUploadMessage = null;
3581 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 default:
3583 break;
3584 }
Leon Scroggins30444232009-09-04 18:36:20 -04003585 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003586 }
3587
3588 /*
3589 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003590 * menu to see the download window. It shows the download window on top of
3591 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003593 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003594 Intent intent = new Intent(this,
3595 BrowserDownloadPage.class);
3596 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003597 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003598
3599 }
3600
Leon Scroggins160a7e72009-08-14 18:28:01 -04003601 /**
3602 * Open the Go page.
3603 * @param startWithHistory If true, open starting on the history tab.
3604 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003605 */
Leon Scroggins30444232009-09-04 18:36:20 -04003606 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 WebView current = mTabControl.getCurrentWebView();
3608 if (current == null) {
3609 return;
3610 }
3611 Intent intent = new Intent(this,
3612 CombinedBookmarkHistoryActivity.class);
3613 String title = current.getTitle();
3614 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003615 Bitmap thumbnail = createScreenshot(current);
3616
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 // Just in case the user opens bookmarks before a page finishes loading
3618 // so the current history item, and therefore the page, is null.
3619 if (null == url) {
3620 url = mLastEnteredUrl;
3621 // This can happen.
3622 if (null == url) {
3623 url = mSettings.getHomePage();
3624 }
3625 }
3626 // In case the web page has not yet received its associated title.
3627 if (title == null) {
3628 title = url;
3629 }
3630 intent.putExtra("title", title);
3631 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003632 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003633 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003634 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003635 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 if (startWithHistory) {
3637 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3638 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3639 }
3640 startActivityForResult(intent, COMBO_PAGE);
3641 }
3642
3643 // Called when loading from context menu or LOAD_URL message
3644 private void loadURL(WebView view, String url) {
3645 // In case the user enters nothing.
3646 if (url != null && url.length() != 0 && view != null) {
3647 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003648 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 view.loadUrl(url);
3650 }
3651 }
3652 }
3653
The Android Open Source Project0c908882009-03-03 19:32:16 -08003654 private String smartUrlFilter(Uri inUri) {
3655 if (inUri != null) {
3656 return smartUrlFilter(inUri.toString());
3657 }
3658 return null;
3659 }
3660
Feng Qianb34f87a2009-03-24 21:27:26 -07003661 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003662 "(?i)" + // switch on case insensitive matching
3663 "(" + // begin group for schema
3664 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003665 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003666 ")" +
3667 "(.*)" );
3668
3669 /**
3670 * Attempts to determine whether user input is a URL or search
3671 * terms. Anything with a space is passed to search.
3672 *
3673 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3674 * "Http://" converts to "http://"
3675 *
3676 * @return Original or modified URL
3677 *
3678 */
3679 String smartUrlFilter(String url) {
3680
3681 String inUrl = url.trim();
3682 boolean hasSpace = inUrl.indexOf(' ') != -1;
3683
3684 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3685 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003686 // force scheme to lowercase
3687 String scheme = matcher.group(1);
3688 String lcScheme = scheme.toLowerCase();
3689 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003690 inUrl = lcScheme + matcher.group(2);
3691 }
3692 if (hasSpace) {
3693 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003694 }
3695 return inUrl;
3696 }
3697 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003698 // FIXME: Is this the correct place to add to searches?
3699 // what if someone else calls this function?
3700 int shortcut = parseUrlShortcut(inUrl);
3701 if (shortcut != SHORTCUT_INVALID) {
3702 Browser.addSearchUrl(mResolver, inUrl);
3703 String query = inUrl.substring(2);
3704 switch (shortcut) {
3705 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003706 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003707 case SHORTCUT_WIKIPEDIA_SEARCH:
3708 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3709 case SHORTCUT_DICTIONARY_SEARCH:
3710 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3711 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003713 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003714 }
3715 }
3716 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003717 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003718 return URLUtil.guessUrl(inUrl);
3719 }
3720 }
3721
3722 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003723 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724 }
3725
Ben Murdochbff2d602009-07-01 20:19:05 +01003726 /* package */ void setShouldShowErrorConsole(boolean flag) {
3727 if (flag == mShouldShowErrorConsole) {
3728 // Nothing to do.
3729 return;
3730 }
3731
3732 mShouldShowErrorConsole = flag;
3733
Grace Kloba22ac16e2009-10-07 18:00:23 -07003734 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3735 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003736
3737 if (flag) {
3738 // Setting the show state of the console will cause it's the layout to be inflated.
3739 if (errorConsole.numberOfErrors() > 0) {
3740 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3741 } else {
3742 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3743 }
3744
3745 // Now we can add it to the main view.
3746 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003747 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003748 ViewGroup.LayoutParams.WRAP_CONTENT));
3749 } else {
3750 mErrorConsoleContainer.removeView(errorConsole);
3751 }
3752
3753 }
3754
Grace Kloba22ac16e2009-10-07 18:00:23 -07003755 boolean shouldShowErrorConsole() {
3756 return mShouldShowErrorConsole;
3757 }
3758
Andrei Popescu163ab742009-10-20 17:58:23 +01003759 private void setStatusBarVisibility(boolean visible) {
3760 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3761 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3762 }
3763
Andrei Popescu56199cc2010-01-12 22:39:16 +00003764
3765 private void sendNetworkType(String type, String subtype) {
3766 WebView w = mTabControl.getCurrentWebView();
3767 if (w != null) {
3768 w.setNetworkType(type, subtype);
3769 }
3770 }
3771
Grace Klobaeb6eef42009-09-15 17:56:32 -07003772 final static int LOCK_ICON_UNSECURE = 0;
3773 final static int LOCK_ICON_SECURE = 1;
3774 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775
The Android Open Source Project0c908882009-03-03 19:32:16 -08003776 private BrowserSettings mSettings;
3777 private TabControl mTabControl;
3778 private ContentResolver mResolver;
3779 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003780 private View mCustomView;
3781 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003782 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003783
3784 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3785 // view, we should rewrite this.
3786 private int mCurrentMenuState = 0;
3787 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003788 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003789 private static final int EMPTY_MENU = -1;
3790 private Menu mMenu;
3791
3792 private FindDialog mFindDialog;
3793 // Used to prevent chording to result in firing two shortcuts immediately
3794 // one after another. Fixes bug 1211714.
3795 boolean mCanChord;
3796
3797 private boolean mInLoad;
3798 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003799 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003800
The Android Open Source Project0c908882009-03-03 19:32:16 -08003801 private boolean mActivityInPause = true;
3802
3803 private boolean mMenuIsDown;
3804
The Android Open Source Project0c908882009-03-03 19:32:16 -08003805 private static boolean mInTrace;
3806
3807 // Performance probe
3808 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3809 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3810 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3811 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3812 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3813 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3814 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3815 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3816 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3817 };
3818
3819 private long mStart;
3820 private long mProcessStart;
3821 private long mUserStart;
3822 private long mSystemStart;
3823 private long mIdleStart;
3824 private long mIrqStart;
3825
3826 private long mUiStart;
3827
3828 private Drawable mMixLockIcon;
3829 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830
3831 /* hold a ref so we can auto-cancel if necessary */
3832 private AlertDialog mAlertDialog;
3833
3834 // Wait for credentials before loading google.com
3835 private ProgressDialog mCredsDlg;
3836
3837 // The up-to-date URL and title (these can be different from those stored
3838 // in WebView, since it takes some time for the information in WebView to
3839 // get updated)
3840 private String mUrl;
3841 private String mTitle;
3842
3843 // As PageInfo has different style for landscape / portrait, we have
3844 // to re-open it when configuration changed
3845 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003846 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003847 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3848 // dialog, we should not just dismiss it, but should get back to the
3849 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003850 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003851
3852 // as SSLCertificateOnError has different style for landscape / portrait,
3853 // we have to re-open it when configuration changed
3854 private AlertDialog mSSLCertificateOnErrorDialog;
3855 private WebView mSSLCertificateOnErrorView;
3856 private SslErrorHandler mSSLCertificateOnErrorHandler;
3857 private SslError mSSLCertificateOnErrorError;
3858
3859 // as SSLCertificate has different style for landscape / portrait, we
3860 // have to re-open it when configuration changed
3861 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003862 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003863
3864 // as HttpAuthentication has different style for landscape / portrait, we
3865 // have to re-open it when configuration changed
3866 private AlertDialog mHttpAuthenticationDialog;
3867 private HttpAuthHandler mHttpAuthHandler;
3868
3869 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3870 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003871 ViewGroup.LayoutParams.MATCH_PARENT,
3872 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003873 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3874 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003875 ViewGroup.LayoutParams.MATCH_PARENT,
3876 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003877 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003878 // Google search
3879 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003880 // Wikipedia search
3881 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3882 // Dictionary search
3883 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3884 // Google Mobile Local search
3885 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3886
3887 final static String QUERY_PLACE_HOLDER = "%s";
3888
3889 // "source" parameter for Google search through search key
3890 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3891 // "source" parameter for Google search through goto menu
3892 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3893 // "source" parameter for Google search through simplily type
3894 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3895 // "source" parameter for Google search suggested by the browser
3896 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3897 // "source" parameter for Google search from unknown source
3898 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3899
3900 private final static String LOGTAG = "browser";
3901
The Android Open Source Project0c908882009-03-03 19:32:16 -08003902 private String mLastEnteredUrl;
3903
3904 private PowerManager.WakeLock mWakeLock;
3905 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3906
3907 private Toast mStopToast;
3908
Leon Scroggins68579392009-09-15 15:31:54 -04003909 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003910
Ben Murdochbff2d602009-07-01 20:19:05 +01003911 private LinearLayout mErrorConsoleContainer = null;
3912 private boolean mShouldShowErrorConsole = false;
3913
The Android Open Source Project0c908882009-03-03 19:32:16 -08003914 // As the ids are dynamically created, we can't guarantee that they will
3915 // be in sequence, so this static array maps ids to a window number.
3916 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3917 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3918 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3919 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3920
3921 // monitor platform changes
3922 private IntentFilter mNetworkStateChangedFilter;
3923 private BroadcastReceiver mNetworkStateIntentReceiver;
3924
Grace Klobab4da0ad2009-05-14 14:45:40 -07003925 private BroadcastReceiver mPackageInstallationReceiver;
3926
The Android Open Source Project0c908882009-03-03 19:32:16 -08003927 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003928 final static int COMBO_PAGE = 1;
3929 final static int DOWNLOAD_PAGE = 2;
3930 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003931 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003932
Andrei Popescu540035d2009-09-18 18:59:20 +01003933 // the default <video> poster
3934 private Bitmap mDefaultVideoPoster;
3935 // the video progress view
3936 private View mVideoProgressView;
3937
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003938 /**
3939 * A UrlData class to abstract how the content will be set to WebView.
3940 * This base class uses loadUrl to show the content.
3941 */
3942 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003943 final String mUrl;
3944 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003945 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003946
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003947 UrlData(String url) {
3948 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003949 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003950 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003951 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003952
Leon Scroggins58d56c62010-01-28 15:12:40 -05003953 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003954 this.mUrl = url;
3955 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003956 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3957 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003958 this.mVoiceIntent = intent;
3959 } else {
3960 this.mVoiceIntent = null;
3961 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003962 }
3963
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003964 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003965 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003966 }
3967
Leon Scroggins58d56c62010-01-28 15:12:40 -05003968 public void loadIn(Tab t) {
3969 if (mVoiceIntent != null) {
3970 t.activateVoiceSearchMode(mVoiceIntent);
3971 } else {
3972 t.getWebView().loadUrl(mUrl, mHeaders);
3973 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003974 }
3975 };
3976
Leon Scroggins1f005d32009-08-10 17:36:42 -04003977 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003978}