blob: 3f7c9e98535030aee28493744d6d61d945ac7f3d [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;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.text.IClipboard;
71import android.text.TextUtils;
72import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040073import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080074import android.util.Log;
75import android.view.ContextMenu;
76import android.view.Gravity;
77import android.view.KeyEvent;
78import android.view.LayoutInflater;
79import android.view.Menu;
80import android.view.MenuInflater;
81import android.view.MenuItem;
82import android.view.View;
83import android.view.ViewGroup;
84import android.view.Window;
85import android.view.WindowManager;
86import android.view.ContextMenu.ContextMenuInfo;
87import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080088import android.webkit.CookieManager;
89import android.webkit.CookieSyncManager;
90import android.webkit.DownloadListener;
91import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070092import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080093import android.webkit.SslErrorHandler;
94import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010095import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.webkit.WebChromeClient;
97import android.webkit.WebHistoryItem;
98import android.webkit.WebIconDatabase;
99import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800100import android.widget.EditText;
101import android.widget.FrameLayout;
102import android.widget.LinearLayout;
103import android.widget.TextView;
104import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800105import android.accounts.Account;
106import android.accounts.AccountManager;
107import android.accounts.AccountManagerFuture;
108import android.accounts.AuthenticatorException;
109import android.accounts.OperationCanceledException;
110import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800111
Dan Egnor5ee906c2009-11-18 12:11:49 -0800112import com.android.common.Patterns;
113
Doug Zongker716d4f52010-01-21 14:35:23 -0800114import com.google.android.gsf.GoogleLoginServiceConstants;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800115
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400116import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800117import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000118import java.io.IOException;
119import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800120import java.net.MalformedURLException;
121import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700122import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.net.URL;
124import java.net.URLEncoder;
125import java.text.ParseException;
126import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800127import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800128import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800129import java.util.Map;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130import java.util.regex.Matcher;
131import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132
133public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800134 implements View.OnCreateContextMenuListener, DownloadListener,
135 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800136
Dave Bort31a6d1c2009-04-13 15:56:49 -0700137 /* Define some aliases to make these debugging flags easier to refer to.
138 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
139 */
140 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
141 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
142 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
143
Satish Sampath565505b2009-05-29 15:37:27 +0100144 // These are single-character shortcuts for searching popular sources.
145 private static final int SHORTCUT_INVALID = 0;
146 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
147 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
148 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
149 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
150
Fred Quintana752b6562009-12-18 10:18:26 -0800151 private Account[] mAccountsGoogle;
152 private Account[] mAccountsPreferHosted;
153
154 private void startReadOfGoogleAccounts() {
155 mAccountsGoogle = null;
156 mAccountsPreferHosted = null;
157
158 AccountManager.get(this).getAccountsByTypeAndFeatures(
159 GoogleLoginServiceConstants.ACCOUNT_TYPE,
160 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
161 this, null);
162 }
163
164 /** This implements AccountManagerCallback<Account[]> */
165 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
166 try {
167 if (mAccountsGoogle == null) {
168 mAccountsGoogle = accountManagerFuture.getResult();
169
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
171 GoogleLoginServiceConstants.ACCOUNT_TYPE,
172 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
173 this, null);
174 } else {
175 mAccountsPreferHosted = accountManagerFuture.getResult();
176 setupHomePage();
177 }
178 } catch (OperationCanceledException e) {
179 setupHomePage();
180 } catch (IOException e) {
181 setupHomePage();
182 } catch (AuthenticatorException e) {
183 setupHomePage();
184 }
185 }
186
The Android Open Source Project0c908882009-03-03 19:32:16 -0800187 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800188 // get the default home page
189 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190
Fred Quintana752b6562009-12-18 10:18:26 -0800191 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
192 // three cases:
193 //
194 // hostedUser == googleUser
195 // The device has only a google account
196 //
197 // hostedUser != googleUser
198 // The device has a hosted account and a google account
199 //
200 // hostedUser != null, googleUser == null
201 // The device has only a hosted account (so far)
202 String hostedUser = mAccountsPreferHosted.length == 0
203 ? null
204 : mAccountsPreferHosted[0].name;
205 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800206
Fred Quintana752b6562009-12-18 10:18:26 -0800207 // developers might have no accounts at all
208 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700209
Fred Quintana752b6562009-12-18 10:18:26 -0800210 if (googleUser == null || !hostedUser.equals(googleUser)) {
211 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
212 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800213 }
Fred Quintana752b6562009-12-18 10:18:26 -0800214 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800215
Fred Quintana752b6562009-12-18 10:18:26 -0800216 mSettings.setHomePage(BrowserActivity.this, homepage);
217 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800218 }
219
Cary Clarka9771242009-08-11 16:42:26 -0400220 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800221 @Override
222 public Void doInBackground(File... files) {
223 if (files != null) {
224 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400225 if (!f.delete()) {
226 Log.e(LOGTAG, f.getPath() + " was not deleted");
227 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800228 }
229 }
230 return null;
231 }
232 }
233
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400234 /**
235 * This layout holds everything you see below the status bar, including the
236 * error console, the custom view container, and the webviews.
237 */
238 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400239
Grace Kloba22ac16e2009-10-07 18:00:23 -0700240 @Override
241 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700242 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800243 Log.v(LOGTAG, this + " onStart");
244 }
245 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800246 // test the browser in OpenGL
247 // requestWindowFeature(Window.FEATURE_OPENGL);
248
Mike Reedd334bf52010-01-26 15:21:44 -0500249 // enable this to test the browser in 32bit
250 if (false) {
251 getWindow().setFormat(PixelFormat.RGBX_8888);
252 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
253 }
254
The Android Open Source Project0c908882009-03-03 19:32:16 -0800255 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
256
257 mResolver = getContentResolver();
258
Grace Kloba0923d692009-09-23 21:37:25 -0700259 // If this was a web search request, pass it on to the default web
260 // search provider and finish this activity.
261 if (handleWebSearchIntent(getIntent())) {
262 finish();
263 return;
264 }
265
The Android Open Source Project0c908882009-03-03 19:32:16 -0800266 mSecLockIcon = Resources.getSystem().getDrawable(
267 android.R.drawable.ic_secure);
268 mMixLockIcon = Resources.getSystem().getDrawable(
269 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800270
Leon Scroggins81db3662009-06-04 17:45:11 -0400271 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
272 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400273 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
274 .inflate(R.layout.custom_screen, null);
275 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
276 R.id.main_content);
277 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
278 .findViewById(R.id.error_console);
279 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
280 .findViewById(R.id.fullscreen_custom_content);
281 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400282 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400283 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800284
285 // Create the tab control and our initial tab
286 mTabControl = new TabControl(this);
287
288 // Open the icon database and retain all the bookmark urls for favicons
289 retainIconsOnStartup();
290
291 // Keep a settings instance handy.
292 mSettings = BrowserSettings.getInstance();
293 mSettings.setTabControl(mTabControl);
294 mSettings.loadFromDb(this);
295
296 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
297 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
298
Grace Klobaa34f6862009-07-31 16:28:17 -0700299 /* enables registration for changes in network status from
300 http stack */
301 mNetworkStateChangedFilter = new IntentFilter();
302 mNetworkStateChangedFilter.addAction(
303 ConnectivityManager.CONNECTIVITY_ACTION);
304 mNetworkStateIntentReceiver = new BroadcastReceiver() {
305 @Override
306 public void onReceive(Context context, Intent intent) {
307 if (intent.getAction().equals(
308 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700309 boolean noConnectivity = intent.getBooleanExtra(
310 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000311 if (!noConnectivity) {
312 NetworkInfo info = intent.getParcelableExtra(
313 ConnectivityManager.EXTRA_NETWORK_INFO);
314 String typeName = info.getTypeName();
315 String subtypeName = info.getSubtypeName();
316 sendNetworkType(typeName.toLowerCase(),
317 (subtypeName != null ? subtypeName.toLowerCase() : ""));
318 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700319 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700320 }
321 }
322 };
323
Grace Kloba615c6c92009-08-03 10:22:44 -0700324 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
325 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
326 filter.addDataScheme("package");
327 mPackageInstallationReceiver = new BroadcastReceiver() {
328 @Override
329 public void onReceive(Context context, Intent intent) {
330 final String action = intent.getAction();
331 final String packageName = intent.getData()
332 .getSchemeSpecificPart();
333 final boolean replacing = intent.getBooleanExtra(
334 Intent.EXTRA_REPLACING, false);
335 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
336 // if it is replacing, refreshPlugins() when adding
337 return;
338 }
339 PackageManager pm = BrowserActivity.this.getPackageManager();
340 PackageInfo pkgInfo = null;
341 try {
342 pkgInfo = pm.getPackageInfo(packageName,
343 PackageManager.GET_PERMISSIONS);
344 } catch (PackageManager.NameNotFoundException e) {
345 return;
346 }
347 if (pkgInfo != null) {
348 String permissions[] = pkgInfo.requestedPermissions;
349 if (permissions == null) {
350 return;
351 }
352 boolean permissionOk = false;
353 for (String permit : permissions) {
354 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
355 permissionOk = true;
356 break;
357 }
358 }
359 if (permissionOk) {
360 PluginManager.getInstance(BrowserActivity.this)
361 .refreshPlugins(
362 Intent.ACTION_PACKAGE_ADDED
363 .equals(action));
364 }
365 }
366 }
367 };
368 registerReceiver(mPackageInstallationReceiver, filter);
369
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 if (!mTabControl.restoreState(icicle)) {
371 // clear up the thumbnail directory if we can't restore the state as
372 // none of the files in the directory are referenced any more.
373 new ClearThumbnails().execute(
374 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700375 // there is no quit on Android. But if we can't restore the state,
376 // we can treat it as a new Browser, remove the old session cookies.
377 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800378 final Intent intent = getIntent();
379 final Bundle extra = intent.getExtras();
380 // Create an initial tab.
381 // If the intent is ACTION_VIEW and data is not null, the Browser is
382 // invoked to view the content by another application. In this case,
383 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700384 UrlData urlData = getUrlDataFromIntent(intent);
385
Leon Scroggins58d56c62010-01-28 15:12:40 -0500386 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700387 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500388 (Intent.ACTION_VIEW.equals(action) &&
389 intent.getData() != null)
390 || Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700391 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800392 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800393 attachTabToContentView(t);
394 WebView webView = t.getWebView();
395 if (extra != null) {
396 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
397 if (scale > 0 && scale <= 1000) {
398 webView.setInitialScale(scale);
399 }
400 }
401 // If we are not restoring from an icicle, then there is a high
402 // likely hood this is the first run. So, check to see if the
403 // homepage needs to be configured and copy any plugins from our
404 // asset directory to the data partition.
405 if ((extra == null || !extra.getBoolean("testing"))
406 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800407 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800408 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800409
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700410 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400411 if (mSettings.isLoginInitialized()) {
412 webView.loadUrl(mSettings.getHomePage());
413 } else {
414 waitForCredentials();
415 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 } else {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500417 urlData.loadIn(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 }
419 } else {
420 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400421 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 attachTabToContentView(mTabControl.getCurrentTab());
423 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700424
Feng Qianb3c02da2009-06-29 15:58:08 -0700425 // Read JavaScript flags if it exists.
426 String jsFlags = mSettings.getJsFlags();
427 if (jsFlags.trim().length() != 0) {
428 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
429 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800430 }
431
Leon Scroggins58d56c62010-01-28 15:12:40 -0500432 /**
433 * Feed the previously stored results strings to the BrowserProvider so that
434 * the SearchDialog will show them instead of the standard searches.
435 * @param result String to show on the editable line of the SearchDialog.
436 */
437 /* package */ void showVoiceSearchResults(String result) {
438 ContentProviderClient client = mResolver.acquireContentProviderClient(
439 Browser.BOOKMARKS_URI);
440 ContentProvider prov = client.getLocalContentProvider();
441 BrowserProvider bp = (BrowserProvider) prov;
442 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
443 client.release();
444
445 startSearch(result, false,
446 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
447 false);
448 }
449
The Android Open Source Project0c908882009-03-03 19:32:16 -0800450 @Override
451 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700452 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800453 // When a tab is closed on exit, the current tab index is set to -1.
454 // Reset before proceed as Browser requires the current tab to be set.
455 if (current == null) {
456 // Try to reset the tab in case the index was incorrect.
457 current = mTabControl.getTab(0);
458 if (current == null) {
459 // No tabs at all so just ignore this intent.
460 return;
461 }
462 mTabControl.setCurrentTab(current);
463 attachTabToContentView(current);
464 resetTitleAndIcon(current.getWebView());
465 }
466 final String action = intent.getAction();
467 final int flags = intent.getFlags();
468 if (Intent.ACTION_MAIN.equals(action) ||
469 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
470 // just resume the browser
471 return;
472 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500473 boolean activateVoiceSearch = Tab.VoiceSearchData.VOICE_SEARCH_RESULTS
474 .equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800475 if (Intent.ACTION_VIEW.equals(action)
476 || Intent.ACTION_SEARCH.equals(action)
477 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500478 || Intent.ACTION_WEB_SEARCH.equals(action)
479 || activateVoiceSearch) {
Satish Sampath565505b2009-05-29 15:37:27 +0100480 // If this was a search request (e.g. search query directly typed into the address bar),
481 // pass it on to the default web search provider.
482 if (handleWebSearchIntent(intent)) {
483 return;
484 }
485
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700486 UrlData urlData = getUrlDataFromIntent(intent);
487 if (urlData.isEmpty()) {
488 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800489 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700490
Grace Klobacc634032009-07-28 15:58:19 -0700491 final String appId = intent
492 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500493 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700494 && !getPackageName().equals(appId)
495 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700496 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700497 if (appTab != null) {
498 Log.i(LOGTAG, "Reusing tab for " + appId);
499 // Dismiss the subwindow if applicable.
500 dismissSubWindow(appTab);
501 // Since we might kill the WebView, remove it from the
502 // content view first.
503 removeTabFromContentView(appTab);
504 // Recreate the main WebView after destroying the old one.
505 // If the WebView has the same original url and is on that
506 // page, it can be reused.
507 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700508 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100509
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700510 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400511 switchToTab(mTabControl.getTabIndex(appTab));
512 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500513 urlData.loadIn(appTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400516 // If the tab was the current tab, we have to attach
517 // it to the view system again.
518 attachTabToContentView(appTab);
519 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500520 urlData.loadIn(appTab);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 }
522 }
523 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400524 } else {
525 // No matching application tab, try to find a regular tab
526 // with a matching url.
527 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400528 if (appTab != null) {
529 if (current != appTab) {
530 switchToTab(mTabControl.getTabIndex(appTab));
531 }
532 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400533 } else {
534 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
535 // will be opened in a new tab unless we have reached
536 // MAX_TABS. Then the url will be opened in the current
537 // tab. If a new tab is created, it will have "true" for
538 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400539 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400540 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700541 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800542 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800543 if (!urlData.isEmpty()
544 && urlData.mUrl.startsWith("about:debug")) {
545 if ("about:debug.dom".equals(urlData.mUrl)) {
546 current.getWebView().dumpDomTree(false);
547 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(true);
549 } else if ("about:debug.render".equals(urlData.mUrl)) {
550 current.getWebView().dumpRenderTree(false);
551 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(true);
553 } else if ("about:debug.display".equals(urlData.mUrl)) {
554 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800555 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
556 int index = urlData.mUrl.codePointAt(16) - '0';
557 if (index <= 0 || index > 9) {
558 current.getWebView().setDragTracker(null);
559 } else {
560 current.getWebView().setDragTracker(new MeshTracker(index));
561 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800562 } else {
563 mSettings.toggleDebugSettings();
564 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800565 return;
566 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400567 // Get rid of the subwindow if it exists
568 dismissSubWindow(current);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500569 urlData.loadIn(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800570 }
571 }
572 }
573
Satish Sampath565505b2009-05-29 15:37:27 +0100574 private int parseUrlShortcut(String url) {
575 if (url == null) return SHORTCUT_INVALID;
576
577 // FIXME: quick search, need to be customized by setting
578 if (url.length() > 2 && url.charAt(1) == ' ') {
579 switch (url.charAt(0)) {
580 case 'g': return SHORTCUT_GOOGLE_SEARCH;
581 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
582 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
583 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
584 }
585 }
586 return SHORTCUT_INVALID;
587 }
588
589 /**
590 * Launches the default web search activity with the query parameters if the given intent's data
591 * are identified as plain search terms and not URLs/shortcuts.
592 * @return true if the intent was handled and web search activity was launched, false if not.
593 */
594 private boolean handleWebSearchIntent(Intent intent) {
595 if (intent == null) return false;
596
597 String url = null;
598 final String action = intent.getAction();
Leon Scroggins58d56c62010-01-28 15:12:40 -0500599 if (Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(action)) {
600 return false;
601 }
Satish Sampath565505b2009-05-29 15:37:27 +0100602 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700603 Uri data = intent.getData();
604 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100605 } else if (Intent.ACTION_SEARCH.equals(action)
606 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
607 || Intent.ACTION_WEB_SEARCH.equals(action)) {
608 url = intent.getStringExtra(SearchManager.QUERY);
609 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100610 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
611 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100612 }
613
614 /**
615 * Launches the default web search activity with the query parameters if the given url string
616 * was identified as plain search terms and not URL/shortcut.
617 * @return true if the request was handled and web search activity was launched, false if not.
618 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100619 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100620 if (inUrl == null) return false;
621
622 // In general, we shouldn't modify URL from Intent.
623 // But currently, we get the user-typed URL from search box as well.
624 String url = fixUrl(inUrl).trim();
625
626 // URLs and site specific search shortcuts are handled by the regular flow of control, so
627 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800628 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100629 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100630 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
631 return false;
632 }
633
634 Browser.updateVisitedHistory(mResolver, url, false);
635 Browser.addSearchUrl(mResolver, url);
636
637 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
638 intent.addCategory(Intent.CATEGORY_DEFAULT);
639 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100640 if (appData != null) {
641 intent.putExtra(SearchManager.APP_DATA, appData);
642 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100643 if (extraData != null) {
644 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
645 }
Grace Klobacc634032009-07-28 15:58:19 -0700646 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100647 startActivity(intent);
648
649 return true;
650 }
651
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700652 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500653 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800654 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800655 if (intent != null) {
656 final String action = intent.getAction();
657 if (Intent.ACTION_VIEW.equals(action)) {
658 url = smartUrlFilter(intent.getData());
659 if (url != null && url.startsWith("content:")) {
660 /* Append mimetype so webview knows how to display */
661 String mimeType = intent.resolveType(getContentResolver());
662 if (mimeType != null) {
663 url += "?" + mimeType;
664 }
665 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800666 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800667 final Bundle pairs = intent
668 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800669 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800670 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800671 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800672 while (iter.hasNext()) {
673 String key = iter.next();
674 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800675 }
676 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800678 } else if (Intent.ACTION_SEARCH.equals(action)
679 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
680 || Intent.ACTION_WEB_SEARCH.equals(action)) {
681 url = intent.getStringExtra(SearchManager.QUERY);
682 if (url != null) {
683 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500684 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800685 // In general, we shouldn't modify URL from Intent.
686 // But currently, we get the user-typed URL from search box as well.
687 url = fixUrl(url);
688 url = smartUrlFilter(url);
689 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
690 if (url.contains(searchSource)) {
691 String source = null;
692 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
693 if (appData != null) {
694 source = appData.getString(SearchManager.SOURCE);
695 }
696 if (TextUtils.isEmpty(source)) {
697 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
698 }
699 url = url.replace(searchSource, "&source=android-"+source+"&");
700 }
701 }
702 }
703 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500706 /* package */ void showVoiceTitleBar(String title) {
707 mTitleBar.setInVoiceMode(true);
708 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800709
Leon Scroggins58d56c62010-01-28 15:12:40 -0500710 mTitleBar.setDisplayTitle(title);
711 mFakeTitleBar.setDisplayTitle(title);
712 }
713 /* package */ void revertVoiceTitleBar() {
714 mTitleBar.setInVoiceMode(false);
715 mFakeTitleBar.setInVoiceMode(false);
716
717 mTitleBar.setDisplayTitle(mTitle);
718 mFakeTitleBar.setDisplayTitle(mTitle);
719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400721 // FIXME: Converting the url to lower case
722 // duplicates functionality in smartUrlFilter().
723 // However, changing all current callers of fixUrl to
724 // call smartUrlFilter in addition may have unwanted
725 // consequences, and is deferred for now.
726 int colon = inUrl.indexOf(':');
727 boolean allLower = true;
728 for (int index = 0; index < colon; index++) {
729 char ch = inUrl.charAt(index);
730 if (!Character.isLetter(ch)) {
731 break;
732 }
733 allLower &= Character.isLowerCase(ch);
734 if (index == colon - 1 && !allLower) {
735 inUrl = inUrl.substring(0, colon).toLowerCase()
736 + inUrl.substring(colon);
737 }
738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
740 return inUrl;
741 if (inUrl.startsWith("http:") ||
742 inUrl.startsWith("https:")) {
743 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
744 inUrl = inUrl.replaceFirst("/", "//");
745 } else inUrl = inUrl.replaceFirst(":", "://");
746 }
747 return inUrl;
748 }
749
Grace Kloba22ac16e2009-10-07 18:00:23 -0700750 @Override
751 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800752 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700753 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800754 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
755 }
756
757 if (!mActivityInPause) {
758 Log.e(LOGTAG, "BrowserActivity is already resumed.");
759 return;
760 }
761
Mike Reed7bfa63b2009-05-28 11:08:32 -0400762 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800763 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400764 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800765
766 if (mWakeLock.isHeld()) {
767 mHandler.removeMessages(RELEASE_WAKELOCK);
768 mWakeLock.release();
769 }
770
771 if (mCredsDlg != null) {
772 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
773 // In case credential request never comes back
774 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
775 }
776 }
777
778 registerReceiver(mNetworkStateIntentReceiver,
779 mNetworkStateChangedFilter);
780 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800781 }
782
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400783 /**
784 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400785 * would change its appearance, use a different TitleBar to show overlayed
786 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400787 */
788 private TitleBar mFakeTitleBar;
789
790 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400791 * Holder for the fake title bar. It will have a foreground shadow, as well
792 * as a white background, so the fake title bar looks like the real one.
793 */
794 private ViewGroup mFakeTitleBarHolder;
795
796 /**
797 * Layout parameters for the fake title bar within mFakeTitleBarHolder
798 */
799 private FrameLayout.LayoutParams mFakeTitleBarParams
800 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800801 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400802 ViewGroup.LayoutParams.WRAP_CONTENT);
803 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400804 * Keeps track of whether the options menu is open. This is important in
805 * determining whether to show or hide the title bar overlay.
806 */
807 private boolean mOptionsMenuOpen;
808
809 /**
810 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
811 * of whether the configuration has changed. The first onMenuOpened call
812 * after a configuration change is simply a reopening of the same menu
813 * (i.e. mIconView did not change).
814 */
815 private boolean mConfigChanged;
816
817 /**
818 * Whether or not the options menu is in its smaller, icon menu form. When
819 * true, we want the title bar overlay to be up. When false, we do not.
820 * Only meaningful if mOptionsMenuOpen is true.
821 */
822 private boolean mIconView;
823
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400824 @Override
825 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400826 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
827 if (mOptionsMenuOpen) {
828 if (mConfigChanged) {
829 // We do not need to make any changes to the state of the
830 // title bar, since the only thing that happened was a
831 // change in orientation
832 mConfigChanged = false;
833 } else {
834 if (mIconView) {
835 // Switching the menu to expanded view, so hide the
836 // title bar.
837 hideFakeTitleBar();
838 mIconView = false;
839 } else {
840 // Switching the menu back to icon view, so show the
841 // title bar once again.
842 showFakeTitleBar();
843 mIconView = true;
844 }
845 }
846 } else {
847 // The options menu is closed, so open it, and show the title
848 showFakeTitleBar();
849 mOptionsMenuOpen = true;
850 mConfigChanged = false;
851 mIconView = true;
852 }
853 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400854 return true;
855 }
856
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400857 /**
858 * Special class used exclusively for the shadow drawn underneath the fake
859 * title bar. The shadow does not need to be drawn if the WebView
860 * underneath is scrolled to the top, because it will draw directly on top
861 * of the embedded shadow.
862 */
863 private static class Shadow extends View {
864 private WebView mWebView;
865
866 public Shadow(Context context, AttributeSet attrs) {
867 super(context, attrs);
868 }
869
870 public void setWebView(WebView view) {
871 mWebView = view;
872 }
873
874 @Override
875 public void draw(Canvas canvas) {
876 // In general onDraw is the method to override, but we care about
877 // whether or not the background gets drawn, which happens in draw()
878 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
879 super.draw(canvas);
880 }
881 // Need to invalidate so that if the scroll position changes, we
882 // still draw as appropriate.
883 invalidate();
884 }
885 }
886
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400887 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400888 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400889 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400890 && !mActivityInPause && decor != null
891 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400892 Rect visRect = new Rect();
893 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
894 if (LOGD_ENABLED) {
895 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
896 }
897 return;
898 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899
900 WindowManager manager
901 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
902
903 // Add the title bar to the window manager so it can receive touches
904 // while the menu is up
905 WindowManager.LayoutParams params
906 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800907 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400908 ViewGroup.LayoutParams.WRAP_CONTENT,
909 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
910 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400911 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400912 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400913 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400914 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400915 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400916 // XXX : Without providing an offset, the fake title bar will be
917 // placed underneath the status bar. Use the global visible rect
918 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400919 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400920 // Add a holder for the title bar. It also holds a shadow to show
921 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400922 if (mFakeTitleBarHolder == null) {
923 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
924 .inflate(R.layout.title_bar_bg, null);
925 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400926 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
927 R.id.shadow);
928 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400929 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400930 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400931 }
932 }
933
934 @Override
935 public void onOptionsMenuClosed(Menu menu) {
936 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400937 if (!mInLoad) {
938 hideFakeTitleBar();
939 } else if (!mIconView) {
940 // The page is currently loading, and we are in expanded mode, so
941 // we were not showing the menu. Show it once again. It will be
942 // removed when the page finishes.
943 showFakeTitleBar();
944 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400945 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400947 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400948 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400949 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
950 mFakeTitleBarHolder.getLayoutParams();
951 WebView mainView = mTabControl.getCurrentWebView();
952 // Although we decided whether or not to animate based on the current
953 // scroll position, the scroll position may have changed since the
954 // fake title bar was displayed. Make sure it has the appropriate
955 // animation/lack thereof before removing.
956 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400957 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400958 WindowManager manager
959 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400960 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400961 mFakeTitleBarHolder.removeView(mFakeTitleBar);
962 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400963 }
964
The Android Open Source Project0c908882009-03-03 19:32:16 -0800965 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400966 * Special method for the fake title bar to call when displaying its context
967 * menu, since it is in its own Window, and its parent does not show a
968 * context menu.
969 */
970 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400971 if (null == mTitleBar.getParent()) {
972 return;
973 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400974 openContextMenu(mTitleBar);
975 }
976
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400977 @Override
978 public void onContextMenuClosed(Menu menu) {
979 super.onContextMenuClosed(menu);
980 if (mInLoad) {
981 showFakeTitleBar();
982 }
983 }
984
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400985 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800986 * onSaveInstanceState(Bundle map)
987 * onSaveInstanceState is called right before onStop(). The map contains
988 * the saved state.
989 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700990 @Override
991 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700992 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
994 }
995 // the default implementation requires each view to have an id. As the
996 // browser handles the state itself and it doesn't use id for the views,
997 // don't call the default implementation. Otherwise it will trigger the
998 // warning like this, "couldn't save which view has focus because the
999 // focused view XXX has no id".
1000
1001 // Save all the tabs
1002 mTabControl.saveState(outState);
1003 }
1004
Grace Kloba22ac16e2009-10-07 18:00:23 -07001005 @Override
1006 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 super.onPause();
1008
1009 if (mActivityInPause) {
1010 Log.e(LOGTAG, "BrowserActivity is already paused.");
1011 return;
1012 }
1013
Mike Reed7bfa63b2009-05-28 11:08:32 -04001014 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001015 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001016 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 mWakeLock.acquire();
1018 mHandler.sendMessageDelayed(mHandler
1019 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1020 }
1021
1022 // Clear the credentials toast if it is up
1023 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1024 mCredsDlg.dismiss();
1025 }
1026 mCredsDlg = null;
1027
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001028 // FIXME: This removes the active tabs page and resets the menu to
1029 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1030 // but then we would need to save it in onSaveInstanceState and restore
1031 // it in onCreate/onRestoreInstanceState
1032 if (mActiveTabsPage != null) {
1033 removeActiveTabPage(true);
1034 }
1035
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 cancelStopToast();
1037
1038 // unregister network state listener
1039 unregisterReceiver(mNetworkStateIntentReceiver);
1040 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042
Grace Kloba22ac16e2009-10-07 18:00:23 -07001043 @Override
1044 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001045 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001046 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1047 }
1048 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001049
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001050 if (mUploadMessage != null) {
1051 mUploadMessage.onReceiveValue(null);
1052 mUploadMessage = null;
1053 }
1054
Grace Kloba0923d692009-09-23 21:37:25 -07001055 if (mTabControl == null) return;
1056
Grace Kloba1fc98a32009-10-21 13:23:08 -07001057 // Remove the fake title bar if it is there
1058 hideFakeTitleBar();
1059
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001061 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001062 if (t != null) {
1063 dismissSubWindow(t);
1064 removeTabFromContentView(t);
1065 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001066 // Destroy all the tabs
1067 mTabControl.destroy();
1068 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001069
Grace Klobab4da0ad2009-05-14 14:45:40 -07001070 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 }
1072
1073 @Override
1074 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001075 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001076 super.onConfigurationChanged(newConfig);
1077
1078 if (mPageInfoDialog != null) {
1079 mPageInfoDialog.dismiss();
1080 showPageInfo(
1081 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001082 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 }
1084 if (mSSLCertificateDialog != null) {
1085 mSSLCertificateDialog.dismiss();
1086 showSSLCertificate(
1087 mSSLCertificateView);
1088 }
1089 if (mSSLCertificateOnErrorDialog != null) {
1090 mSSLCertificateOnErrorDialog.dismiss();
1091 showSSLCertificateOnError(
1092 mSSLCertificateOnErrorView,
1093 mSSLCertificateOnErrorHandler,
1094 mSSLCertificateOnErrorError);
1095 }
1096 if (mHttpAuthenticationDialog != null) {
1097 String title = ((TextView) mHttpAuthenticationDialog
1098 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1099 .toString();
1100 String name = ((TextView) mHttpAuthenticationDialog
1101 .findViewById(R.id.username_edit)).getText().toString();
1102 String password = ((TextView) mHttpAuthenticationDialog
1103 .findViewById(R.id.password_edit)).getText().toString();
1104 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1105 .getId();
1106 mHttpAuthenticationDialog.dismiss();
1107 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1108 name, password, focusId);
1109 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001110 }
1111
Grace Kloba22ac16e2009-10-07 18:00:23 -07001112 @Override
1113 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001114 super.onLowMemory();
1115 mTabControl.freeMemory();
1116 }
1117
Mike Reed7bfa63b2009-05-28 11:08:32 -04001118 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001119 Tab tab = mTabControl.getCurrentTab();
1120 boolean inLoad = tab.inLoad();
1121 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001123 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 if (w != null) {
1125 w.resumeTimers();
1126 }
1127 return true;
1128 } else {
1129 return false;
1130 }
1131 }
1132
Mike Reed7bfa63b2009-05-28 11:08:32 -04001133 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001134 Tab tab = mTabControl.getCurrentTab();
1135 boolean inLoad = tab.inLoad();
1136 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001137 CookieSyncManager.getInstance().stopSync();
1138 WebView w = mTabControl.getCurrentWebView();
1139 if (w != null) {
1140 w.pauseTimers();
1141 }
1142 return true;
1143 } else {
1144 return false;
1145 }
1146 }
1147
Leon Scroggins1f005d32009-08-10 17:36:42 -04001148 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001149 /*
1150 * This function is called when we are launching for the first time. We
1151 * are waiting for the login credentials before loading Google home
1152 * pages. This way the user will be logged in straight away.
1153 */
1154 private void waitForCredentials() {
1155 // Show a toast
1156 mCredsDlg = new ProgressDialog(this);
1157 mCredsDlg.setIndeterminate(true);
1158 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1159 // If the user cancels the operation, then cancel the Google
1160 // Credentials request.
1161 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1162 mCredsDlg.show();
1163
1164 // We set a timeout for the retrieval of credentials in onResume()
1165 // as that is when we have freed up some CPU time to get
1166 // the login credentials.
1167 }
1168
1169 /*
1170 * If we have received the credentials or we have timed out and we are
1171 * showing the credentials dialog, then it is time to move on.
1172 */
1173 private void resumeAfterCredentials() {
1174 if (mCredsDlg == null) {
1175 return;
1176 }
1177
1178 // Clear the toast
1179 if (mCredsDlg.isShowing()) {
1180 mCredsDlg.dismiss();
1181 }
1182 mCredsDlg = null;
1183
1184 // Clear any pending timeout
1185 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1186
1187 // Load the page
1188 WebView w = mTabControl.getCurrentWebView();
1189 if (w != null) {
1190 w.loadUrl(mSettings.getHomePage());
1191 }
1192
1193 // Update the settings, need to do this last as it can take a moment
1194 // to persist the settings. In the mean time we could be loading
1195 // content.
1196 mSettings.setLoginInitialized(this);
1197 }
1198
1199 // Open the icon database and retain all the icons for visited sites.
1200 private void retainIconsOnStartup() {
1201 final WebIconDatabase db = WebIconDatabase.getInstance();
1202 db.open(getDir("icons", 0).getPath());
1203 try {
1204 Cursor c = Browser.getAllBookmarks(mResolver);
1205 if (!c.moveToFirst()) {
1206 c.deactivate();
1207 return;
1208 }
1209 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1210 do {
1211 String url = c.getString(urlIndex);
1212 db.retainIconForPageUrl(url);
1213 } while (c.moveToNext());
1214 c.deactivate();
1215 } catch (IllegalStateException e) {
1216 Log.e(LOGTAG, "retainIconsOnStartup", e);
1217 }
1218 }
1219
1220 // Helper method for getting the top window.
1221 WebView getTopWindow() {
1222 return mTabControl.getCurrentTopWebView();
1223 }
1224
Grace Kloba22ac16e2009-10-07 18:00:23 -07001225 TabControl getTabControl() {
1226 return mTabControl;
1227 }
1228
The Android Open Source Project0c908882009-03-03 19:32:16 -08001229 @Override
1230 public boolean onCreateOptionsMenu(Menu menu) {
1231 super.onCreateOptionsMenu(menu);
1232
1233 MenuInflater inflater = getMenuInflater();
1234 inflater.inflate(R.menu.browser, menu);
1235 mMenu = menu;
1236 updateInLoadMenuItems();
1237 return true;
1238 }
1239
1240 /**
1241 * As the menu can be open when loading state changes
1242 * we must manually update the state of the stop/reload menu
1243 * item
1244 */
1245 private void updateInLoadMenuItems() {
1246 if (mMenu == null) {
1247 return;
1248 }
1249 MenuItem src = mInLoad ?
1250 mMenu.findItem(R.id.stop_menu_id):
1251 mMenu.findItem(R.id.reload_menu_id);
1252 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1253 dest.setIcon(src.getIcon());
1254 dest.setTitle(src.getTitle());
1255 }
1256
1257 @Override
1258 public boolean onContextItemSelected(MenuItem item) {
1259 // chording is not an issue with context menus, but we use the same
1260 // options selector, so set mCanChord to true so we can access them.
1261 mCanChord = true;
1262 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001263 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001264 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001265 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001266 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001267 Tab currentTab = mTabControl.getCurrentTab();
1268 if (null == currentTab) {
1269 result = false;
1270 break;
1271 }
1272 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001273 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001274 result = false;
1275 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001276 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001277 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001278 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001279 // -- Browser context menu
1280 case R.id.open_context_menu_id:
1281 case R.id.open_newtab_context_menu_id:
1282 case R.id.bookmark_context_menu_id:
1283 case R.id.save_link_context_menu_id:
1284 case R.id.share_link_context_menu_id:
1285 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001286 final WebView webView = getTopWindow();
1287 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001288 result = false;
1289 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001290 }
1291 final HashMap hrefMap = new HashMap();
1292 hrefMap.put("webview", webView);
1293 final Message msg = mHandler.obtainMessage(
1294 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001295 webView.requestFocusNodeHref(msg);
1296 break;
1297
1298 default:
1299 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001300 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001301 }
1302 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001303 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001304 }
1305
1306 private Bundle createGoogleSearchSourceBundle(String source) {
1307 Bundle bundle = new Bundle();
1308 bundle.putString(SearchManager.SOURCE, source);
1309 return bundle;
1310 }
1311
1312 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001313 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001314 */
1315 @Override
1316 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001317 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001318 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001319 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001320 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001321 return true;
1322 }
1323
1324 @Override
1325 public void startSearch(String initialQuery, boolean selectInitialQuery,
1326 Bundle appSearchData, boolean globalSearch) {
1327 if (appSearchData == null) {
1328 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1329 }
1330 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1331 }
1332
Leon Scroggins1f005d32009-08-10 17:36:42 -04001333 /**
1334 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1335 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001336 * @param index Index of the tab to change to, as defined by
1337 * mTabControl.getTabIndex(Tab t).
1338 * @return boolean True if we successfully switched to a different tab. If
1339 * the indexth tab is null, or if that tab is the same as
1340 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001342 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001343 Tab tab = mTabControl.getTab(index);
1344 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001345 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001346 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001347 }
1348 if (currentTab != null) {
1349 // currentTab may be null if it was just removed. In that case,
1350 // we do not need to remove it
1351 removeTabFromContentView(currentTab);
1352 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 mTabControl.setCurrentTab(tab);
1354 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001355 resetTitleIconAndProgress();
1356 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001357 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001358 }
1359
Grace Kloba22ac16e2009-10-07 18:00:23 -07001360 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001361 return openTabAndShow(mSettings.getHomePage(), false, null);
1362 }
1363
Leon Scroggins1f005d32009-08-10 17:36:42 -04001364 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001365 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001366 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001367 // This is the last tab. Open a new one, with the home
1368 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001369 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001370 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001371 return;
1372 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001373 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001374 int indexToShow = -1;
1375 if (parent != null) {
1376 indexToShow = mTabControl.getTabIndex(parent);
1377 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001378 final int currentIndex = mTabControl.getCurrentIndex();
1379 // Try to move to the tab to the right
1380 indexToShow = currentIndex + 1;
1381 if (indexToShow > mTabControl.getTabCount() - 1) {
1382 // Try to move to the tab to the left
1383 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001384 }
1385 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001386 if (switchToTab(indexToShow)) {
1387 // Close window
1388 closeTab(current);
1389 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001390 }
1391
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001392 private ActiveTabsPage mActiveTabsPage;
1393
1394 /**
1395 * Remove the active tabs page.
1396 * @param needToAttach If true, the active tabs page did not attach a tab
1397 * to the content view, so we need to do that here.
1398 */
1399 /* package */ void removeActiveTabPage(boolean needToAttach) {
1400 mContentView.removeView(mActiveTabsPage);
1401 mActiveTabsPage = null;
1402 mMenuState = R.id.MAIN_MENU;
1403 if (needToAttach) {
1404 attachTabToContentView(mTabControl.getCurrentTab());
1405 }
1406 getTopWindow().requestFocus();
1407 }
1408
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 @Override
1410 public boolean onOptionsItemSelected(MenuItem item) {
1411 if (!mCanChord) {
1412 // The user has already fired a shortcut with this hold down of the
1413 // menu key.
1414 return false;
1415 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001416 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001417 return false;
1418 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001419 if (mMenuIsDown) {
1420 // The shortcut action consumes the MENU. Even if it is still down,
1421 // it won't trigger the next shortcut action. In the case of the
1422 // shortcut action triggering a new activity, like Bookmarks, we
1423 // won't get onKeyUp for MENU. So it is important to reset it here.
1424 mMenuIsDown = false;
1425 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001426 switch (item.getItemId()) {
1427 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001428 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001429 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001430 break;
1431
Leon Scroggins64b80f32009-08-07 12:03:34 -04001432 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001433 onSearchRequested();
1434 break;
1435
1436 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001437 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 break;
1439
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001440 case R.id.active_tabs_menu_id:
1441 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1442 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001443 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001444 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1445 mActiveTabsPage.requestFocus();
1446 mMenuState = EMPTY_MENU;
1447 break;
1448
Leon Scroggins1f005d32009-08-10 17:36:42 -04001449 case R.id.add_bookmark_menu_id:
1450 Intent i = new Intent(BrowserActivity.this,
1451 AddBookmarkPage.class);
1452 WebView w = getTopWindow();
1453 i.putExtra("url", w.getUrl());
1454 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001455 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001456 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001457 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 break;
1459
1460 case R.id.stop_reload_menu_id:
1461 if (mInLoad) {
1462 stopLoading();
1463 } else {
1464 getTopWindow().reload();
1465 }
1466 break;
1467
1468 case R.id.back_menu_id:
1469 getTopWindow().goBack();
1470 break;
1471
1472 case R.id.forward_menu_id:
1473 getTopWindow().goForward();
1474 break;
1475
1476 case R.id.close_menu_id:
1477 // Close the subwindow if it exists.
1478 if (mTabControl.getCurrentSubWindow() != null) {
1479 dismissSubWindow(mTabControl.getCurrentTab());
1480 break;
1481 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001482 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 break;
1484
1485 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001486 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001487 if (current != null) {
1488 dismissSubWindow(current);
1489 current.getWebView().loadUrl(mSettings.getHomePage());
1490 }
1491 break;
1492
1493 case R.id.preferences_menu_id:
1494 Intent intent = new Intent(this,
1495 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001496 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1497 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001498 startActivityForResult(intent, PREFERENCES_PAGE);
1499 break;
1500
1501 case R.id.find_menu_id:
1502 if (null == mFindDialog) {
1503 mFindDialog = new FindDialog(this);
1504 }
1505 mFindDialog.setWebView(getTopWindow());
1506 mFindDialog.show();
1507 mMenuState = EMPTY_MENU;
1508 break;
1509
1510 case R.id.select_text_id:
1511 getTopWindow().emulateShiftHeld();
1512 break;
1513 case R.id.page_info_menu_id:
1514 showPageInfo(mTabControl.getCurrentTab(), false);
1515 break;
1516
1517 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001518 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001519 break;
1520
Leon Scroggins96afcb12009-12-10 12:35:56 -05001521 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001522 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001523 Tab currentTab = mTabControl.getCurrentTab();
1524 if (null == currentTab) {
1525 mCanChord = false;
1526 return false;
1527 }
1528 currentTab.populatePickerData();
1529 sharePage(this, currentTab.getTitle(),
1530 currentTab.getUrl(), currentTab.getFavicon(),
1531 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 break;
1533
1534 case R.id.dump_nav_menu_id:
1535 getTopWindow().debugDump();
1536 break;
1537
1538 case R.id.zoom_in_menu_id:
1539 getTopWindow().zoomIn();
1540 break;
1541
1542 case R.id.zoom_out_menu_id:
1543 getTopWindow().zoomOut();
1544 break;
1545
1546 case R.id.view_downloads_menu_id:
1547 viewDownloads(null);
1548 break;
1549
The Android Open Source Project0c908882009-03-03 19:32:16 -08001550 case R.id.window_one_menu_id:
1551 case R.id.window_two_menu_id:
1552 case R.id.window_three_menu_id:
1553 case R.id.window_four_menu_id:
1554 case R.id.window_five_menu_id:
1555 case R.id.window_six_menu_id:
1556 case R.id.window_seven_menu_id:
1557 case R.id.window_eight_menu_id:
1558 {
1559 int menuid = item.getItemId();
1560 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1561 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001562 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001563 if (desiredTab != null &&
1564 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001565 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 }
1567 break;
1568 }
1569 }
1570 }
1571 break;
1572
1573 default:
1574 if (!super.onOptionsItemSelected(item)) {
1575 return false;
1576 }
1577 // Otherwise fall through.
1578 }
1579 mCanChord = false;
1580 return true;
1581 }
1582
1583 public void closeFind() {
1584 mMenuState = R.id.MAIN_MENU;
1585 }
1586
Grace Kloba22ac16e2009-10-07 18:00:23 -07001587 @Override
1588 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001589 // This happens when the user begins to hold down the menu key, so
1590 // allow them to chord to get a shortcut.
1591 mCanChord = true;
1592 // Note: setVisible will decide whether an item is visible; while
1593 // setEnabled() will decide whether an item is enabled, which also means
1594 // whether the matching shortcut key will function.
1595 super.onPrepareOptionsMenu(menu);
1596 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001597 case EMPTY_MENU:
1598 if (mCurrentMenuState != mMenuState) {
1599 menu.setGroupVisible(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1601 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001602 }
1603 break;
1604 default:
1605 if (mCurrentMenuState != mMenuState) {
1606 menu.setGroupVisible(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1608 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001609 }
1610 final WebView w = getTopWindow();
1611 boolean canGoBack = false;
1612 boolean canGoForward = false;
1613 boolean isHome = false;
1614 if (w != null) {
1615 canGoBack = w.canGoBack();
1616 canGoForward = w.canGoForward();
1617 isHome = mSettings.getHomePage().equals(w.getUrl());
1618 }
1619 final MenuItem back = menu.findItem(R.id.back_menu_id);
1620 back.setEnabled(canGoBack);
1621
1622 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1623 home.setEnabled(!isHome);
1624
1625 menu.findItem(R.id.forward_menu_id)
1626 .setEnabled(canGoForward);
1627
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001628 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001629 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001630
The Android Open Source Project0c908882009-03-03 19:32:16 -08001631 // decide whether to show the share link option
1632 PackageManager pm = getPackageManager();
1633 Intent send = new Intent(Intent.ACTION_SEND);
1634 send.setType("text/plain");
1635 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1636 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1637
The Android Open Source Project0c908882009-03-03 19:32:16 -08001638 boolean isNavDump = mSettings.isNavDump();
1639 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1640 nav.setVisible(isNavDump);
1641 nav.setEnabled(isNavDump);
1642 break;
1643 }
1644 mCurrentMenuState = mMenuState;
1645 return true;
1646 }
1647
1648 @Override
1649 public void onCreateContextMenu(ContextMenu menu, View v,
1650 ContextMenuInfo menuInfo) {
1651 WebView webview = (WebView) v;
1652 WebView.HitTestResult result = webview.getHitTestResult();
1653 if (result == null) {
1654 return;
1655 }
1656
1657 int type = result.getType();
1658 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1659 Log.w(LOGTAG,
1660 "We should not show context menu when nothing is touched");
1661 return;
1662 }
1663 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1664 // let TextView handles context menu
1665 return;
1666 }
1667
1668 // Note, http://b/issue?id=1106666 is requesting that
1669 // an inflated menu can be used again. This is not available
1670 // yet, so inflate each time (yuk!)
1671 MenuInflater inflater = getMenuInflater();
1672 inflater.inflate(R.menu.browsercontext, menu);
1673
1674 // Show the correct menu group
1675 String extra = result.getExtra();
1676 menu.setGroupVisible(R.id.PHONE_MENU,
1677 type == WebView.HitTestResult.PHONE_TYPE);
1678 menu.setGroupVisible(R.id.EMAIL_MENU,
1679 type == WebView.HitTestResult.EMAIL_TYPE);
1680 menu.setGroupVisible(R.id.GEO_MENU,
1681 type == WebView.HitTestResult.GEO_TYPE);
1682 menu.setGroupVisible(R.id.IMAGE_MENU,
1683 type == WebView.HitTestResult.IMAGE_TYPE
1684 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1685 menu.setGroupVisible(R.id.ANCHOR_MENU,
1686 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1687 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1688
1689 // Setup custom handling depending on the type
1690 switch (type) {
1691 case WebView.HitTestResult.PHONE_TYPE:
1692 menu.setHeaderTitle(Uri.decode(extra));
1693 menu.findItem(R.id.dial_context_menu_id).setIntent(
1694 new Intent(Intent.ACTION_VIEW, Uri
1695 .parse(WebView.SCHEME_TEL + extra)));
1696 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1697 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001698 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001699 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1700 addIntent);
1701 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1702 new Copy(extra));
1703 break;
1704
1705 case WebView.HitTestResult.EMAIL_TYPE:
1706 menu.setHeaderTitle(extra);
1707 menu.findItem(R.id.email_context_menu_id).setIntent(
1708 new Intent(Intent.ACTION_VIEW, Uri
1709 .parse(WebView.SCHEME_MAILTO + extra)));
1710 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1711 new Copy(extra));
1712 break;
1713
1714 case WebView.HitTestResult.GEO_TYPE:
1715 menu.setHeaderTitle(extra);
1716 menu.findItem(R.id.map_context_menu_id).setIntent(
1717 new Intent(Intent.ACTION_VIEW, Uri
1718 .parse(WebView.SCHEME_GEO
1719 + URLEncoder.encode(extra))));
1720 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1721 new Copy(extra));
1722 break;
1723
1724 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1725 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1726 TextView titleView = (TextView) LayoutInflater.from(this)
1727 .inflate(android.R.layout.browser_link_context_header,
1728 null);
1729 titleView.setText(extra);
1730 menu.setHeaderView(titleView);
1731 // decide whether to show the open link in new tab option
1732 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001733 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001734 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1735 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001736 PackageManager pm = getPackageManager();
1737 Intent send = new Intent(Intent.ACTION_SEND);
1738 send.setType("text/plain");
1739 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1740 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1741 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1742 break;
1743 }
1744 // otherwise fall through to handle image part
1745 case WebView.HitTestResult.IMAGE_TYPE:
1746 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1747 menu.setHeaderTitle(extra);
1748 }
1749 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1750 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1751 menu.findItem(R.id.download_context_menu_id).
1752 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001753 menu.findItem(R.id.set_wallpaper_context_menu_id).
1754 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 break;
1756
1757 default:
1758 Log.w(LOGTAG, "We should not get here.");
1759 break;
1760 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001761 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001762 }
1763
The Android Open Source Project0c908882009-03-03 19:32:16 -08001764 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001765 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001766 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001767 // Attach the container that contains the main WebView and any other UI
1768 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001769 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001770
1771 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001772 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001773 if (errorConsole.numberOfErrors() == 0) {
1774 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1775 } else {
1776 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1777 }
1778
1779 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001780 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001781 ViewGroup.LayoutParams.WRAP_CONTENT));
1782 }
1783
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001784 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001785 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001786 if (t.isInVoiceSearchMode()) {
1787 showVoiceTitleBar(t.getVoiceDisplayTitle());
1788 } else {
1789 revertVoiceTitleBar();
1790 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001791 // Request focus on the top window.
1792 t.getTopWindow().requestFocus();
1793 }
1794
1795 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001796 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001797 t.attachSubWindow(mContentView);
1798 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 }
1800
1801 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001802 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001803 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001804 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001805
Grace Kloba22ac16e2009-10-07 18:00:23 -07001806 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1807 if (errorConsole != null) {
1808 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001809 }
1810
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001811 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001812 if (view != null) {
1813 view.setEmbeddedTitleBar(null);
1814 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 }
1816
1817 // Remove the sub window if it exists. Also called by TabControl when the
1818 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001819 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001820 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001821 // dismiss the subwindow. This will destroy the WebView.
1822 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001823 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
1825
Leon Scroggins1f005d32009-08-10 17:36:42 -04001826 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001827 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001829 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001830 }
1831
1832 // This method does a ton of stuff. It will attempt to create a new tab
1833 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001834 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001835 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1836 String appId) {
1837 final Tab currentTab = mTabControl.getCurrentTab();
1838 if (mTabControl.canCreateNewTab()) {
1839 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1840 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001841 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001842 // If the last tab was removed from the active tabs page, currentTab
1843 // will be null.
1844 if (currentTab != null) {
1845 removeTabFromContentView(currentTab);
1846 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001847 // We must set the new tab as the current tab to reflect the old
1848 // animation behavior.
1849 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001850 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001851 if (!urlData.isEmpty()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05001852 urlData.loadIn(tab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001853 }
1854 return tab;
1855 } else {
1856 // Get rid of the subwindow if it exists
1857 dismissSubWindow(currentTab);
1858 if (!urlData.isEmpty()) {
1859 // Load the given url.
Leon Scroggins58d56c62010-01-28 15:12:40 -05001860 urlData.loadIn(currentTab);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001861 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001862 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 }
1864 }
1865
Grace Kloba22ac16e2009-10-07 18:00:23 -07001866 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001867 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001868 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001869 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001870 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001871 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001872 }
Grace Klobac9181842009-04-14 08:53:22 -07001873 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001874 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001875 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001876 }
1877 }
1878
1879 private class Copy implements OnMenuItemClickListener {
1880 private CharSequence mText;
1881
1882 public boolean onMenuItemClick(MenuItem item) {
1883 copy(mText);
1884 return true;
1885 }
1886
1887 public Copy(CharSequence toCopy) {
1888 mText = toCopy;
1889 }
1890 }
1891
1892 private class Download implements OnMenuItemClickListener {
1893 private String mText;
1894
1895 public boolean onMenuItemClick(MenuItem item) {
1896 onDownloadStartNoStream(mText, null, null, null, -1);
1897 return true;
1898 }
1899
1900 public Download(String toDownload) {
1901 mText = toDownload;
1902 }
1903 }
1904
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001905 private class SetAsWallpaper extends Thread implements
1906 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1907 private URL mUrl;
1908 private ProgressDialog mWallpaperProgress;
1909 private boolean mCanceled = false;
1910
1911 public SetAsWallpaper(String url) {
1912 try {
1913 mUrl = new URL(url);
1914 } catch (MalformedURLException e) {
1915 mUrl = null;
1916 }
1917 }
1918
1919 public void onCancel(DialogInterface dialog) {
1920 mCanceled = true;
1921 }
1922
1923 public boolean onMenuItemClick(MenuItem item) {
1924 if (mUrl != null) {
1925 // The user may have tried to set a image with a large file size as their
1926 // background so it may take a few moments to perform the operation. Display
1927 // a progress spinner while it is working.
1928 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1929 mWallpaperProgress.setIndeterminate(true);
1930 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1931 mWallpaperProgress.setCancelable(true);
1932 mWallpaperProgress.setOnCancelListener(this);
1933 mWallpaperProgress.show();
1934 start();
1935 }
1936 return true;
1937 }
1938
1939 public void run() {
1940 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1941 try {
1942 // TODO: This will cause the resource to be downloaded again, when we
1943 // should in most cases be able to grab it from the cache. To fix this
1944 // we should query WebCore to see if we can access a cached version and
1945 // instead open an input stream on that. This pattern could also be used
1946 // in the download manager where the same problem exists.
1947 InputStream inputstream = mUrl.openStream();
1948 if (inputstream != null) {
1949 setWallpaper(inputstream);
1950 }
1951 } catch (IOException e) {
1952 Log.e(LOGTAG, "Unable to set new wallpaper");
1953 // Act as though the user canceled the operation so we try to
1954 // restore the old wallpaper.
1955 mCanceled = true;
1956 }
1957
1958 if (mCanceled) {
1959 // Restore the old wallpaper if the user cancelled whilst we were setting
1960 // the new wallpaper.
1961 int width = oldWallpaper.getIntrinsicWidth();
1962 int height = oldWallpaper.getIntrinsicHeight();
1963 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1964 Canvas canvas = new Canvas(bm);
1965 oldWallpaper.setBounds(0, 0, width, height);
1966 oldWallpaper.draw(canvas);
1967 try {
1968 setWallpaper(bm);
1969 } catch (IOException e) {
1970 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1971 }
1972 mCanceled = false;
1973 }
1974
1975 if (mWallpaperProgress.isShowing()) {
1976 mWallpaperProgress.dismiss();
1977 }
1978 }
1979 }
1980
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 private void copy(CharSequence text) {
1982 try {
1983 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1984 if (clip != null) {
1985 clip.setClipboardText(text);
1986 }
1987 } catch (android.os.RemoteException e) {
1988 Log.e(LOGTAG, "Copy failed", e);
1989 }
1990 }
1991
1992 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 * Resets the browser title-view to whatever it must be
1994 * (for example, if we had a loading error)
1995 * When we have a new page, we call resetTitle, when we
1996 * have to reset the titlebar to whatever it used to be
1997 * (for example, if the user chose to stop loading), we
1998 * call resetTitleAndRevertLockIcon.
1999 */
2000 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002001 mTabControl.getCurrentTab().revertLockIcon();
2002 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 resetTitleIconAndProgress();
2004 }
2005
2006 /**
2007 * Reset the title, favicon, and progress.
2008 */
2009 private void resetTitleIconAndProgress() {
2010 WebView current = mTabControl.getCurrentWebView();
2011 if (current == null) {
2012 return;
2013 }
2014 resetTitleAndIcon(current);
2015 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002016 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002017 }
2018
2019 // Reset the title and the icon based on the given item.
2020 private void resetTitleAndIcon(WebView view) {
2021 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2022 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002023 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002024 setFavicon(item.getFavicon());
2025 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002026 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002027 setFavicon(null);
2028 }
2029 }
2030
2031 /**
2032 * Sets a title composed of the URL and the title string.
2033 * @param url The URL of the site being loaded.
2034 * @param title The title of the site being loaded.
2035 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002036 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 mUrl = url;
2038 mTitle = title;
2039
Leon Scroggins58d56c62010-01-28 15:12:40 -05002040 // If we are in voice search mode, the title has already been set.
2041 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2042 mTitleBar.setDisplayTitle(url);
2043 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 }
2045
2046 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 * @param url The URL to build a title version of the URL from.
2048 * @return The title version of the URL or null if fails.
2049 * The title version of the URL can be either the URL hostname,
2050 * or the hostname with an "https://" prefix (for secure URLs),
2051 * or an empty string if, for example, the URL in question is a
2052 * file:// URL with no hostname.
2053 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002054 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002055 String titleUrl = null;
2056
2057 if (url != null) {
2058 try {
2059 // parse the url string
2060 URL urlObj = new URL(url);
2061 if (urlObj != null) {
2062 titleUrl = "";
2063
2064 String protocol = urlObj.getProtocol();
2065 String host = urlObj.getHost();
2066
2067 if (host != null && 0 < host.length()) {
2068 titleUrl = host;
2069 if (protocol != null) {
2070 // if a secure site, add an "https://" prefix!
2071 if (protocol.equalsIgnoreCase("https")) {
2072 titleUrl = protocol + "://" + host;
2073 }
2074 }
2075 }
2076 }
2077 } catch (MalformedURLException e) {}
2078 }
2079
2080 return titleUrl;
2081 }
2082
2083 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002084 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002085 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002086 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 }
2088
2089 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002090 * Close the tab, remove its associated title bar, and adjust mTabControl's
2091 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002092 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002093 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002094 int currentIndex = mTabControl.getCurrentIndex();
2095 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002096 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002097 if (currentIndex >= removeIndex && currentIndex != 0) {
2098 currentIndex--;
2099 }
2100 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002101 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002102 }
2103
2104 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002105 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002106 if (current == null) {
2107 /*
2108 * Instead of finishing the activity, simply push this to the back
2109 * of the stack and let ActivityManager to choose the foreground
2110 * activity. As BrowserActivity is singleTask, it will be always the
2111 * root of the task. So we can use either true or false for
2112 * moveTaskToBack().
2113 */
2114 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002115 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 }
2117 WebView w = current.getWebView();
2118 if (w.canGoBack()) {
2119 w.goBack();
2120 } else {
2121 // Check to see if we are closing a window that was created by
2122 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002123 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002125 switchToTab(mTabControl.getTabIndex(parent));
2126 // Now we close the other tab
2127 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 } else {
2129 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002130 // force the tab's inLoad() to be false as we are going to
2131 // either finish the activity or remove the tab. This will
2132 // ensure pauseWebViewTimers() taking action.
2133 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 if (mTabControl.getTabCount() == 1) {
2135 finish();
2136 return;
2137 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002138 // call pauseWebViewTimers() now, we won't be able to call
2139 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002140 // Temporarily change mActivityInPause to be true as
2141 // pauseWebViewTimers() will do nothing if mActivityInPause
2142 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002143 boolean savedState = mActivityInPause;
2144 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002145 Log.e(LOGTAG, "BrowserActivity is already paused "
2146 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002147 }
2148 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002149 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002150 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 removeTabFromContentView(current);
2152 mTabControl.removeTab(current);
2153 }
2154 /*
2155 * Instead of finishing the activity, simply push this to the back
2156 * of the stack and let ActivityManager to choose the foreground
2157 * activity. As BrowserActivity is singleTask, it will be always the
2158 * root of the task. So we can use either true or false for
2159 * moveTaskToBack().
2160 */
2161 moveTaskToBack(true);
2162 }
2163 }
2164 }
2165
Grace Kloba22ac16e2009-10-07 18:00:23 -07002166 boolean isMenuDown() {
2167 return mMenuIsDown;
2168 }
2169
Grace Kloba5942df02009-09-18 11:48:29 -07002170 @Override
2171 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002172 // Even if MENU is already held down, we need to call to super to open
2173 // the IME on long press.
2174 if (KeyEvent.KEYCODE_MENU == keyCode) {
2175 mMenuIsDown = true;
2176 return super.onKeyDown(keyCode, event);
2177 }
Grace Kloba5942df02009-09-18 11:48:29 -07002178 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2179 // still down, we don't want to trigger the search. Pretend to consume
2180 // the key and do nothing.
2181 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182
Grace Kloba5942df02009-09-18 11:48:29 -07002183 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002184 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002185 // WebView/WebTextView handle the keys in the KeyDown. As
2186 // the Activity's shortcut keys are only handled when WebView
2187 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2188 if (event.isShiftPressed()) {
2189 getTopWindow().pageUp(false);
2190 } else {
2191 getTopWindow().pageDown(false);
2192 }
Grace Kloba5942df02009-09-18 11:48:29 -07002193 return true;
2194 case KeyEvent.KEYCODE_BACK:
2195 if (event.getRepeatCount() == 0) {
2196 event.startTracking();
2197 return true;
2198 } else if (mCustomView == null && mActiveTabsPage == null
2199 && event.isLongPress()) {
2200 bookmarksOrHistoryPicker(true);
2201 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002202 }
Grace Kloba5942df02009-09-18 11:48:29 -07002203 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
Grace Kloba5942df02009-09-18 11:48:29 -07002205 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 }
2207
Grace Kloba5942df02009-09-18 11:48:29 -07002208 @Override
2209 public boolean onKeyUp(int keyCode, KeyEvent event) {
2210 switch(keyCode) {
2211 case KeyEvent.KEYCODE_MENU:
2212 mMenuIsDown = false;
2213 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002214 case KeyEvent.KEYCODE_BACK:
2215 if (event.isTracking() && !event.isCanceled()) {
2216 if (mCustomView != null) {
2217 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002218 mTabControl.getCurrentWebView().getWebChromeClient()
2219 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002220 } else if (mActiveTabsPage != null) {
2221 // if tab page is showing, hide it
2222 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002223 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002224 WebView subwindow = mTabControl.getCurrentSubWindow();
2225 if (subwindow != null) {
2226 if (subwindow.canGoBack()) {
2227 subwindow.goBack();
2228 } else {
2229 dismissSubWindow(mTabControl.getCurrentTab());
2230 }
2231 } else {
2232 goBackOnePageOrQuit();
2233 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002234 }
Grace Kloba5942df02009-09-18 11:48:29 -07002235 return true;
2236 }
2237 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 }
Grace Kloba5942df02009-09-18 11:48:29 -07002239 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002240 }
2241
Leon Scroggins68579392009-09-15 15:31:54 -04002242 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002243 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 resetTitleAndRevertLockIcon();
2245 WebView w = getTopWindow();
2246 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002247 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2248 // same logic here. But for subwindow case, should we call into the main
2249 // WebView's onPageFinished as we never call its onPageStarted and if
2250 // the page finishes itself, we don't call onPageFinished.
2251 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2252 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253
2254 cancelStopToast();
2255 mStopToast = Toast
2256 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2257 mStopToast.show();
2258 }
2259
Grace Kloba22ac16e2009-10-07 18:00:23 -07002260 boolean didUserStopLoading() {
2261 return mDidStopLoad;
2262 }
2263
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 private void cancelStopToast() {
2265 if (mStopToast != null) {
2266 mStopToast.cancel();
2267 mStopToast = null;
2268 }
2269 }
2270
Grace Kloba22ac16e2009-10-07 18:00:23 -07002271 // called by a UI or non-UI thread to post the message
2272 public void postMessage(int what, int arg1, int arg2, Object obj,
2273 long delayMillis) {
2274 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2275 obj), delayMillis);
2276 }
2277
2278 // called by a UI or non-UI thread to remove the message
2279 void removeMessages(int what, Object object) {
2280 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 }
2282
2283 // public message ids
2284 public final static int LOAD_URL = 1001;
2285 public final static int STOP_LOAD = 1002;
2286
2287 // Message Ids
2288 private static final int FOCUS_NODE_HREF = 102;
2289 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002290 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002291
Grace Kloba22ac16e2009-10-07 18:00:23 -07002292 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002293
The Android Open Source Project0c908882009-03-03 19:32:16 -08002294 // Private handler for handling javascript and saving passwords
2295 private Handler mHandler = new Handler() {
2296
2297 public void handleMessage(Message msg) {
2298 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002299 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002300 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002301 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002302 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303 if (url == null || url.length() == 0) {
2304 break;
2305 }
2306 HashMap focusNodeMap = (HashMap) msg.obj;
2307 WebView view = (WebView) focusNodeMap.get("webview");
2308 // Only apply the action if the top window did not change.
2309 if (getTopWindow() != view) {
2310 break;
2311 }
2312 switch (msg.arg1) {
2313 case R.id.open_context_menu_id:
2314 case R.id.view_image_context_menu_id:
2315 loadURL(getTopWindow(), url);
2316 break;
2317 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002318 final Tab parent = mTabControl.getCurrentTab();
2319 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002320 if (newTab != parent) {
2321 parent.addChildTab(newTab);
2322 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 break;
2324 case R.id.bookmark_context_menu_id:
2325 Intent intent = new Intent(BrowserActivity.this,
2326 AddBookmarkPage.class);
2327 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002328 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002329 startActivity(intent);
2330 break;
2331 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002332 // See if this site has been visited before
2333 StringBuilder sb = new StringBuilder(
2334 Browser.BookmarkColumns.URL + " = ");
2335 DatabaseUtils.appendEscapedSQLString(sb, url);
2336 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2337 Browser.HISTORY_PROJECTION,
2338 sb.toString(),
2339 null,
2340 null);
2341 if (c.moveToFirst()) {
2342 // The site has been visited before, so grab the
2343 // info from the database.
2344 Bitmap favicon = null;
2345 Bitmap thumbnail = null;
2346 String linkTitle = c.getString(Browser.
2347 HISTORY_PROJECTION_TITLE_INDEX);
2348 byte[] data = c.getBlob(Browser.
2349 HISTORY_PROJECTION_FAVICON_INDEX);
2350 if (data != null) {
2351 favicon = BitmapFactory.decodeByteArray(
2352 data, 0, data.length);
2353 }
2354 data = c.getBlob(Browser.
2355 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2356 if (data != null) {
2357 thumbnail = BitmapFactory.decodeByteArray(
2358 data, 0, data.length);
2359 }
2360 sharePage(BrowserActivity.this,
2361 linkTitle, url, favicon, thumbnail);
2362 } else {
2363 Browser.sendString(BrowserActivity.this, url,
2364 getString(
2365 R.string.choosertitle_sharevia));
2366 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002367 break;
2368 case R.id.copy_link_context_menu_id:
2369 copy(url);
2370 break;
2371 case R.id.save_link_context_menu_id:
2372 case R.id.download_context_menu_id:
2373 onDownloadStartNoStream(url, null, null, null, -1);
2374 break;
2375 }
2376 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002377 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002378
2379 case LOAD_URL:
2380 loadURL(getTopWindow(), (String) msg.obj);
2381 break;
2382
2383 case STOP_LOAD:
2384 stopLoading();
2385 break;
2386
2387 case CANCEL_CREDS_REQUEST:
2388 resumeAfterCredentials();
2389 break;
2390
The Android Open Source Project0c908882009-03-03 19:32:16 -08002391 case RELEASE_WAKELOCK:
2392 if (mWakeLock.isHeld()) {
2393 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002394 // if we reach here, Browser should be still in the
2395 // background loading after WAKELOCK_TIMEOUT (5-min).
2396 // To avoid burning the battery, stop loading.
2397 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002398 }
2399 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002400
2401 case UPDATE_BOOKMARK_THUMBNAIL:
2402 WebView view = (WebView) msg.obj;
2403 if (view != null) {
2404 updateScreenshot(view);
2405 }
2406 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002407 }
2408 }
2409 };
2410
Leon Scroggins96afcb12009-12-10 12:35:56 -05002411 /**
2412 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2413 * an {@link Intent} to launch the Activity chooser.
2414 * @param c Context used to launch a new Activity.
2415 * @param title Title of the page. Stored in the Intent with
2416 * {@link Browser#EXTRA_SHARE_TITLE}
2417 * @param url URL of the page. Stored in the Intent with
2418 * {@link Intent#EXTRA_TEXT}
2419 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2420 * with {@link Browser#EXTRA_SHARE_FAVICON}
2421 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2422 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2423 */
2424 public static final void sharePage(Context c, String title, String url,
2425 Bitmap favicon, Bitmap screenshot) {
2426 Intent send = new Intent(Intent.ACTION_SEND);
2427 send.setType("text/plain");
2428 send.putExtra(Intent.EXTRA_TEXT, url);
2429 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2430 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2431 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2432 try {
2433 c.startActivity(Intent.createChooser(send, c.getString(
2434 R.string.choosertitle_sharevia)));
2435 } catch(android.content.ActivityNotFoundException ex) {
2436 // if no app handles it, do nothing
2437 }
2438 }
2439
Leon Scroggins89c6d362009-07-15 16:54:37 -04002440 private void updateScreenshot(WebView view) {
2441 // If this is a bookmarked site, add a screenshot to the database.
2442 // FIXME: When should we update? Every time?
2443 // FIXME: Would like to make sure there is actually something to
2444 // draw, but the API for that (WebViewCore.pictureReady()) is not
2445 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002446
Patrick Scott3918d442009-08-04 13:22:29 -04002447 ContentResolver cr = getContentResolver();
2448 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002449 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002450 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002451 boolean succeed = c.moveToFirst();
2452 ContentValues values = null;
2453 while (succeed) {
2454 if (values == null) {
2455 final ByteArrayOutputStream os
2456 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002457 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002458 if (bm == null) {
2459 c.close();
2460 return;
2461 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002462 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2463 values = new ContentValues();
2464 values.put(Browser.BookmarkColumns.THUMBNAIL,
2465 os.toByteArray());
2466 }
2467 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2468 c.getInt(0)), values, null, null);
2469 succeed = c.moveToNext();
2470 }
2471 c.close();
2472 }
2473 }
2474
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002475 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002476 * Values for the size of the thumbnail created when taking a screenshot.
2477 * Lazily initialized. Instead of using these directly, use
2478 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002479 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002480 private static int THUMBNAIL_WIDTH = 0;
2481 private static int THUMBNAIL_HEIGHT = 0;
2482
2483 /**
2484 * Return the desired width for thumbnail screenshots, which are stored in
2485 * the database, and used on the bookmarks screen.
2486 * @param context Context for finding out the density of the screen.
2487 * @return int desired width for thumbnail screenshot.
2488 */
2489 /* package */ static int getDesiredThumbnailWidth(Context context) {
2490 if (THUMBNAIL_WIDTH == 0) {
2491 float density = context.getResources().getDisplayMetrics().density;
2492 THUMBNAIL_WIDTH = (int) (90 * density);
2493 THUMBNAIL_HEIGHT = (int) (80 * density);
2494 }
2495 return THUMBNAIL_WIDTH;
2496 }
2497
2498 /**
2499 * Return the desired height for thumbnail screenshots, which are stored in
2500 * the database, and used on the bookmarks screen.
2501 * @param context Context for finding out the density of the screen.
2502 * @return int desired height for thumbnail screenshot.
2503 */
2504 /* package */ static int getDesiredThumbnailHeight(Context context) {
2505 // To ensure that they are both initialized.
2506 getDesiredThumbnailWidth(context);
2507 return THUMBNAIL_HEIGHT;
2508 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002509
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002510 private Bitmap createScreenshot(WebView view) {
2511 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002512 if (thumbnail == null) {
2513 return null;
2514 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002515 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2516 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002517 Canvas canvas = new Canvas(bm);
2518 // May need to tweak these values to determine what is the
2519 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002520 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002521 int thumbnailHeight = thumbnail.getHeight();
2522 float scaleFactorX = 1.0f;
2523 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002524 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002525 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002526 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002527 } else {
2528 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002529 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002530
2531 if (view.getWidth() > view.getHeight() &&
2532 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2533 // If the device is in landscape and the page is shorter
2534 // than the height of the view, stretch the thumbnail to fill the
2535 // space.
2536 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2537 (float)thumbnailHeight;
2538 } else {
2539 // In the portrait case, this looks nice.
2540 scaleFactorY = scaleFactorX;
2541 }
2542
2543 canvas.scale(scaleFactorX, scaleFactorY);
2544
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002545 thumbnail.draw(canvas);
2546 return bm;
2547 }
2548
The Android Open Source Project0c908882009-03-03 19:32:16 -08002549 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002550 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002551 //-------------------------------------------------------------------------
2552
2553 // Use in overrideUrlLoading
2554 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2555 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2556 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2557 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2558
Grace Kloba22ac16e2009-10-07 18:00:23 -07002559 void onPageStarted(WebView view, String url, Bitmap favicon) {
2560 // when BrowserActivity just starts, onPageStarted may be called before
2561 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2562 // to start the timer. As we won't switch tabs while an activity is in
2563 // pause state, we can ensure calling resume and pause in pair.
2564 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002565
Grace Kloba22ac16e2009-10-07 18:00:23 -07002566 resetLockIcon(url);
2567 setUrlTitle(url, null);
2568 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002569 // Keep this initial progress in sync with initialProgressValue (* 100)
2570 // in ProgressTracker.cpp
2571 // Show some progress so that the user knows the page is beginning to
2572 // load
2573 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002574 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002575 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002576
Grace Kloba22ac16e2009-10-07 18:00:23 -07002577 if (mSettings.isTracing()) {
2578 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002580 WebAddress uri = new WebAddress(url);
2581 host = uri.mHost;
2582 } catch (android.net.ParseException ex) {
2583 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002584 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002585 host = host.replace('.', '_');
2586 host += ".trace";
2587 mInTrace = true;
2588 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2589 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 // Performance probe
2592 if (false) {
2593 mStart = SystemClock.uptimeMillis();
2594 mProcessStart = Process.getElapsedCpuTime();
2595 long[] sysCpu = new long[7];
2596 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2597 sysCpu, null)) {
2598 mUserStart = sysCpu[0] + sysCpu[1];
2599 mSystemStart = sysCpu[2];
2600 mIdleStart = sysCpu[3];
2601 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2602 }
2603 mUiStart = SystemClock.currentThreadTimeMillis();
2604 }
2605 }
2606
2607 void onPageFinished(WebView view, String url) {
2608 // Reset the title and icon in case we stopped a provisional load.
2609 resetTitleAndIcon(view);
2610 // Update the lock icon image only once we are done loading
2611 updateLockIconToLatest();
2612 // pause the WebView timer and release the wake lock if it is finished
2613 // while BrowserActivity is in pause state.
2614 if (mActivityInPause && pauseWebViewTimers()) {
2615 if (mWakeLock.isHeld()) {
2616 mHandler.removeMessages(RELEASE_WAKELOCK);
2617 mWakeLock.release();
2618 }
2619 }
2620
2621 // Performance probe
2622 if (false) {
2623 long[] sysCpu = new long[7];
2624 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2625 sysCpu, null)) {
2626 String uiInfo = "UI thread used "
2627 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2628 + " ms";
2629 if (LOGD_ENABLED) {
2630 Log.d(LOGTAG, uiInfo);
2631 }
2632 //The string that gets written to the log
2633 String performanceString = "It took total "
2634 + (SystemClock.uptimeMillis() - mStart)
2635 + " ms clock time to load the page."
2636 + "\nbrowser process used "
2637 + (Process.getElapsedCpuTime() - mProcessStart)
2638 + " ms, user processes used "
2639 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2640 + " ms, kernel used "
2641 + (sysCpu[2] - mSystemStart) * 10
2642 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2643 + " ms and irq took "
2644 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2645 * 10 + " ms, " + uiInfo;
2646 if (LOGD_ENABLED) {
2647 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2648 }
2649 if (url != null) {
2650 // strip the url to maintain consistency
2651 String newUrl = new String(url);
2652 if (newUrl.startsWith("http://www.")) {
2653 newUrl = newUrl.substring(11);
2654 } else if (newUrl.startsWith("http://")) {
2655 newUrl = newUrl.substring(7);
2656 } else if (newUrl.startsWith("https://www.")) {
2657 newUrl = newUrl.substring(12);
2658 } else if (newUrl.startsWith("https://")) {
2659 newUrl = newUrl.substring(8);
2660 }
2661 if (LOGD_ENABLED) {
2662 Log.d(LOGTAG, newUrl + " loaded");
2663 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002664 }
2665 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002666 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002667
Grace Kloba22ac16e2009-10-07 18:00:23 -07002668 if (mInTrace) {
2669 mInTrace = false;
2670 Debug.stopMethodTracing();
2671 }
2672 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 boolean shouldOverrideUrlLoading(WebView view, String url) {
2675 if (url.startsWith(SCHEME_WTAI)) {
2676 // wtai://wp/mc;number
2677 // number=string(phone-number)
2678 if (url.startsWith(SCHEME_WTAI_MC)) {
2679 Intent intent = new Intent(Intent.ACTION_VIEW,
2680 Uri.parse(WebView.SCHEME_TEL +
2681 url.substring(SCHEME_WTAI_MC.length())));
2682 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002683 return true;
2684 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002685 // wtai://wp/sd;dtmf
2686 // dtmf=string(dialstring)
2687 if (url.startsWith(SCHEME_WTAI_SD)) {
2688 // TODO: only send when there is active voice connection
2689 return false;
2690 }
2691 // wtai://wp/ap;number;name
2692 // number=string(phone-number)
2693 // name=string
2694 if (url.startsWith(SCHEME_WTAI_AP)) {
2695 // TODO
2696 return false;
2697 }
2698 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002699
Grace Kloba22ac16e2009-10-07 18:00:23 -07002700 // The "about:" schemes are internal to the browser; don't want these to
2701 // be dispatched to other apps.
2702 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002703 return false;
2704 }
2705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 Intent intent;
2707 // perform generic parsing of the URI to turn it into an Intent.
2708 try {
2709 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2710 } catch (URISyntaxException ex) {
2711 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2712 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002713 }
2714
Grace Kloba22ac16e2009-10-07 18:00:23 -07002715 // check whether the intent can be resolved. If not, we will see
2716 // whether we can download it from the Market.
2717 if (getPackageManager().resolveActivity(intent, 0) == null) {
2718 String packagename = intent.getPackage();
2719 if (packagename != null) {
2720 intent = new Intent(Intent.ACTION_VIEW, Uri
2721 .parse("market://search?q=pname:" + packagename));
2722 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2723 startActivity(intent);
2724 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002725 } else {
2726 return false;
2727 }
2728 }
2729
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 // sanitize the Intent, ensuring web pages can not bypass browser
2731 // security (only access to BROWSABLE activities).
2732 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2733 intent.setComponent(null);
2734 try {
2735 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736 return true;
2737 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 } catch (ActivityNotFoundException ex) {
2739 // ignore the error. If no application can handle the URL,
2740 // eg about:blank, assume the browser can handle it.
2741 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002742
Grace Kloba22ac16e2009-10-07 18:00:23 -07002743 if (mMenuIsDown) {
2744 openTab(url);
2745 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002746 return true;
2747 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002748 return false;
2749 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002750
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 // -------------------------------------------------------------------------
2752 // Helper function for WebChromeClient
2753 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002754
Grace Kloba22ac16e2009-10-07 18:00:23 -07002755 void onProgressChanged(WebView view, int newProgress) {
2756 mTitleBar.setProgress(newProgress);
2757 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758
Grace Kloba22ac16e2009-10-07 18:00:23 -07002759 if (newProgress == 100) {
2760 // onProgressChanged() may continue to be called after the main
2761 // frame has finished loading, as any remaining sub frames continue
2762 // to load. We'll only get called once though with newProgress as
2763 // 100 when everything is loaded. (onPageFinished is called once
2764 // when the main frame completes loading regardless of the state of
2765 // any sub frames so calls to onProgressChanges may continue after
2766 // onPageFinished has executed)
2767 if (mInLoad) {
2768 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002769 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 // If the options menu is open, leave the title bar
2771 if (!mOptionsMenuOpen || !mIconView) {
2772 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002773 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002775 } else if (!mInLoad) {
2776 // onPageFinished may have already been called but a subframe is
2777 // still loading and updating the progress. Reset mInLoad and update
2778 // the menu items.
2779 mInLoad = true;
2780 updateInLoadMenuItems();
2781 if (!mOptionsMenuOpen || mIconView) {
2782 // This page has begun to load, so show the title bar
2783 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002784 }
2785 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002786 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002789 // if a view already exists then immediately terminate the new one
2790 if (mCustomView != null) {
2791 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002793 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794
2795 // Add the custom view to its container.
2796 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2797 mCustomView = view;
2798 mCustomViewCallback = callback;
2799 // Save the menu state and set it to empty while the custom
2800 // view is showing.
2801 mOldMenuState = mMenuState;
2802 mMenuState = EMPTY_MENU;
2803 // Hide the content view.
2804 mContentView.setVisibility(View.GONE);
2805 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002806 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002807 mCustomViewContainer.setVisibility(View.VISIBLE);
2808 mCustomViewContainer.bringToFront();
2809 }
2810
2811 void onHideCustomView() {
2812 if (mCustomView == null)
2813 return;
2814
2815 // Hide the custom view.
2816 mCustomView.setVisibility(View.GONE);
2817 // Remove the custom view from its container.
2818 mCustomViewContainer.removeView(mCustomView);
2819 mCustomView = null;
2820 // Reset the old menu state.
2821 mMenuState = mOldMenuState;
2822 mOldMenuState = EMPTY_MENU;
2823 mCustomViewContainer.setVisibility(View.GONE);
2824 mCustomViewCallback.onCustomViewHidden();
2825 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002826 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002827 mContentView.setVisibility(View.VISIBLE);
2828 }
2829
2830 Bitmap getDefaultVideoPoster() {
2831 if (mDefaultVideoPoster == null) {
2832 mDefaultVideoPoster = BitmapFactory.decodeResource(
2833 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002834 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002835 return mDefaultVideoPoster;
2836 }
Patrick Scott3918d442009-08-04 13:22:29 -04002837
Grace Kloba22ac16e2009-10-07 18:00:23 -07002838 View getVideoLoadingProgressView() {
2839 if (mVideoProgressView == null) {
2840 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2841 mVideoProgressView = inflater.inflate(
2842 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002843 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002844 return mVideoProgressView;
2845 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002846
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002847 /*
2848 * The Object used to inform the WebView of the file to upload.
2849 */
2850 private ValueCallback<Uri> mUploadMessage;
2851
Grace Kloba22ac16e2009-10-07 18:00:23 -07002852 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2853 if (mUploadMessage != null) return;
2854 mUploadMessage = uploadMsg;
2855 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2856 i.addCategory(Intent.CATEGORY_OPENABLE);
2857 i.setType("*/*");
2858 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2859 getString(R.string.choose_upload)), FILE_SELECTED);
2860 }
2861
2862 // -------------------------------------------------------------------------
2863 // Implement functions for DownloadListener
2864 // -------------------------------------------------------------------------
2865
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866 /**
2867 * Notify the host application a download should be done, or that
2868 * the data should be streamed if a streaming viewer is available.
2869 * @param url The full url to the content that should be downloaded
2870 * @param contentDisposition Content-disposition http header, if
2871 * present.
2872 * @param mimetype The mimetype of the content reported by the server
2873 * @param contentLength The file size reported by the server
2874 */
2875 public void onDownloadStart(String url, String userAgent,
2876 String contentDisposition, String mimetype, long contentLength) {
2877 // if we're dealing wih A/V content that's not explicitly marked
2878 // for download, check if it's streamable.
2879 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002880 || !contentDisposition.regionMatches(
2881 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 // query the package manager to see if there's a registered handler
2883 // that matches.
2884 Intent intent = new Intent(Intent.ACTION_VIEW);
2885 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002886 ResolveInfo info = getPackageManager().resolveActivity(intent,
2887 PackageManager.MATCH_DEFAULT_ONLY);
2888 if (info != null) {
2889 ComponentName myName = getComponentName();
2890 // If we resolved to ourselves, we don't want to attempt to
2891 // load the url only to try and download it again.
2892 if (!myName.getPackageName().equals(
2893 info.activityInfo.packageName)
2894 || !myName.getClassName().equals(
2895 info.activityInfo.name)) {
2896 // someone (other than us) knows how to handle this mime
2897 // type with this scheme, don't download.
2898 try {
2899 startActivity(intent);
2900 return;
2901 } catch (ActivityNotFoundException ex) {
2902 if (LOGD_ENABLED) {
2903 Log.d(LOGTAG, "activity not found for " + mimetype
2904 + " over " + Uri.parse(url).getScheme(),
2905 ex);
2906 }
2907 // Best behavior is to fall back to a download in this
2908 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002910 }
2911 }
2912 }
2913 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2914 }
2915
2916 /**
2917 * Notify the host application a download should be done, even if there
2918 * is a streaming viewer available for thise type.
2919 * @param url The full url to the content that should be downloaded
2920 * @param contentDisposition Content-disposition http header, if
2921 * present.
2922 * @param mimetype The mimetype of the content reported by the server
2923 * @param contentLength The file size reported by the server
2924 */
2925 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2926 String contentDisposition, String mimetype, long contentLength) {
2927
2928 String filename = URLUtil.guessFileName(url,
2929 contentDisposition, mimetype);
2930
2931 // Check to see if we have an SDCard
2932 String status = Environment.getExternalStorageState();
2933 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2934 int title;
2935 String msg;
2936
2937 // Check to see if the SDCard is busy, same as the music app
2938 if (status.equals(Environment.MEDIA_SHARED)) {
2939 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2940 title = R.string.download_sdcard_busy_dlg_title;
2941 } else {
2942 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2943 title = R.string.download_no_sdcard_dlg_title;
2944 }
2945
2946 new AlertDialog.Builder(this)
2947 .setTitle(title)
2948 .setIcon(android.R.drawable.ic_dialog_alert)
2949 .setMessage(msg)
2950 .setPositiveButton(R.string.ok, null)
2951 .show();
2952 return;
2953 }
2954
2955 // java.net.URI is a lot stricter than KURL so we have to undo
2956 // KURL's percent-encoding and redo the encoding using java.net.URI.
2957 URI uri = null;
2958 try {
2959 // Undo the percent-encoding that KURL may have done.
2960 String newUrl = new String(URLUtil.decode(url.getBytes()));
2961 // Parse the url into pieces
2962 WebAddress w = new WebAddress(newUrl);
2963 String frag = null;
2964 String query = null;
2965 String path = w.mPath;
2966 // Break the path into path, query, and fragment
2967 if (path.length() > 0) {
2968 // Strip the fragment
2969 int idx = path.lastIndexOf('#');
2970 if (idx != -1) {
2971 frag = path.substring(idx + 1);
2972 path = path.substring(0, idx);
2973 }
2974 idx = path.lastIndexOf('?');
2975 if (idx != -1) {
2976 query = path.substring(idx + 1);
2977 path = path.substring(0, idx);
2978 }
2979 }
2980 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2981 query, frag);
2982 } catch (Exception e) {
2983 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2984 return;
2985 }
2986
2987 // XXX: Have to use the old url since the cookies were stored using the
2988 // old percent-encoded url.
2989 String cookies = CookieManager.getInstance().getCookie(url);
2990
2991 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002992 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2993 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2994 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2995 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002996 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002997 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002999 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3000 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3001 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3002 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3003 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003004 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003005 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003006 }
3007 if (mimetype == null) {
3008 // We must have long pressed on a link or image to download it. We
3009 // are not sure of the mimetype in this case, so do a head request
3010 new FetchUrlMimeType(this).execute(values);
3011 } else {
3012 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003013 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003014 }
3015
3016 }
3017
Grace Kloba22ac16e2009-10-07 18:00:23 -07003018 // -------------------------------------------------------------------------
3019
The Android Open Source Project0c908882009-03-03 19:32:16 -08003020 /**
3021 * Resets the lock icon. This method is called when we start a new load and
3022 * know the url to be loaded.
3023 */
3024 private void resetLockIcon(String url) {
3025 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003026 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003027 updateLockIconImage(LOCK_ICON_UNSECURE);
3028 }
3029
The Android Open Source Project0c908882009-03-03 19:32:16 -08003030 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003031 * Update the lock icon to correspond to our latest state.
3032 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003033 private void updateLockIconToLatest() {
3034 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003035 }
3036
3037 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003038 * Updates the lock-icon image in the title-bar.
3039 */
3040 private void updateLockIconImage(int lockIconType) {
3041 Drawable d = null;
3042 if (lockIconType == LOCK_ICON_SECURE) {
3043 d = mSecLockIcon;
3044 } else if (lockIconType == LOCK_ICON_MIXED) {
3045 d = mMixLockIcon;
3046 }
Leon Scroggins68579392009-09-15 15:31:54 -04003047 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003048 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003049 }
3050
3051 /**
3052 * Displays a page-info dialog.
3053 * @param tab The tab to show info about
3054 * @param fromShowSSLCertificateOnError The flag that indicates whether
3055 * this dialog was opened from the SSL-certificate-on-error dialog or
3056 * not. This is important, since we need to know whether to return to
3057 * the parent dialog or simply dismiss.
3058 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003059 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060 final boolean fromShowSSLCertificateOnError) {
3061 final LayoutInflater factory = LayoutInflater
3062 .from(this);
3063
3064 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3065
3066 final WebView view = tab.getWebView();
3067
3068 String url = null;
3069 String title = null;
3070
3071 if (view == null) {
3072 url = tab.getUrl();
3073 title = tab.getTitle();
3074 } else if (view == mTabControl.getCurrentWebView()) {
3075 // Use the cached title and url if this is the current WebView
3076 url = mUrl;
3077 title = mTitle;
3078 } else {
3079 url = view.getUrl();
3080 title = view.getTitle();
3081 }
3082
3083 if (url == null) {
3084 url = "";
3085 }
3086 if (title == null) {
3087 title = "";
3088 }
3089
3090 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3091 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3092
3093 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003094 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003095
3096 AlertDialog.Builder alertDialogBuilder =
3097 new AlertDialog.Builder(this)
3098 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3099 .setView(pageInfoView)
3100 .setPositiveButton(
3101 R.string.ok,
3102 new DialogInterface.OnClickListener() {
3103 public void onClick(DialogInterface dialog,
3104 int whichButton) {
3105 mPageInfoDialog = null;
3106 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003107
3108 // if we came here from the SSL error dialog
3109 if (fromShowSSLCertificateOnError) {
3110 // go back to the SSL error dialog
3111 showSSLCertificateOnError(
3112 mSSLCertificateOnErrorView,
3113 mSSLCertificateOnErrorHandler,
3114 mSSLCertificateOnErrorError);
3115 }
3116 }
3117 })
3118 .setOnCancelListener(
3119 new DialogInterface.OnCancelListener() {
3120 public void onCancel(DialogInterface dialog) {
3121 mPageInfoDialog = null;
3122 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123
3124 // if we came here from the SSL error dialog
3125 if (fromShowSSLCertificateOnError) {
3126 // go back to the SSL error dialog
3127 showSSLCertificateOnError(
3128 mSSLCertificateOnErrorView,
3129 mSSLCertificateOnErrorHandler,
3130 mSSLCertificateOnErrorError);
3131 }
3132 }
3133 });
3134
3135 // if we have a main top-level page SSL certificate set or a certificate
3136 // error
3137 if (fromShowSSLCertificateOnError ||
3138 (view != null && view.getCertificate() != null)) {
3139 // add a 'View Certificate' button
3140 alertDialogBuilder.setNeutralButton(
3141 R.string.view_certificate,
3142 new DialogInterface.OnClickListener() {
3143 public void onClick(DialogInterface dialog,
3144 int whichButton) {
3145 mPageInfoDialog = null;
3146 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003147
3148 // if we came here from the SSL error dialog
3149 if (fromShowSSLCertificateOnError) {
3150 // go back to the SSL error dialog
3151 showSSLCertificateOnError(
3152 mSSLCertificateOnErrorView,
3153 mSSLCertificateOnErrorHandler,
3154 mSSLCertificateOnErrorError);
3155 } else {
3156 // otherwise, display the top-most certificate from
3157 // the chain
3158 if (view.getCertificate() != null) {
3159 showSSLCertificate(tab);
3160 }
3161 }
3162 }
3163 });
3164 }
3165
3166 mPageInfoDialog = alertDialogBuilder.show();
3167 }
3168
3169 /**
3170 * Displays the main top-level page SSL certificate dialog
3171 * (accessible from the Page-Info dialog).
3172 * @param tab The tab to show certificate for.
3173 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003174 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003175 final View certificateView =
3176 inflateCertificateView(tab.getWebView().getCertificate());
3177 if (certificateView == null) {
3178 return;
3179 }
3180
3181 LayoutInflater factory = LayoutInflater.from(this);
3182
3183 final LinearLayout placeholder =
3184 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3185
3186 LinearLayout ll = (LinearLayout) factory.inflate(
3187 R.layout.ssl_success, placeholder);
3188 ((TextView)ll.findViewById(R.id.success))
3189 .setText(R.string.ssl_certificate_is_valid);
3190
3191 mSSLCertificateView = tab;
3192 mSSLCertificateDialog =
3193 new AlertDialog.Builder(this)
3194 .setTitle(R.string.ssl_certificate).setIcon(
3195 R.drawable.ic_dialog_browser_certificate_secure)
3196 .setView(certificateView)
3197 .setPositiveButton(R.string.ok,
3198 new DialogInterface.OnClickListener() {
3199 public void onClick(DialogInterface dialog,
3200 int whichButton) {
3201 mSSLCertificateDialog = null;
3202 mSSLCertificateView = null;
3203
3204 showPageInfo(tab, false);
3205 }
3206 })
3207 .setOnCancelListener(
3208 new DialogInterface.OnCancelListener() {
3209 public void onCancel(DialogInterface dialog) {
3210 mSSLCertificateDialog = null;
3211 mSSLCertificateView = null;
3212
3213 showPageInfo(tab, false);
3214 }
3215 })
3216 .show();
3217 }
3218
3219 /**
3220 * Displays the SSL error certificate dialog.
3221 * @param view The target web-view.
3222 * @param handler The SSL error handler responsible for cancelling the
3223 * connection that resulted in an SSL error or proceeding per user request.
3224 * @param error The SSL error object.
3225 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003226 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003227 final WebView view, final SslErrorHandler handler, final SslError error) {
3228
3229 final View certificateView =
3230 inflateCertificateView(error.getCertificate());
3231 if (certificateView == null) {
3232 return;
3233 }
3234
3235 LayoutInflater factory = LayoutInflater.from(this);
3236
3237 final LinearLayout placeholder =
3238 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3239
3240 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3241 LinearLayout ll = (LinearLayout)factory
3242 .inflate(R.layout.ssl_warning, placeholder);
3243 ((TextView)ll.findViewById(R.id.warning))
3244 .setText(R.string.ssl_untrusted);
3245 }
3246
3247 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3248 LinearLayout ll = (LinearLayout)factory
3249 .inflate(R.layout.ssl_warning, placeholder);
3250 ((TextView)ll.findViewById(R.id.warning))
3251 .setText(R.string.ssl_mismatch);
3252 }
3253
3254 if (error.hasError(SslError.SSL_EXPIRED)) {
3255 LinearLayout ll = (LinearLayout)factory
3256 .inflate(R.layout.ssl_warning, placeholder);
3257 ((TextView)ll.findViewById(R.id.warning))
3258 .setText(R.string.ssl_expired);
3259 }
3260
3261 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3262 LinearLayout ll = (LinearLayout)factory
3263 .inflate(R.layout.ssl_warning, placeholder);
3264 ((TextView)ll.findViewById(R.id.warning))
3265 .setText(R.string.ssl_not_yet_valid);
3266 }
3267
3268 mSSLCertificateOnErrorHandler = handler;
3269 mSSLCertificateOnErrorView = view;
3270 mSSLCertificateOnErrorError = error;
3271 mSSLCertificateOnErrorDialog =
3272 new AlertDialog.Builder(this)
3273 .setTitle(R.string.ssl_certificate).setIcon(
3274 R.drawable.ic_dialog_browser_certificate_partially_secure)
3275 .setView(certificateView)
3276 .setPositiveButton(R.string.ok,
3277 new DialogInterface.OnClickListener() {
3278 public void onClick(DialogInterface dialog,
3279 int whichButton) {
3280 mSSLCertificateOnErrorDialog = null;
3281 mSSLCertificateOnErrorView = null;
3282 mSSLCertificateOnErrorHandler = null;
3283 mSSLCertificateOnErrorError = null;
3284
Grace Kloba22ac16e2009-10-07 18:00:23 -07003285 view.getWebViewClient().onReceivedSslError(
3286 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003287 }
3288 })
3289 .setNeutralButton(R.string.page_info_view,
3290 new DialogInterface.OnClickListener() {
3291 public void onClick(DialogInterface dialog,
3292 int whichButton) {
3293 mSSLCertificateOnErrorDialog = null;
3294
3295 // do not clear the dialog state: we will
3296 // need to show the dialog again once the
3297 // user is done exploring the page-info details
3298
3299 showPageInfo(mTabControl.getTabFromView(view),
3300 true);
3301 }
3302 })
3303 .setOnCancelListener(
3304 new DialogInterface.OnCancelListener() {
3305 public void onCancel(DialogInterface dialog) {
3306 mSSLCertificateOnErrorDialog = null;
3307 mSSLCertificateOnErrorView = null;
3308 mSSLCertificateOnErrorHandler = null;
3309 mSSLCertificateOnErrorError = null;
3310
Grace Kloba22ac16e2009-10-07 18:00:23 -07003311 view.getWebViewClient().onReceivedSslError(
3312 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003313 }
3314 })
3315 .show();
3316 }
3317
3318 /**
3319 * Inflates the SSL certificate view (helper method).
3320 * @param certificate The SSL certificate.
3321 * @return The resultant certificate view with issued-to, issued-by,
3322 * issued-on, expires-on, and possibly other fields set.
3323 * If the input certificate is null, returns null.
3324 */
3325 private View inflateCertificateView(SslCertificate certificate) {
3326 if (certificate == null) {
3327 return null;
3328 }
3329
3330 LayoutInflater factory = LayoutInflater.from(this);
3331
3332 View certificateView = factory.inflate(
3333 R.layout.ssl_certificate, null);
3334
3335 // issued to:
3336 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3337 if (issuedTo != null) {
3338 ((TextView) certificateView.findViewById(R.id.to_common))
3339 .setText(issuedTo.getCName());
3340 ((TextView) certificateView.findViewById(R.id.to_org))
3341 .setText(issuedTo.getOName());
3342 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3343 .setText(issuedTo.getUName());
3344 }
3345
3346 // issued by:
3347 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3348 if (issuedBy != null) {
3349 ((TextView) certificateView.findViewById(R.id.by_common))
3350 .setText(issuedBy.getCName());
3351 ((TextView) certificateView.findViewById(R.id.by_org))
3352 .setText(issuedBy.getOName());
3353 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3354 .setText(issuedBy.getUName());
3355 }
3356
3357 // issued on:
3358 String issuedOn = reformatCertificateDate(
3359 certificate.getValidNotBefore());
3360 ((TextView) certificateView.findViewById(R.id.issued_on))
3361 .setText(issuedOn);
3362
3363 // expires on:
3364 String expiresOn = reformatCertificateDate(
3365 certificate.getValidNotAfter());
3366 ((TextView) certificateView.findViewById(R.id.expires_on))
3367 .setText(expiresOn);
3368
3369 return certificateView;
3370 }
3371
3372 /**
3373 * Re-formats the certificate date (Date.toString()) string to
3374 * a properly localized date string.
3375 * @return Properly localized version of the certificate date string and
3376 * the original certificate date string if fails to localize.
3377 * If the original string is null, returns an empty string "".
3378 */
3379 private String reformatCertificateDate(String certificateDate) {
3380 String reformattedDate = null;
3381
3382 if (certificateDate != null) {
3383 Date date = null;
3384 try {
3385 date = java.text.DateFormat.getInstance().parse(certificateDate);
3386 } catch (ParseException e) {
3387 date = null;
3388 }
3389
3390 if (date != null) {
3391 reformattedDate =
3392 DateFormat.getDateFormat(this).format(date);
3393 }
3394 }
3395
3396 return reformattedDate != null ? reformattedDate :
3397 (certificateDate != null ? certificateDate : "");
3398 }
3399
3400 /**
3401 * Displays an http-authentication dialog.
3402 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003403 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003404 final String host, final String realm, final String title,
3405 final String name, final String password, int focusId) {
3406 LayoutInflater factory = LayoutInflater.from(this);
3407 final View v = factory
3408 .inflate(R.layout.http_authentication, null);
3409 if (name != null) {
3410 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3411 }
3412 if (password != null) {
3413 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3414 }
3415
3416 String titleText = title;
3417 if (titleText == null) {
3418 titleText = getText(R.string.sign_in_to).toString().replace(
3419 "%s1", host).replace("%s2", realm);
3420 }
3421
3422 mHttpAuthHandler = handler;
3423 AlertDialog dialog = new AlertDialog.Builder(this)
3424 .setTitle(titleText)
3425 .setIcon(android.R.drawable.ic_dialog_alert)
3426 .setView(v)
3427 .setPositiveButton(R.string.action,
3428 new DialogInterface.OnClickListener() {
3429 public void onClick(DialogInterface dialog,
3430 int whichButton) {
3431 String nm = ((EditText) v
3432 .findViewById(R.id.username_edit))
3433 .getText().toString();
3434 String pw = ((EditText) v
3435 .findViewById(R.id.password_edit))
3436 .getText().toString();
3437 BrowserActivity.this.setHttpAuthUsernamePassword
3438 (host, realm, nm, pw);
3439 handler.proceed(nm, pw);
3440 mHttpAuthenticationDialog = null;
3441 mHttpAuthHandler = null;
3442 }})
3443 .setNegativeButton(R.string.cancel,
3444 new DialogInterface.OnClickListener() {
3445 public void onClick(DialogInterface dialog,
3446 int whichButton) {
3447 handler.cancel();
3448 BrowserActivity.this.resetTitleAndRevertLockIcon();
3449 mHttpAuthenticationDialog = null;
3450 mHttpAuthHandler = null;
3451 }})
3452 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3453 public void onCancel(DialogInterface dialog) {
3454 handler.cancel();
3455 BrowserActivity.this.resetTitleAndRevertLockIcon();
3456 mHttpAuthenticationDialog = null;
3457 mHttpAuthHandler = null;
3458 }})
3459 .create();
3460 // Make the IME appear when the dialog is displayed if applicable.
3461 dialog.getWindow().setSoftInputMode(
3462 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3463 dialog.show();
3464 if (focusId != 0) {
3465 dialog.findViewById(focusId).requestFocus();
3466 } else {
3467 v.findViewById(R.id.username_edit).requestFocus();
3468 }
3469 mHttpAuthenticationDialog = dialog;
3470 }
3471
3472 public int getProgress() {
3473 WebView w = mTabControl.getCurrentWebView();
3474 if (w != null) {
3475 return w.getProgress();
3476 } else {
3477 return 100;
3478 }
3479 }
3480
3481 /**
3482 * Set HTTP authentication password.
3483 *
3484 * @param host The host for the password
3485 * @param realm The realm for the password
3486 * @param username The username for the password. If it is null, it means
3487 * password can't be saved.
3488 * @param password The password
3489 */
3490 public void setHttpAuthUsernamePassword(String host, String realm,
3491 String username,
3492 String password) {
3493 WebView w = mTabControl.getCurrentWebView();
3494 if (w != null) {
3495 w.setHttpAuthUsernamePassword(host, realm, username, password);
3496 }
3497 }
3498
3499 /**
3500 * connectivity manager says net has come or gone... inform the user
3501 * @param up true if net has come up, false if net has gone down
3502 */
3503 public void onNetworkToggle(boolean up) {
3504 if (up == mIsNetworkUp) {
3505 return;
3506 } else if (up) {
3507 mIsNetworkUp = true;
3508 if (mAlertDialog != null) {
3509 mAlertDialog.cancel();
3510 mAlertDialog = null;
3511 }
3512 } else {
3513 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003514 if (mInLoad) {
3515 createAndShowNetworkDialog();
3516 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003517 }
3518 WebView w = mTabControl.getCurrentWebView();
3519 if (w != null) {
3520 w.setNetworkAvailable(up);
3521 }
3522 }
3523
Grace Kloba22ac16e2009-10-07 18:00:23 -07003524 boolean isNetworkUp() {
3525 return mIsNetworkUp;
3526 }
3527
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003528 // This method shows the network dialog alerting the user that the net is
3529 // down. It will only show the dialog if mAlertDialog is null.
3530 private void createAndShowNetworkDialog() {
3531 if (mAlertDialog == null) {
3532 mAlertDialog = new AlertDialog.Builder(this)
3533 .setTitle(R.string.loadSuspendedTitle)
3534 .setMessage(R.string.loadSuspended)
3535 .setPositiveButton(R.string.ok, null)
3536 .show();
3537 }
3538 }
3539
The Android Open Source Project0c908882009-03-03 19:32:16 -08003540 @Override
3541 protected void onActivityResult(int requestCode, int resultCode,
3542 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003543 if (getTopWindow() == null) return;
3544
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545 switch (requestCode) {
3546 case COMBO_PAGE:
3547 if (resultCode == RESULT_OK && intent != null) {
3548 String data = intent.getAction();
3549 Bundle extras = intent.getExtras();
3550 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003551 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003553 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003555 dismissSubWindow(currentTab);
3556 if (data != null && data.length() != 0) {
3557 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 }
3559 }
3560 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003561 // Deliberately fall through to PREFERENCES_PAGE, since the
3562 // same extra may be attached to the COMBO_PAGE
3563 case PREFERENCES_PAGE:
3564 if (resultCode == RESULT_OK && intent != null) {
3565 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3566 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3567 mTabControl.removeParentChildRelationShips();
3568 }
3569 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003571 // Choose a file from the file picker.
3572 case FILE_SELECTED:
3573 if (null == mUploadMessage) break;
3574 Uri result = intent == null || resultCode != RESULT_OK ? null
3575 : intent.getData();
3576 mUploadMessage.onReceiveValue(result);
3577 mUploadMessage = null;
3578 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003579 default:
3580 break;
3581 }
Leon Scroggins30444232009-09-04 18:36:20 -04003582 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 }
3584
3585 /*
3586 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003587 * menu to see the download window. It shows the download window on top of
3588 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003589 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003590 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 Intent intent = new Intent(this,
3592 BrowserDownloadPage.class);
3593 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003594 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595
3596 }
3597
Leon Scroggins160a7e72009-08-14 18:28:01 -04003598 /**
3599 * Open the Go page.
3600 * @param startWithHistory If true, open starting on the history tab.
3601 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003602 */
Leon Scroggins30444232009-09-04 18:36:20 -04003603 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003604 WebView current = mTabControl.getCurrentWebView();
3605 if (current == null) {
3606 return;
3607 }
3608 Intent intent = new Intent(this,
3609 CombinedBookmarkHistoryActivity.class);
3610 String title = current.getTitle();
3611 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003612 Bitmap thumbnail = createScreenshot(current);
3613
The Android Open Source Project0c908882009-03-03 19:32:16 -08003614 // Just in case the user opens bookmarks before a page finishes loading
3615 // so the current history item, and therefore the page, is null.
3616 if (null == url) {
3617 url = mLastEnteredUrl;
3618 // This can happen.
3619 if (null == url) {
3620 url = mSettings.getHomePage();
3621 }
3622 }
3623 // In case the web page has not yet received its associated title.
3624 if (title == null) {
3625 title = url;
3626 }
3627 intent.putExtra("title", title);
3628 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003629 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003630 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003631 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003632 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 if (startWithHistory) {
3634 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3635 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3636 }
3637 startActivityForResult(intent, COMBO_PAGE);
3638 }
3639
3640 // Called when loading from context menu or LOAD_URL message
3641 private void loadURL(WebView view, String url) {
3642 // In case the user enters nothing.
3643 if (url != null && url.length() != 0 && view != null) {
3644 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003645 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003646 view.loadUrl(url);
3647 }
3648 }
3649 }
3650
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 private String smartUrlFilter(Uri inUri) {
3652 if (inUri != null) {
3653 return smartUrlFilter(inUri.toString());
3654 }
3655 return null;
3656 }
3657
Feng Qianb34f87a2009-03-24 21:27:26 -07003658 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 "(?i)" + // switch on case insensitive matching
3660 "(" + // begin group for schema
3661 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003662 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003663 ")" +
3664 "(.*)" );
3665
3666 /**
3667 * Attempts to determine whether user input is a URL or search
3668 * terms. Anything with a space is passed to search.
3669 *
3670 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3671 * "Http://" converts to "http://"
3672 *
3673 * @return Original or modified URL
3674 *
3675 */
3676 String smartUrlFilter(String url) {
3677
3678 String inUrl = url.trim();
3679 boolean hasSpace = inUrl.indexOf(' ') != -1;
3680
3681 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3682 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003683 // force scheme to lowercase
3684 String scheme = matcher.group(1);
3685 String lcScheme = scheme.toLowerCase();
3686 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003687 inUrl = lcScheme + matcher.group(2);
3688 }
3689 if (hasSpace) {
3690 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003691 }
3692 return inUrl;
3693 }
3694 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003695 // FIXME: Is this the correct place to add to searches?
3696 // what if someone else calls this function?
3697 int shortcut = parseUrlShortcut(inUrl);
3698 if (shortcut != SHORTCUT_INVALID) {
3699 Browser.addSearchUrl(mResolver, inUrl);
3700 String query = inUrl.substring(2);
3701 switch (shortcut) {
3702 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003703 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003704 case SHORTCUT_WIKIPEDIA_SEARCH:
3705 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3706 case SHORTCUT_DICTIONARY_SEARCH:
3707 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3708 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003709 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003710 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003711 }
3712 }
3713 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003714 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003715 return URLUtil.guessUrl(inUrl);
3716 }
3717 }
3718
3719 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003720 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003721 }
3722
Ben Murdochbff2d602009-07-01 20:19:05 +01003723 /* package */ void setShouldShowErrorConsole(boolean flag) {
3724 if (flag == mShouldShowErrorConsole) {
3725 // Nothing to do.
3726 return;
3727 }
3728
3729 mShouldShowErrorConsole = flag;
3730
Grace Kloba22ac16e2009-10-07 18:00:23 -07003731 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3732 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003733
3734 if (flag) {
3735 // Setting the show state of the console will cause it's the layout to be inflated.
3736 if (errorConsole.numberOfErrors() > 0) {
3737 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3738 } else {
3739 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3740 }
3741
3742 // Now we can add it to the main view.
3743 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003744 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003745 ViewGroup.LayoutParams.WRAP_CONTENT));
3746 } else {
3747 mErrorConsoleContainer.removeView(errorConsole);
3748 }
3749
3750 }
3751
Grace Kloba22ac16e2009-10-07 18:00:23 -07003752 boolean shouldShowErrorConsole() {
3753 return mShouldShowErrorConsole;
3754 }
3755
Andrei Popescu163ab742009-10-20 17:58:23 +01003756 private void setStatusBarVisibility(boolean visible) {
3757 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3758 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3759 }
3760
Andrei Popescu56199cc2010-01-12 22:39:16 +00003761
3762 private void sendNetworkType(String type, String subtype) {
3763 WebView w = mTabControl.getCurrentWebView();
3764 if (w != null) {
3765 w.setNetworkType(type, subtype);
3766 }
3767 }
3768
Grace Klobaeb6eef42009-09-15 17:56:32 -07003769 final static int LOCK_ICON_UNSECURE = 0;
3770 final static int LOCK_ICON_SECURE = 1;
3771 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003772
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773 private BrowserSettings mSettings;
3774 private TabControl mTabControl;
3775 private ContentResolver mResolver;
3776 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003777 private View mCustomView;
3778 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003779 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003780
3781 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3782 // view, we should rewrite this.
3783 private int mCurrentMenuState = 0;
3784 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003785 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003786 private static final int EMPTY_MENU = -1;
3787 private Menu mMenu;
3788
3789 private FindDialog mFindDialog;
3790 // Used to prevent chording to result in firing two shortcuts immediately
3791 // one after another. Fixes bug 1211714.
3792 boolean mCanChord;
3793
3794 private boolean mInLoad;
3795 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003796 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003797
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798 private boolean mActivityInPause = true;
3799
3800 private boolean mMenuIsDown;
3801
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 private static boolean mInTrace;
3803
3804 // Performance probe
3805 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3806 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3807 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3808 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3809 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3810 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3811 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3812 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3813 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3814 };
3815
3816 private long mStart;
3817 private long mProcessStart;
3818 private long mUserStart;
3819 private long mSystemStart;
3820 private long mIdleStart;
3821 private long mIrqStart;
3822
3823 private long mUiStart;
3824
3825 private Drawable mMixLockIcon;
3826 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003827
3828 /* hold a ref so we can auto-cancel if necessary */
3829 private AlertDialog mAlertDialog;
3830
3831 // Wait for credentials before loading google.com
3832 private ProgressDialog mCredsDlg;
3833
3834 // The up-to-date URL and title (these can be different from those stored
3835 // in WebView, since it takes some time for the information in WebView to
3836 // get updated)
3837 private String mUrl;
3838 private String mTitle;
3839
3840 // As PageInfo has different style for landscape / portrait, we have
3841 // to re-open it when configuration changed
3842 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003843 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003844 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3845 // dialog, we should not just dismiss it, but should get back to the
3846 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003847 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003848
3849 // as SSLCertificateOnError has different style for landscape / portrait,
3850 // we have to re-open it when configuration changed
3851 private AlertDialog mSSLCertificateOnErrorDialog;
3852 private WebView mSSLCertificateOnErrorView;
3853 private SslErrorHandler mSSLCertificateOnErrorHandler;
3854 private SslError mSSLCertificateOnErrorError;
3855
3856 // as SSLCertificate has different style for landscape / portrait, we
3857 // have to re-open it when configuration changed
3858 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003859 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003860
3861 // as HttpAuthentication has different style for landscape / portrait, we
3862 // have to re-open it when configuration changed
3863 private AlertDialog mHttpAuthenticationDialog;
3864 private HttpAuthHandler mHttpAuthHandler;
3865
3866 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3867 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003868 ViewGroup.LayoutParams.MATCH_PARENT,
3869 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003870 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3871 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003872 ViewGroup.LayoutParams.MATCH_PARENT,
3873 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003874 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003875 // Google search
3876 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003877 // Wikipedia search
3878 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3879 // Dictionary search
3880 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3881 // Google Mobile Local search
3882 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3883
3884 final static String QUERY_PLACE_HOLDER = "%s";
3885
3886 // "source" parameter for Google search through search key
3887 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3888 // "source" parameter for Google search through goto menu
3889 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3890 // "source" parameter for Google search through simplily type
3891 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3892 // "source" parameter for Google search suggested by the browser
3893 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3894 // "source" parameter for Google search from unknown source
3895 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3896
3897 private final static String LOGTAG = "browser";
3898
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 private String mLastEnteredUrl;
3900
3901 private PowerManager.WakeLock mWakeLock;
3902 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3903
3904 private Toast mStopToast;
3905
Leon Scroggins68579392009-09-15 15:31:54 -04003906 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003907
Ben Murdochbff2d602009-07-01 20:19:05 +01003908 private LinearLayout mErrorConsoleContainer = null;
3909 private boolean mShouldShowErrorConsole = false;
3910
The Android Open Source Project0c908882009-03-03 19:32:16 -08003911 // As the ids are dynamically created, we can't guarantee that they will
3912 // be in sequence, so this static array maps ids to a window number.
3913 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3914 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3915 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3916 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3917
3918 // monitor platform changes
3919 private IntentFilter mNetworkStateChangedFilter;
3920 private BroadcastReceiver mNetworkStateIntentReceiver;
3921
Grace Klobab4da0ad2009-05-14 14:45:40 -07003922 private BroadcastReceiver mPackageInstallationReceiver;
3923
The Android Open Source Project0c908882009-03-03 19:32:16 -08003924 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003925 final static int COMBO_PAGE = 1;
3926 final static int DOWNLOAD_PAGE = 2;
3927 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003928 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003929
Andrei Popescu540035d2009-09-18 18:59:20 +01003930 // the default <video> poster
3931 private Bitmap mDefaultVideoPoster;
3932 // the video progress view
3933 private View mVideoProgressView;
3934
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003935 /**
3936 * A UrlData class to abstract how the content will be set to WebView.
3937 * This base class uses loadUrl to show the content.
3938 */
3939 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003940 final String mUrl;
3941 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003942 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003943
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003944 UrlData(String url) {
3945 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003946 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003947 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003948 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003949
Leon Scroggins58d56c62010-01-28 15:12:40 -05003950 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003951 this.mUrl = url;
3952 this.mHeaders = headers;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003953 if (Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(
3954 intent.getAction())) {
3955 this.mVoiceIntent = intent;
3956 } else {
3957 this.mVoiceIntent = null;
3958 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003959 }
3960
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003961 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003962 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003963 }
3964
Leon Scroggins58d56c62010-01-28 15:12:40 -05003965 public void loadIn(Tab t) {
3966 if (mVoiceIntent != null) {
3967 t.activateVoiceSearchMode(mVoiceIntent);
3968 } else {
3969 t.getWebView().loadUrl(mUrl, mHeaders);
3970 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003971 }
3972 };
3973
Leon Scroggins1f005d32009-08-10 17:36:42 -04003974 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003975}