blob: ebb52461ab183a494b7b02af63229f3c442e2dd4 [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
76import android.view.ContextMenu;
77import android.view.Gravity;
78import android.view.KeyEvent;
79import android.view.LayoutInflater;
80import android.view.Menu;
81import android.view.MenuInflater;
82import android.view.MenuItem;
83import android.view.View;
84import android.view.ViewGroup;
85import android.view.Window;
86import android.view.WindowManager;
87import android.view.ContextMenu.ContextMenuInfo;
88import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.webkit.CookieManager;
90import android.webkit.CookieSyncManager;
91import android.webkit.DownloadListener;
92import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070093import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.SslErrorHandler;
95import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010096import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080097import android.webkit.WebChromeClient;
98import android.webkit.WebHistoryItem;
99import android.webkit.WebIconDatabase;
100import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800101import android.widget.EditText;
102import android.widget.FrameLayout;
103import android.widget.LinearLayout;
104import android.widget.TextView;
105import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800106import android.accounts.Account;
107import android.accounts.AccountManager;
108import android.accounts.AccountManagerFuture;
109import android.accounts.AuthenticatorException;
110import android.accounts.OperationCanceledException;
111import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800112
Dan Egnor5ee906c2009-11-18 12:11:49 -0800113import com.android.common.Patterns;
114
Doug Zongker716d4f52010-01-21 14:35:23 -0800115import com.google.android.gsf.GoogleLoginServiceConstants;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800116
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400117import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000119import java.io.IOException;
120import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.MalformedURLException;
122import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700123import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.net.URL;
125import java.net.URLEncoder;
126import java.text.ParseException;
127import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128import java.util.HashMap;
Grace Kloba00f54c52010-01-27 14:53:51 -0800129import java.util.Iterator;
Grace Kloba068e48b2010-01-26 18:11:27 -0800130import java.util.Map;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800131import java.util.regex.Matcher;
132import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800133
134public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800135 implements View.OnCreateContextMenuListener, DownloadListener,
136 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137
Dave Bort31a6d1c2009-04-13 15:56:49 -0700138 /* Define some aliases to make these debugging flags easier to refer to.
139 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
140 */
141 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
142 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
143 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
144
Satish Sampath565505b2009-05-29 15:37:27 +0100145 // These are single-character shortcuts for searching popular sources.
146 private static final int SHORTCUT_INVALID = 0;
147 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
148 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
149 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
150 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
151
Fred Quintana752b6562009-12-18 10:18:26 -0800152 private Account[] mAccountsGoogle;
153 private Account[] mAccountsPreferHosted;
154
155 private void startReadOfGoogleAccounts() {
156 mAccountsGoogle = null;
157 mAccountsPreferHosted = null;
158
159 AccountManager.get(this).getAccountsByTypeAndFeatures(
160 GoogleLoginServiceConstants.ACCOUNT_TYPE,
161 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
162 this, null);
163 }
164
165 /** This implements AccountManagerCallback<Account[]> */
166 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
167 try {
168 if (mAccountsGoogle == null) {
169 mAccountsGoogle = accountManagerFuture.getResult();
170
171 AccountManager.get(this).getAccountsByTypeAndFeatures(
172 GoogleLoginServiceConstants.ACCOUNT_TYPE,
173 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
174 this, null);
175 } else {
176 mAccountsPreferHosted = accountManagerFuture.getResult();
177 setupHomePage();
178 }
179 } catch (OperationCanceledException e) {
180 setupHomePage();
181 } catch (IOException e) {
182 setupHomePage();
183 } catch (AuthenticatorException e) {
184 setupHomePage();
185 }
186 }
187
The Android Open Source Project0c908882009-03-03 19:32:16 -0800188 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800189 // get the default home page
190 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800191
Fred Quintana752b6562009-12-18 10:18:26 -0800192 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
193 // three cases:
194 //
195 // hostedUser == googleUser
196 // The device has only a google account
197 //
198 // hostedUser != googleUser
199 // The device has a hosted account and a google account
200 //
201 // hostedUser != null, googleUser == null
202 // The device has only a hosted account (so far)
203 String hostedUser = mAccountsPreferHosted.length == 0
204 ? null
205 : mAccountsPreferHosted[0].name;
206 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207
Fred Quintana752b6562009-12-18 10:18:26 -0800208 // developers might have no accounts at all
209 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700210
Fred Quintana752b6562009-12-18 10:18:26 -0800211 if (googleUser == null || !hostedUser.equals(googleUser)) {
212 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
213 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800214 }
Fred Quintana752b6562009-12-18 10:18:26 -0800215 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800216
Fred Quintana752b6562009-12-18 10:18:26 -0800217 mSettings.setHomePage(BrowserActivity.this, homepage);
218 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800219 }
220
Cary Clarka9771242009-08-11 16:42:26 -0400221 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800222 @Override
223 public Void doInBackground(File... files) {
224 if (files != null) {
225 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400226 if (!f.delete()) {
227 Log.e(LOGTAG, f.getPath() + " was not deleted");
228 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800229 }
230 }
231 return null;
232 }
233 }
234
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400235 /**
236 * This layout holds everything you see below the status bar, including the
237 * error console, the custom view container, and the webviews.
238 */
239 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400240
Grace Kloba22ac16e2009-10-07 18:00:23 -0700241 @Override
242 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700243 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800244 Log.v(LOGTAG, this + " onStart");
245 }
246 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800247 // test the browser in OpenGL
248 // requestWindowFeature(Window.FEATURE_OPENGL);
249
Mike Reedd334bf52010-01-26 15:21:44 -0500250 // enable this to test the browser in 32bit
251 if (false) {
252 getWindow().setFormat(PixelFormat.RGBX_8888);
253 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
254 }
255
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
257
258 mResolver = getContentResolver();
259
Grace Kloba0923d692009-09-23 21:37:25 -0700260 // If this was a web search request, pass it on to the default web
261 // search provider and finish this activity.
262 if (handleWebSearchIntent(getIntent())) {
263 finish();
264 return;
265 }
266
The Android Open Source Project0c908882009-03-03 19:32:16 -0800267 mSecLockIcon = Resources.getSystem().getDrawable(
268 android.R.drawable.ic_secure);
269 mMixLockIcon = Resources.getSystem().getDrawable(
270 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800271
Leon Scroggins81db3662009-06-04 17:45:11 -0400272 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
273 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400274 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
275 .inflate(R.layout.custom_screen, null);
276 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
277 R.id.main_content);
278 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
279 .findViewById(R.id.error_console);
280 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
281 .findViewById(R.id.fullscreen_custom_content);
282 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400283 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400284 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800285
286 // Create the tab control and our initial tab
287 mTabControl = new TabControl(this);
288
289 // Open the icon database and retain all the bookmark urls for favicons
290 retainIconsOnStartup();
291
292 // Keep a settings instance handy.
293 mSettings = BrowserSettings.getInstance();
294 mSettings.setTabControl(mTabControl);
295 mSettings.loadFromDb(this);
296
297 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
298 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
299
Grace Klobaa34f6862009-07-31 16:28:17 -0700300 /* enables registration for changes in network status from
301 http stack */
302 mNetworkStateChangedFilter = new IntentFilter();
303 mNetworkStateChangedFilter.addAction(
304 ConnectivityManager.CONNECTIVITY_ACTION);
305 mNetworkStateIntentReceiver = new BroadcastReceiver() {
306 @Override
307 public void onReceive(Context context, Intent intent) {
308 if (intent.getAction().equals(
309 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700310 boolean noConnectivity = intent.getBooleanExtra(
311 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000312 if (!noConnectivity) {
313 NetworkInfo info = intent.getParcelableExtra(
314 ConnectivityManager.EXTRA_NETWORK_INFO);
315 String typeName = info.getTypeName();
316 String subtypeName = info.getSubtypeName();
317 sendNetworkType(typeName.toLowerCase(),
318 (subtypeName != null ? subtypeName.toLowerCase() : ""));
319 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700320 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700321 }
322 }
323 };
324
Grace Kloba615c6c92009-08-03 10:22:44 -0700325 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
326 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
327 filter.addDataScheme("package");
328 mPackageInstallationReceiver = new BroadcastReceiver() {
329 @Override
330 public void onReceive(Context context, Intent intent) {
331 final String action = intent.getAction();
332 final String packageName = intent.getData()
333 .getSchemeSpecificPart();
334 final boolean replacing = intent.getBooleanExtra(
335 Intent.EXTRA_REPLACING, false);
336 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
337 // if it is replacing, refreshPlugins() when adding
338 return;
339 }
340 PackageManager pm = BrowserActivity.this.getPackageManager();
341 PackageInfo pkgInfo = null;
342 try {
343 pkgInfo = pm.getPackageInfo(packageName,
344 PackageManager.GET_PERMISSIONS);
345 } catch (PackageManager.NameNotFoundException e) {
346 return;
347 }
348 if (pkgInfo != null) {
349 String permissions[] = pkgInfo.requestedPermissions;
350 if (permissions == null) {
351 return;
352 }
353 boolean permissionOk = false;
354 for (String permit : permissions) {
355 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
356 permissionOk = true;
357 break;
358 }
359 }
360 if (permissionOk) {
361 PluginManager.getInstance(BrowserActivity.this)
362 .refreshPlugins(
363 Intent.ACTION_PACKAGE_ADDED
364 .equals(action));
365 }
366 }
367 }
368 };
369 registerReceiver(mPackageInstallationReceiver, filter);
370
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 if (!mTabControl.restoreState(icicle)) {
372 // clear up the thumbnail directory if we can't restore the state as
373 // none of the files in the directory are referenced any more.
374 new ClearThumbnails().execute(
375 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700376 // there is no quit on Android. But if we can't restore the state,
377 // we can treat it as a new Browser, remove the old session cookies.
378 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800379 final Intent intent = getIntent();
380 final Bundle extra = intent.getExtras();
381 // Create an initial tab.
382 // If the intent is ACTION_VIEW and data is not null, the Browser is
383 // invoked to view the content by another application. In this case,
384 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 UrlData urlData = getUrlDataFromIntent(intent);
386
Leon Scroggins58d56c62010-01-28 15:12:40 -0500387 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700388 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500389 (Intent.ACTION_VIEW.equals(action) &&
390 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500391 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
392 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700393 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 attachTabToContentView(t);
396 WebView webView = t.getWebView();
397 if (extra != null) {
398 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
399 if (scale > 0 && scale <= 1000) {
400 webView.setInitialScale(scale);
401 }
402 }
403 // If we are not restoring from an icicle, then there is a high
404 // likely hood this is the first run. So, check to see if the
405 // homepage needs to be configured and copy any plugins from our
406 // asset directory to the data partition.
407 if ((extra == null || !extra.getBoolean("testing"))
408 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800409 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800411
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700412 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400413 if (mSettings.isLoginInitialized()) {
414 webView.loadUrl(mSettings.getHomePage());
415 } else {
416 waitForCredentials();
417 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800418 } else {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500419 urlData.loadIn(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 }
421 } else {
422 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400423 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800424 attachTabToContentView(mTabControl.getCurrentTab());
425 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700426
Feng Qianb3c02da2009-06-29 15:58:08 -0700427 // Read JavaScript flags if it exists.
428 String jsFlags = mSettings.getJsFlags();
429 if (jsFlags.trim().length() != 0) {
430 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
431 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800432 }
433
Leon Scroggins58d56c62010-01-28 15:12:40 -0500434 /**
435 * Feed the previously stored results strings to the BrowserProvider so that
436 * the SearchDialog will show them instead of the standard searches.
437 * @param result String to show on the editable line of the SearchDialog.
438 */
439 /* package */ void showVoiceSearchResults(String result) {
440 ContentProviderClient client = mResolver.acquireContentProviderClient(
441 Browser.BOOKMARKS_URI);
442 ContentProvider prov = client.getLocalContentProvider();
443 BrowserProvider bp = (BrowserProvider) prov;
444 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
445 client.release();
446
447 startSearch(result, false,
448 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
449 false);
450 }
451
The Android Open Source Project0c908882009-03-03 19:32:16 -0800452 @Override
453 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700454 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800455 // When a tab is closed on exit, the current tab index is set to -1.
456 // Reset before proceed as Browser requires the current tab to be set.
457 if (current == null) {
458 // Try to reset the tab in case the index was incorrect.
459 current = mTabControl.getTab(0);
460 if (current == null) {
461 // No tabs at all so just ignore this intent.
462 return;
463 }
464 mTabControl.setCurrentTab(current);
465 attachTabToContentView(current);
466 resetTitleAndIcon(current.getWebView());
467 }
468 final String action = intent.getAction();
469 final int flags = intent.getFlags();
470 if (Intent.ACTION_MAIN.equals(action) ||
471 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
472 // just resume the browser
473 return;
474 }
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500475 boolean activateVoiceSearch = RecognizerResultsIntent
476 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800477 if (Intent.ACTION_VIEW.equals(action)
478 || Intent.ACTION_SEARCH.equals(action)
479 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500480 || Intent.ACTION_WEB_SEARCH.equals(action)
481 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500482 if (current.isInVoiceSearchMode()) {
483 String title = current.getVoiceDisplayTitle();
484 if (title != null && title.equals(intent.getStringExtra(
485 SearchManager.QUERY))) {
486 // The user submitted the same search as the last voice
487 // search, so do nothing.
488 return;
489 }
490 }
Satish Sampath565505b2009-05-29 15:37:27 +0100491 // If this was a search request (e.g. search query directly typed into the address bar),
492 // pass it on to the default web search provider.
493 if (handleWebSearchIntent(intent)) {
494 return;
495 }
496
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700497 UrlData urlData = getUrlDataFromIntent(intent);
498 if (urlData.isEmpty()) {
499 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800500 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700501
Grace Klobacc634032009-07-28 15:58:19 -0700502 final String appId = intent
503 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500504 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
Grace Klobacc634032009-07-28 15:58:19 -0700505 && !getPackageName().equals(appId)
506 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700507 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700508 if (appTab != null) {
509 Log.i(LOGTAG, "Reusing tab for " + appId);
510 // Dismiss the subwindow if applicable.
511 dismissSubWindow(appTab);
512 // Since we might kill the WebView, remove it from the
513 // content view first.
514 removeTabFromContentView(appTab);
515 // Recreate the main WebView after destroying the old one.
516 // If the WebView has the same original url and is on that
517 // page, it can be reused.
518 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700519 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100520
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700521 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400522 switchToTab(mTabControl.getTabIndex(appTab));
523 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500524 urlData.loadIn(appTab);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400525 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700526 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400527 // If the tab was the current tab, we have to attach
528 // it to the view system again.
529 attachTabToContentView(appTab);
530 if (needsLoad) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500531 urlData.loadIn(appTab);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700532 }
533 }
534 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400535 } else {
536 // No matching application tab, try to find a regular tab
537 // with a matching url.
538 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400539 if (appTab != null) {
540 if (current != appTab) {
541 switchToTab(mTabControl.getTabIndex(appTab));
542 }
543 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400544 } else {
545 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
546 // will be opened in a new tab unless we have reached
547 // MAX_TABS. Then the url will be opened in the current
548 // tab. If a new tab is created, it will have "true" for
549 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400550 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400551 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700552 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800553 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800554 if (!urlData.isEmpty()
555 && urlData.mUrl.startsWith("about:debug")) {
556 if ("about:debug.dom".equals(urlData.mUrl)) {
557 current.getWebView().dumpDomTree(false);
558 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
559 current.getWebView().dumpDomTree(true);
560 } else if ("about:debug.render".equals(urlData.mUrl)) {
561 current.getWebView().dumpRenderTree(false);
562 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
563 current.getWebView().dumpRenderTree(true);
564 } else if ("about:debug.display".equals(urlData.mUrl)) {
565 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800566 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
567 int index = urlData.mUrl.codePointAt(16) - '0';
568 if (index <= 0 || index > 9) {
569 current.getWebView().setDragTracker(null);
570 } else {
571 current.getWebView().setDragTracker(new MeshTracker(index));
572 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800573 } else {
574 mSettings.toggleDebugSettings();
575 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800576 return;
577 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400578 // Get rid of the subwindow if it exists
579 dismissSubWindow(current);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500580 urlData.loadIn(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800581 }
582 }
583 }
584
Satish Sampath565505b2009-05-29 15:37:27 +0100585 private int parseUrlShortcut(String url) {
586 if (url == null) return SHORTCUT_INVALID;
587
588 // FIXME: quick search, need to be customized by setting
589 if (url.length() > 2 && url.charAt(1) == ' ') {
590 switch (url.charAt(0)) {
591 case 'g': return SHORTCUT_GOOGLE_SEARCH;
592 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
593 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
594 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
595 }
596 }
597 return SHORTCUT_INVALID;
598 }
599
600 /**
601 * Launches the default web search activity with the query parameters if the given intent's data
602 * are identified as plain search terms and not URLs/shortcuts.
603 * @return true if the intent was handled and web search activity was launched, false if not.
604 */
605 private boolean handleWebSearchIntent(Intent intent) {
606 if (intent == null) return false;
607
608 String url = null;
609 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500610 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
611 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500612 return false;
613 }
Satish Sampath565505b2009-05-29 15:37:27 +0100614 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700615 Uri data = intent.getData();
616 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100617 } else if (Intent.ACTION_SEARCH.equals(action)
618 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
619 || Intent.ACTION_WEB_SEARCH.equals(action)) {
620 url = intent.getStringExtra(SearchManager.QUERY);
621 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100622 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
623 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100624 }
625
626 /**
627 * Launches the default web search activity with the query parameters if the given url string
628 * was identified as plain search terms and not URL/shortcut.
629 * @return true if the request was handled and web search activity was launched, false if not.
630 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100631 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100632 if (inUrl == null) return false;
633
634 // In general, we shouldn't modify URL from Intent.
635 // But currently, we get the user-typed URL from search box as well.
636 String url = fixUrl(inUrl).trim();
637
638 // URLs and site specific search shortcuts are handled by the regular flow of control, so
639 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800640 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100641 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100642 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
643 return false;
644 }
645
646 Browser.updateVisitedHistory(mResolver, url, false);
647 Browser.addSearchUrl(mResolver, url);
648
649 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
650 intent.addCategory(Intent.CATEGORY_DEFAULT);
651 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100652 if (appData != null) {
653 intent.putExtra(SearchManager.APP_DATA, appData);
654 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100655 if (extraData != null) {
656 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
657 }
Grace Klobacc634032009-07-28 15:58:19 -0700658 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100659 startActivity(intent);
660
661 return true;
662 }
663
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700664 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500665 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800666 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800667 if (intent != null) {
668 final String action = intent.getAction();
669 if (Intent.ACTION_VIEW.equals(action)) {
670 url = smartUrlFilter(intent.getData());
671 if (url != null && url.startsWith("content:")) {
672 /* Append mimetype so webview knows how to display */
673 String mimeType = intent.resolveType(getContentResolver());
674 if (mimeType != null) {
675 url += "?" + mimeType;
676 }
677 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800678 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800679 final Bundle pairs = intent
680 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800681 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800682 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800683 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800684 while (iter.hasNext()) {
685 String key = iter.next();
686 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800687 }
688 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700689 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 } else if (Intent.ACTION_SEARCH.equals(action)
691 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
692 || Intent.ACTION_WEB_SEARCH.equals(action)) {
693 url = intent.getStringExtra(SearchManager.QUERY);
694 if (url != null) {
695 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500696 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 // In general, we shouldn't modify URL from Intent.
698 // But currently, we get the user-typed URL from search box as well.
699 url = fixUrl(url);
700 url = smartUrlFilter(url);
701 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
702 if (url.contains(searchSource)) {
703 String source = null;
704 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
705 if (appData != null) {
706 source = appData.getString(SearchManager.SOURCE);
707 }
708 if (TextUtils.isEmpty(source)) {
709 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
710 }
711 url = url.replace(searchSource, "&source=android-"+source+"&");
712 }
713 }
714 }
715 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500716 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800717 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500718 /* package */ void showVoiceTitleBar(String title) {
719 mTitleBar.setInVoiceMode(true);
720 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800721
Leon Scroggins58d56c62010-01-28 15:12:40 -0500722 mTitleBar.setDisplayTitle(title);
723 mFakeTitleBar.setDisplayTitle(title);
724 }
725 /* package */ void revertVoiceTitleBar() {
726 mTitleBar.setInVoiceMode(false);
727 mFakeTitleBar.setInVoiceMode(false);
728
729 mTitleBar.setDisplayTitle(mTitle);
730 mFakeTitleBar.setDisplayTitle(mTitle);
731 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400733 // FIXME: Converting the url to lower case
734 // duplicates functionality in smartUrlFilter().
735 // However, changing all current callers of fixUrl to
736 // call smartUrlFilter in addition may have unwanted
737 // consequences, and is deferred for now.
738 int colon = inUrl.indexOf(':');
739 boolean allLower = true;
740 for (int index = 0; index < colon; index++) {
741 char ch = inUrl.charAt(index);
742 if (!Character.isLetter(ch)) {
743 break;
744 }
745 allLower &= Character.isLowerCase(ch);
746 if (index == colon - 1 && !allLower) {
747 inUrl = inUrl.substring(0, colon).toLowerCase()
748 + inUrl.substring(colon);
749 }
750 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800751 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
752 return inUrl;
753 if (inUrl.startsWith("http:") ||
754 inUrl.startsWith("https:")) {
755 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
756 inUrl = inUrl.replaceFirst("/", "//");
757 } else inUrl = inUrl.replaceFirst(":", "://");
758 }
759 return inUrl;
760 }
761
Grace Kloba22ac16e2009-10-07 18:00:23 -0700762 @Override
763 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800764 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700765 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800766 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
767 }
768
769 if (!mActivityInPause) {
770 Log.e(LOGTAG, "BrowserActivity is already resumed.");
771 return;
772 }
773
Mike Reed7bfa63b2009-05-28 11:08:32 -0400774 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800775 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400776 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800777
778 if (mWakeLock.isHeld()) {
779 mHandler.removeMessages(RELEASE_WAKELOCK);
780 mWakeLock.release();
781 }
782
783 if (mCredsDlg != null) {
784 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
785 // In case credential request never comes back
786 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
787 }
788 }
789
790 registerReceiver(mNetworkStateIntentReceiver,
791 mNetworkStateChangedFilter);
792 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800793 }
794
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400795 /**
796 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400797 * would change its appearance, use a different TitleBar to show overlayed
798 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400799 */
800 private TitleBar mFakeTitleBar;
801
802 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400803 * Holder for the fake title bar. It will have a foreground shadow, as well
804 * as a white background, so the fake title bar looks like the real one.
805 */
806 private ViewGroup mFakeTitleBarHolder;
807
808 /**
809 * Layout parameters for the fake title bar within mFakeTitleBarHolder
810 */
811 private FrameLayout.LayoutParams mFakeTitleBarParams
812 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800813 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400814 ViewGroup.LayoutParams.WRAP_CONTENT);
815 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400816 * Keeps track of whether the options menu is open. This is important in
817 * determining whether to show or hide the title bar overlay.
818 */
819 private boolean mOptionsMenuOpen;
820
821 /**
822 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
823 * of whether the configuration has changed. The first onMenuOpened call
824 * after a configuration change is simply a reopening of the same menu
825 * (i.e. mIconView did not change).
826 */
827 private boolean mConfigChanged;
828
829 /**
830 * Whether or not the options menu is in its smaller, icon menu form. When
831 * true, we want the title bar overlay to be up. When false, we do not.
832 * Only meaningful if mOptionsMenuOpen is true.
833 */
834 private boolean mIconView;
835
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400836 @Override
837 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400838 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
839 if (mOptionsMenuOpen) {
840 if (mConfigChanged) {
841 // We do not need to make any changes to the state of the
842 // title bar, since the only thing that happened was a
843 // change in orientation
844 mConfigChanged = false;
845 } else {
846 if (mIconView) {
847 // Switching the menu to expanded view, so hide the
848 // title bar.
849 hideFakeTitleBar();
850 mIconView = false;
851 } else {
852 // Switching the menu back to icon view, so show the
853 // title bar once again.
854 showFakeTitleBar();
855 mIconView = true;
856 }
857 }
858 } else {
859 // The options menu is closed, so open it, and show the title
860 showFakeTitleBar();
861 mOptionsMenuOpen = true;
862 mConfigChanged = false;
863 mIconView = true;
864 }
865 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400866 return true;
867 }
868
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400869 /**
870 * Special class used exclusively for the shadow drawn underneath the fake
871 * title bar. The shadow does not need to be drawn if the WebView
872 * underneath is scrolled to the top, because it will draw directly on top
873 * of the embedded shadow.
874 */
875 private static class Shadow extends View {
876 private WebView mWebView;
877
878 public Shadow(Context context, AttributeSet attrs) {
879 super(context, attrs);
880 }
881
882 public void setWebView(WebView view) {
883 mWebView = view;
884 }
885
886 @Override
887 public void draw(Canvas canvas) {
888 // In general onDraw is the method to override, but we care about
889 // whether or not the background gets drawn, which happens in draw()
890 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
891 super.draw(canvas);
892 }
893 // Need to invalidate so that if the scroll position changes, we
894 // still draw as appropriate.
895 invalidate();
896 }
897 }
898
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400900 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400901 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400902 && !mActivityInPause && decor != null
903 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400904 Rect visRect = new Rect();
905 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
906 if (LOGD_ENABLED) {
907 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
908 }
909 return;
910 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400911
912 WindowManager manager
913 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
914
915 // Add the title bar to the window manager so it can receive touches
916 // while the menu is up
917 WindowManager.LayoutParams params
918 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800919 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400920 ViewGroup.LayoutParams.WRAP_CONTENT,
921 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
922 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400923 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400924 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400925 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400926 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400927 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400928 // XXX : Without providing an offset, the fake title bar will be
929 // placed underneath the status bar. Use the global visible rect
930 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400931 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400932 // Add a holder for the title bar. It also holds a shadow to show
933 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400934 if (mFakeTitleBarHolder == null) {
935 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
936 .inflate(R.layout.title_bar_bg, null);
937 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400938 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
939 R.id.shadow);
940 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400941 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400942 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400943 }
944 }
945
946 @Override
947 public void onOptionsMenuClosed(Menu menu) {
948 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400949 if (!mInLoad) {
950 hideFakeTitleBar();
951 } else if (!mIconView) {
952 // The page is currently loading, and we are in expanded mode, so
953 // we were not showing the menu. Show it once again. It will be
954 // removed when the page finishes.
955 showFakeTitleBar();
956 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400957 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700958
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400959 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400960 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400961 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
962 mFakeTitleBarHolder.getLayoutParams();
963 WebView mainView = mTabControl.getCurrentWebView();
964 // Although we decided whether or not to animate based on the current
965 // scroll position, the scroll position may have changed since the
966 // fake title bar was displayed. Make sure it has the appropriate
967 // animation/lack thereof before removing.
968 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400969 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400970 WindowManager manager
971 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400972 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400973 mFakeTitleBarHolder.removeView(mFakeTitleBar);
974 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400975 }
976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400978 * Special method for the fake title bar to call when displaying its context
979 * menu, since it is in its own Window, and its parent does not show a
980 * context menu.
981 */
982 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400983 if (null == mTitleBar.getParent()) {
984 return;
985 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400986 openContextMenu(mTitleBar);
987 }
988
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400989 @Override
990 public void onContextMenuClosed(Menu menu) {
991 super.onContextMenuClosed(menu);
992 if (mInLoad) {
993 showFakeTitleBar();
994 }
995 }
996
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400997 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 * onSaveInstanceState(Bundle map)
999 * onSaveInstanceState is called right before onStop(). The map contains
1000 * the saved state.
1001 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 @Override
1003 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001004 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001005 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1006 }
1007 // the default implementation requires each view to have an id. As the
1008 // browser handles the state itself and it doesn't use id for the views,
1009 // don't call the default implementation. Otherwise it will trigger the
1010 // warning like this, "couldn't save which view has focus because the
1011 // focused view XXX has no id".
1012
1013 // Save all the tabs
1014 mTabControl.saveState(outState);
1015 }
1016
Grace Kloba22ac16e2009-10-07 18:00:23 -07001017 @Override
1018 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001019 super.onPause();
1020
1021 if (mActivityInPause) {
1022 Log.e(LOGTAG, "BrowserActivity is already paused.");
1023 return;
1024 }
1025
Mike Reed7bfa63b2009-05-28 11:08:32 -04001026 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001028 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001029 mWakeLock.acquire();
1030 mHandler.sendMessageDelayed(mHandler
1031 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1032 }
1033
1034 // Clear the credentials toast if it is up
1035 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1036 mCredsDlg.dismiss();
1037 }
1038 mCredsDlg = null;
1039
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -04001040 // FIXME: This removes the active tabs page and resets the menu to
1041 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1042 // but then we would need to save it in onSaveInstanceState and restore
1043 // it in onCreate/onRestoreInstanceState
1044 if (mActiveTabsPage != null) {
1045 removeActiveTabPage(true);
1046 }
1047
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 cancelStopToast();
1049
1050 // unregister network state listener
1051 unregisterReceiver(mNetworkStateIntentReceiver);
1052 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001053 }
1054
Grace Kloba22ac16e2009-10-07 18:00:23 -07001055 @Override
1056 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001057 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1059 }
1060 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001061
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001062 if (mUploadMessage != null) {
1063 mUploadMessage.onReceiveValue(null);
1064 mUploadMessage = null;
1065 }
1066
Grace Kloba0923d692009-09-23 21:37:25 -07001067 if (mTabControl == null) return;
1068
Grace Kloba1fc98a32009-10-21 13:23:08 -07001069 // Remove the fake title bar if it is there
1070 hideFakeTitleBar();
1071
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001073 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001074 if (t != null) {
1075 dismissSubWindow(t);
1076 removeTabFromContentView(t);
1077 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 // Destroy all the tabs
1079 mTabControl.destroy();
1080 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081
Grace Klobab4da0ad2009-05-14 14:45:40 -07001082 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 }
1084
1085 @Override
1086 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001087 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 super.onConfigurationChanged(newConfig);
1089
1090 if (mPageInfoDialog != null) {
1091 mPageInfoDialog.dismiss();
1092 showPageInfo(
1093 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001094 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001095 }
1096 if (mSSLCertificateDialog != null) {
1097 mSSLCertificateDialog.dismiss();
1098 showSSLCertificate(
1099 mSSLCertificateView);
1100 }
1101 if (mSSLCertificateOnErrorDialog != null) {
1102 mSSLCertificateOnErrorDialog.dismiss();
1103 showSSLCertificateOnError(
1104 mSSLCertificateOnErrorView,
1105 mSSLCertificateOnErrorHandler,
1106 mSSLCertificateOnErrorError);
1107 }
1108 if (mHttpAuthenticationDialog != null) {
1109 String title = ((TextView) mHttpAuthenticationDialog
1110 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1111 .toString();
1112 String name = ((TextView) mHttpAuthenticationDialog
1113 .findViewById(R.id.username_edit)).getText().toString();
1114 String password = ((TextView) mHttpAuthenticationDialog
1115 .findViewById(R.id.password_edit)).getText().toString();
1116 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1117 .getId();
1118 mHttpAuthenticationDialog.dismiss();
1119 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1120 name, password, focusId);
1121 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001122 }
1123
Grace Kloba22ac16e2009-10-07 18:00:23 -07001124 @Override
1125 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001126 super.onLowMemory();
1127 mTabControl.freeMemory();
1128 }
1129
Mike Reed7bfa63b2009-05-28 11:08:32 -04001130 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001131 Tab tab = mTabControl.getCurrentTab();
1132 boolean inLoad = tab.inLoad();
1133 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001134 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001135 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001136 if (w != null) {
1137 w.resumeTimers();
1138 }
1139 return true;
1140 } else {
1141 return false;
1142 }
1143 }
1144
Mike Reed7bfa63b2009-05-28 11:08:32 -04001145 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001146 Tab tab = mTabControl.getCurrentTab();
1147 boolean inLoad = tab.inLoad();
1148 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001149 CookieSyncManager.getInstance().stopSync();
1150 WebView w = mTabControl.getCurrentWebView();
1151 if (w != null) {
1152 w.pauseTimers();
1153 }
1154 return true;
1155 } else {
1156 return false;
1157 }
1158 }
1159
Leon Scroggins1f005d32009-08-10 17:36:42 -04001160 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 /*
1162 * This function is called when we are launching for the first time. We
1163 * are waiting for the login credentials before loading Google home
1164 * pages. This way the user will be logged in straight away.
1165 */
1166 private void waitForCredentials() {
1167 // Show a toast
1168 mCredsDlg = new ProgressDialog(this);
1169 mCredsDlg.setIndeterminate(true);
1170 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1171 // If the user cancels the operation, then cancel the Google
1172 // Credentials request.
1173 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1174 mCredsDlg.show();
1175
1176 // We set a timeout for the retrieval of credentials in onResume()
1177 // as that is when we have freed up some CPU time to get
1178 // the login credentials.
1179 }
1180
1181 /*
1182 * If we have received the credentials or we have timed out and we are
1183 * showing the credentials dialog, then it is time to move on.
1184 */
1185 private void resumeAfterCredentials() {
1186 if (mCredsDlg == null) {
1187 return;
1188 }
1189
1190 // Clear the toast
1191 if (mCredsDlg.isShowing()) {
1192 mCredsDlg.dismiss();
1193 }
1194 mCredsDlg = null;
1195
1196 // Clear any pending timeout
1197 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1198
1199 // Load the page
1200 WebView w = mTabControl.getCurrentWebView();
1201 if (w != null) {
1202 w.loadUrl(mSettings.getHomePage());
1203 }
1204
1205 // Update the settings, need to do this last as it can take a moment
1206 // to persist the settings. In the mean time we could be loading
1207 // content.
1208 mSettings.setLoginInitialized(this);
1209 }
1210
1211 // Open the icon database and retain all the icons for visited sites.
1212 private void retainIconsOnStartup() {
1213 final WebIconDatabase db = WebIconDatabase.getInstance();
1214 db.open(getDir("icons", 0).getPath());
1215 try {
1216 Cursor c = Browser.getAllBookmarks(mResolver);
1217 if (!c.moveToFirst()) {
1218 c.deactivate();
1219 return;
1220 }
1221 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1222 do {
1223 String url = c.getString(urlIndex);
1224 db.retainIconForPageUrl(url);
1225 } while (c.moveToNext());
1226 c.deactivate();
1227 } catch (IllegalStateException e) {
1228 Log.e(LOGTAG, "retainIconsOnStartup", e);
1229 }
1230 }
1231
1232 // Helper method for getting the top window.
1233 WebView getTopWindow() {
1234 return mTabControl.getCurrentTopWebView();
1235 }
1236
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 TabControl getTabControl() {
1238 return mTabControl;
1239 }
1240
The Android Open Source Project0c908882009-03-03 19:32:16 -08001241 @Override
1242 public boolean onCreateOptionsMenu(Menu menu) {
1243 super.onCreateOptionsMenu(menu);
1244
1245 MenuInflater inflater = getMenuInflater();
1246 inflater.inflate(R.menu.browser, menu);
1247 mMenu = menu;
1248 updateInLoadMenuItems();
1249 return true;
1250 }
1251
1252 /**
1253 * As the menu can be open when loading state changes
1254 * we must manually update the state of the stop/reload menu
1255 * item
1256 */
1257 private void updateInLoadMenuItems() {
1258 if (mMenu == null) {
1259 return;
1260 }
1261 MenuItem src = mInLoad ?
1262 mMenu.findItem(R.id.stop_menu_id):
1263 mMenu.findItem(R.id.reload_menu_id);
1264 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1265 dest.setIcon(src.getIcon());
1266 dest.setTitle(src.getTitle());
1267 }
1268
1269 @Override
1270 public boolean onContextItemSelected(MenuItem item) {
1271 // chording is not an issue with context menus, but we use the same
1272 // options selector, so set mCanChord to true so we can access them.
1273 mCanChord = true;
1274 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001275 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001276 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001277 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001278 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001279 Tab currentTab = mTabControl.getCurrentTab();
1280 if (null == currentTab) {
1281 result = false;
1282 break;
1283 }
1284 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001285 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001286 result = false;
1287 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001288 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001289 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001290 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001291 // -- Browser context menu
1292 case R.id.open_context_menu_id:
1293 case R.id.open_newtab_context_menu_id:
1294 case R.id.bookmark_context_menu_id:
1295 case R.id.save_link_context_menu_id:
1296 case R.id.share_link_context_menu_id:
1297 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001298 final WebView webView = getTopWindow();
1299 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001300 result = false;
1301 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001302 }
1303 final HashMap hrefMap = new HashMap();
1304 hrefMap.put("webview", webView);
1305 final Message msg = mHandler.obtainMessage(
1306 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001307 webView.requestFocusNodeHref(msg);
1308 break;
1309
1310 default:
1311 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001312 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001313 }
1314 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001315 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 }
1317
1318 private Bundle createGoogleSearchSourceBundle(String source) {
1319 Bundle bundle = new Bundle();
1320 bundle.putString(SearchManager.SOURCE, source);
1321 return bundle;
1322 }
1323
1324 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001325 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001326 */
1327 @Override
1328 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001329 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001330 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001331 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001332 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001333 return true;
1334 }
1335
1336 @Override
1337 public void startSearch(String initialQuery, boolean selectInitialQuery,
1338 Bundle appSearchData, boolean globalSearch) {
1339 if (appSearchData == null) {
1340 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1341 }
1342 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1343 }
1344
Leon Scroggins1f005d32009-08-10 17:36:42 -04001345 /**
1346 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1347 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001348 * @param index Index of the tab to change to, as defined by
1349 * mTabControl.getTabIndex(Tab t).
1350 * @return boolean True if we successfully switched to a different tab. If
1351 * the indexth tab is null, or if that tab is the same as
1352 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001353 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001354 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001355 Tab tab = mTabControl.getTab(index);
1356 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001357 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001358 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001359 }
1360 if (currentTab != null) {
1361 // currentTab may be null if it was just removed. In that case,
1362 // we do not need to remove it
1363 removeTabFromContentView(currentTab);
1364 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001365 mTabControl.setCurrentTab(tab);
1366 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001367 resetTitleIconAndProgress();
1368 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001369 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001370 }
1371
Grace Kloba22ac16e2009-10-07 18:00:23 -07001372 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001373 return openTabAndShow(mSettings.getHomePage(), false, null);
1374 }
1375
Leon Scroggins1f005d32009-08-10 17:36:42 -04001376 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001377 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001378 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001379 // This is the last tab. Open a new one, with the home
1380 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001381 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001382 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001383 return;
1384 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001385 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001386 int indexToShow = -1;
1387 if (parent != null) {
1388 indexToShow = mTabControl.getTabIndex(parent);
1389 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001390 final int currentIndex = mTabControl.getCurrentIndex();
1391 // Try to move to the tab to the right
1392 indexToShow = currentIndex + 1;
1393 if (indexToShow > mTabControl.getTabCount() - 1) {
1394 // Try to move to the tab to the left
1395 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001396 }
1397 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001398 if (switchToTab(indexToShow)) {
1399 // Close window
1400 closeTab(current);
1401 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001402 }
1403
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001404 private ActiveTabsPage mActiveTabsPage;
1405
1406 /**
1407 * Remove the active tabs page.
1408 * @param needToAttach If true, the active tabs page did not attach a tab
1409 * to the content view, so we need to do that here.
1410 */
1411 /* package */ void removeActiveTabPage(boolean needToAttach) {
1412 mContentView.removeView(mActiveTabsPage);
1413 mActiveTabsPage = null;
1414 mMenuState = R.id.MAIN_MENU;
1415 if (needToAttach) {
1416 attachTabToContentView(mTabControl.getCurrentTab());
1417 }
1418 getTopWindow().requestFocus();
1419 }
1420
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 @Override
1422 public boolean onOptionsItemSelected(MenuItem item) {
1423 if (!mCanChord) {
1424 // The user has already fired a shortcut with this hold down of the
1425 // menu key.
1426 return false;
1427 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001428 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001429 return false;
1430 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001431 if (mMenuIsDown) {
1432 // The shortcut action consumes the MENU. Even if it is still down,
1433 // it won't trigger the next shortcut action. In the case of the
1434 // shortcut action triggering a new activity, like Bookmarks, we
1435 // won't get onKeyUp for MENU. So it is important to reset it here.
1436 mMenuIsDown = false;
1437 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 switch (item.getItemId()) {
1439 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001440 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001441 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001442 break;
1443
Leon Scroggins64b80f32009-08-07 12:03:34 -04001444 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001445 onSearchRequested();
1446 break;
1447
1448 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001449 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 break;
1451
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001452 case R.id.active_tabs_menu_id:
1453 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1454 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001455 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001456 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1457 mActiveTabsPage.requestFocus();
1458 mMenuState = EMPTY_MENU;
1459 break;
1460
Leon Scroggins1f005d32009-08-10 17:36:42 -04001461 case R.id.add_bookmark_menu_id:
1462 Intent i = new Intent(BrowserActivity.this,
1463 AddBookmarkPage.class);
1464 WebView w = getTopWindow();
1465 i.putExtra("url", w.getUrl());
1466 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001467 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001468 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001469 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 break;
1471
1472 case R.id.stop_reload_menu_id:
1473 if (mInLoad) {
1474 stopLoading();
1475 } else {
1476 getTopWindow().reload();
1477 }
1478 break;
1479
1480 case R.id.back_menu_id:
1481 getTopWindow().goBack();
1482 break;
1483
1484 case R.id.forward_menu_id:
1485 getTopWindow().goForward();
1486 break;
1487
1488 case R.id.close_menu_id:
1489 // Close the subwindow if it exists.
1490 if (mTabControl.getCurrentSubWindow() != null) {
1491 dismissSubWindow(mTabControl.getCurrentTab());
1492 break;
1493 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001494 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001495 break;
1496
1497 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001498 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001499 if (current != null) {
1500 dismissSubWindow(current);
1501 current.getWebView().loadUrl(mSettings.getHomePage());
1502 }
1503 break;
1504
1505 case R.id.preferences_menu_id:
1506 Intent intent = new Intent(this,
1507 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001508 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1509 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001510 startActivityForResult(intent, PREFERENCES_PAGE);
1511 break;
1512
1513 case R.id.find_menu_id:
1514 if (null == mFindDialog) {
1515 mFindDialog = new FindDialog(this);
1516 }
1517 mFindDialog.setWebView(getTopWindow());
1518 mFindDialog.show();
1519 mMenuState = EMPTY_MENU;
1520 break;
1521
1522 case R.id.select_text_id:
1523 getTopWindow().emulateShiftHeld();
1524 break;
1525 case R.id.page_info_menu_id:
1526 showPageInfo(mTabControl.getCurrentTab(), false);
1527 break;
1528
1529 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001530 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001531 break;
1532
Leon Scroggins96afcb12009-12-10 12:35:56 -05001533 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001534 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001535 Tab currentTab = mTabControl.getCurrentTab();
1536 if (null == currentTab) {
1537 mCanChord = false;
1538 return false;
1539 }
1540 currentTab.populatePickerData();
1541 sharePage(this, currentTab.getTitle(),
1542 currentTab.getUrl(), currentTab.getFavicon(),
1543 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 break;
1545
1546 case R.id.dump_nav_menu_id:
1547 getTopWindow().debugDump();
1548 break;
1549
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001550 case R.id.dump_counters_menu_id:
1551 getTopWindow().dumpV8Counters();
1552 break;
1553
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 case R.id.zoom_in_menu_id:
1555 getTopWindow().zoomIn();
1556 break;
1557
1558 case R.id.zoom_out_menu_id:
1559 getTopWindow().zoomOut();
1560 break;
1561
1562 case R.id.view_downloads_menu_id:
1563 viewDownloads(null);
1564 break;
1565
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 case R.id.window_one_menu_id:
1567 case R.id.window_two_menu_id:
1568 case R.id.window_three_menu_id:
1569 case R.id.window_four_menu_id:
1570 case R.id.window_five_menu_id:
1571 case R.id.window_six_menu_id:
1572 case R.id.window_seven_menu_id:
1573 case R.id.window_eight_menu_id:
1574 {
1575 int menuid = item.getItemId();
1576 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1577 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001578 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001579 if (desiredTab != null &&
1580 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001581 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001582 }
1583 break;
1584 }
1585 }
1586 }
1587 break;
1588
1589 default:
1590 if (!super.onOptionsItemSelected(item)) {
1591 return false;
1592 }
1593 // Otherwise fall through.
1594 }
1595 mCanChord = false;
1596 return true;
1597 }
1598
1599 public void closeFind() {
1600 mMenuState = R.id.MAIN_MENU;
1601 }
1602
Grace Kloba22ac16e2009-10-07 18:00:23 -07001603 @Override
1604 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001605 // This happens when the user begins to hold down the menu key, so
1606 // allow them to chord to get a shortcut.
1607 mCanChord = true;
1608 // Note: setVisible will decide whether an item is visible; while
1609 // setEnabled() will decide whether an item is enabled, which also means
1610 // whether the matching shortcut key will function.
1611 super.onPrepareOptionsMenu(menu);
1612 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001613 case EMPTY_MENU:
1614 if (mCurrentMenuState != mMenuState) {
1615 menu.setGroupVisible(R.id.MAIN_MENU, false);
1616 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1617 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001618 }
1619 break;
1620 default:
1621 if (mCurrentMenuState != mMenuState) {
1622 menu.setGroupVisible(R.id.MAIN_MENU, true);
1623 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1624 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001625 }
1626 final WebView w = getTopWindow();
1627 boolean canGoBack = false;
1628 boolean canGoForward = false;
1629 boolean isHome = false;
1630 if (w != null) {
1631 canGoBack = w.canGoBack();
1632 canGoForward = w.canGoForward();
1633 isHome = mSettings.getHomePage().equals(w.getUrl());
1634 }
1635 final MenuItem back = menu.findItem(R.id.back_menu_id);
1636 back.setEnabled(canGoBack);
1637
1638 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1639 home.setEnabled(!isHome);
1640
1641 menu.findItem(R.id.forward_menu_id)
1642 .setEnabled(canGoForward);
1643
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001644 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001645 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001646
The Android Open Source Project0c908882009-03-03 19:32:16 -08001647 // decide whether to show the share link option
1648 PackageManager pm = getPackageManager();
1649 Intent send = new Intent(Intent.ACTION_SEND);
1650 send.setType("text/plain");
1651 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1652 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1653
The Android Open Source Project0c908882009-03-03 19:32:16 -08001654 boolean isNavDump = mSettings.isNavDump();
1655 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1656 nav.setVisible(isNavDump);
1657 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001658
1659 boolean showDebugSettings = mSettings.showDebugSettings();
1660 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1661 counter.setVisible(showDebugSettings);
1662 counter.setEnabled(showDebugSettings);
1663
The Android Open Source Project0c908882009-03-03 19:32:16 -08001664 break;
1665 }
1666 mCurrentMenuState = mMenuState;
1667 return true;
1668 }
1669
1670 @Override
1671 public void onCreateContextMenu(ContextMenu menu, View v,
1672 ContextMenuInfo menuInfo) {
1673 WebView webview = (WebView) v;
1674 WebView.HitTestResult result = webview.getHitTestResult();
1675 if (result == null) {
1676 return;
1677 }
1678
1679 int type = result.getType();
1680 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1681 Log.w(LOGTAG,
1682 "We should not show context menu when nothing is touched");
1683 return;
1684 }
1685 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1686 // let TextView handles context menu
1687 return;
1688 }
1689
1690 // Note, http://b/issue?id=1106666 is requesting that
1691 // an inflated menu can be used again. This is not available
1692 // yet, so inflate each time (yuk!)
1693 MenuInflater inflater = getMenuInflater();
1694 inflater.inflate(R.menu.browsercontext, menu);
1695
1696 // Show the correct menu group
1697 String extra = result.getExtra();
1698 menu.setGroupVisible(R.id.PHONE_MENU,
1699 type == WebView.HitTestResult.PHONE_TYPE);
1700 menu.setGroupVisible(R.id.EMAIL_MENU,
1701 type == WebView.HitTestResult.EMAIL_TYPE);
1702 menu.setGroupVisible(R.id.GEO_MENU,
1703 type == WebView.HitTestResult.GEO_TYPE);
1704 menu.setGroupVisible(R.id.IMAGE_MENU,
1705 type == WebView.HitTestResult.IMAGE_TYPE
1706 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1707 menu.setGroupVisible(R.id.ANCHOR_MENU,
1708 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1709 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1710
1711 // Setup custom handling depending on the type
1712 switch (type) {
1713 case WebView.HitTestResult.PHONE_TYPE:
1714 menu.setHeaderTitle(Uri.decode(extra));
1715 menu.findItem(R.id.dial_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_TEL + extra)));
1718 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1719 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001720 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1722 addIntent);
1723 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1724 new Copy(extra));
1725 break;
1726
1727 case WebView.HitTestResult.EMAIL_TYPE:
1728 menu.setHeaderTitle(extra);
1729 menu.findItem(R.id.email_context_menu_id).setIntent(
1730 new Intent(Intent.ACTION_VIEW, Uri
1731 .parse(WebView.SCHEME_MAILTO + extra)));
1732 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1733 new Copy(extra));
1734 break;
1735
1736 case WebView.HitTestResult.GEO_TYPE:
1737 menu.setHeaderTitle(extra);
1738 menu.findItem(R.id.map_context_menu_id).setIntent(
1739 new Intent(Intent.ACTION_VIEW, Uri
1740 .parse(WebView.SCHEME_GEO
1741 + URLEncoder.encode(extra))));
1742 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1743 new Copy(extra));
1744 break;
1745
1746 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1747 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1748 TextView titleView = (TextView) LayoutInflater.from(this)
1749 .inflate(android.R.layout.browser_link_context_header,
1750 null);
1751 titleView.setText(extra);
1752 menu.setHeaderView(titleView);
1753 // decide whether to show the open link in new tab option
1754 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001755 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001756 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1757 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001758 PackageManager pm = getPackageManager();
1759 Intent send = new Intent(Intent.ACTION_SEND);
1760 send.setType("text/plain");
1761 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1762 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1763 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1764 break;
1765 }
1766 // otherwise fall through to handle image part
1767 case WebView.HitTestResult.IMAGE_TYPE:
1768 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1769 menu.setHeaderTitle(extra);
1770 }
1771 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1772 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1773 menu.findItem(R.id.download_context_menu_id).
1774 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001775 menu.findItem(R.id.set_wallpaper_context_menu_id).
1776 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001777 break;
1778
1779 default:
1780 Log.w(LOGTAG, "We should not get here.");
1781 break;
1782 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001783 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001784 }
1785
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001787 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001788 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001789 // Attach the container that contains the main WebView and any other UI
1790 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001791 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001792
1793 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001794 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001795 if (errorConsole.numberOfErrors() == 0) {
1796 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1797 } else {
1798 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1799 }
1800
1801 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001802 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001803 ViewGroup.LayoutParams.WRAP_CONTENT));
1804 }
1805
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001806 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001807 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001808 if (t.isInVoiceSearchMode()) {
1809 showVoiceTitleBar(t.getVoiceDisplayTitle());
1810 } else {
1811 revertVoiceTitleBar();
1812 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001813 // Request focus on the top window.
1814 t.getTopWindow().requestFocus();
1815 }
1816
1817 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001819 t.attachSubWindow(mContentView);
1820 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 }
1822
1823 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001824 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001825 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001826 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001827
Grace Kloba22ac16e2009-10-07 18:00:23 -07001828 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1829 if (errorConsole != null) {
1830 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001831 }
1832
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001833 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001834 if (view != null) {
1835 view.setEmbeddedTitleBar(null);
1836 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001837 }
1838
1839 // Remove the sub window if it exists. Also called by TabControl when the
1840 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001841 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001842 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001843 // dismiss the subwindow. This will destroy the WebView.
1844 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001845 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001846 }
1847
Leon Scroggins1f005d32009-08-10 17:36:42 -04001848 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001849 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001850 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001851 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001852 }
1853
1854 // This method does a ton of stuff. It will attempt to create a new tab
1855 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001856 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001857 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1858 String appId) {
1859 final Tab currentTab = mTabControl.getCurrentTab();
1860 if (mTabControl.canCreateNewTab()) {
1861 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1862 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001863 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001864 // If the last tab was removed from the active tabs page, currentTab
1865 // will be null.
1866 if (currentTab != null) {
1867 removeTabFromContentView(currentTab);
1868 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001869 // We must set the new tab as the current tab to reflect the old
1870 // animation behavior.
1871 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001872 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001873 if (!urlData.isEmpty()) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05001874 urlData.loadIn(tab);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001875 }
1876 return tab;
1877 } else {
1878 // Get rid of the subwindow if it exists
1879 dismissSubWindow(currentTab);
1880 if (!urlData.isEmpty()) {
1881 // Load the given url.
Leon Scroggins58d56c62010-01-28 15:12:40 -05001882 urlData.loadIn(currentTab);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001883 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001884 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001885 }
1886 }
1887
Grace Kloba22ac16e2009-10-07 18:00:23 -07001888 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001889 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001890 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001891 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001892 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001893 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001894 }
Grace Klobac9181842009-04-14 08:53:22 -07001895 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001896 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001897 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001898 }
1899 }
1900
1901 private class Copy implements OnMenuItemClickListener {
1902 private CharSequence mText;
1903
1904 public boolean onMenuItemClick(MenuItem item) {
1905 copy(mText);
1906 return true;
1907 }
1908
1909 public Copy(CharSequence toCopy) {
1910 mText = toCopy;
1911 }
1912 }
1913
1914 private class Download implements OnMenuItemClickListener {
1915 private String mText;
1916
1917 public boolean onMenuItemClick(MenuItem item) {
1918 onDownloadStartNoStream(mText, null, null, null, -1);
1919 return true;
1920 }
1921
1922 public Download(String toDownload) {
1923 mText = toDownload;
1924 }
1925 }
1926
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001927 private class SetAsWallpaper extends Thread implements
1928 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1929 private URL mUrl;
1930 private ProgressDialog mWallpaperProgress;
1931 private boolean mCanceled = false;
1932
1933 public SetAsWallpaper(String url) {
1934 try {
1935 mUrl = new URL(url);
1936 } catch (MalformedURLException e) {
1937 mUrl = null;
1938 }
1939 }
1940
1941 public void onCancel(DialogInterface dialog) {
1942 mCanceled = true;
1943 }
1944
1945 public boolean onMenuItemClick(MenuItem item) {
1946 if (mUrl != null) {
1947 // The user may have tried to set a image with a large file size as their
1948 // background so it may take a few moments to perform the operation. Display
1949 // a progress spinner while it is working.
1950 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1951 mWallpaperProgress.setIndeterminate(true);
1952 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1953 mWallpaperProgress.setCancelable(true);
1954 mWallpaperProgress.setOnCancelListener(this);
1955 mWallpaperProgress.show();
1956 start();
1957 }
1958 return true;
1959 }
1960
1961 public void run() {
1962 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1963 try {
1964 // TODO: This will cause the resource to be downloaded again, when we
1965 // should in most cases be able to grab it from the cache. To fix this
1966 // we should query WebCore to see if we can access a cached version and
1967 // instead open an input stream on that. This pattern could also be used
1968 // in the download manager where the same problem exists.
1969 InputStream inputstream = mUrl.openStream();
1970 if (inputstream != null) {
1971 setWallpaper(inputstream);
1972 }
1973 } catch (IOException e) {
1974 Log.e(LOGTAG, "Unable to set new wallpaper");
1975 // Act as though the user canceled the operation so we try to
1976 // restore the old wallpaper.
1977 mCanceled = true;
1978 }
1979
1980 if (mCanceled) {
1981 // Restore the old wallpaper if the user cancelled whilst we were setting
1982 // the new wallpaper.
1983 int width = oldWallpaper.getIntrinsicWidth();
1984 int height = oldWallpaper.getIntrinsicHeight();
1985 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1986 Canvas canvas = new Canvas(bm);
1987 oldWallpaper.setBounds(0, 0, width, height);
1988 oldWallpaper.draw(canvas);
1989 try {
1990 setWallpaper(bm);
1991 } catch (IOException e) {
1992 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1993 }
1994 mCanceled = false;
1995 }
1996
1997 if (mWallpaperProgress.isShowing()) {
1998 mWallpaperProgress.dismiss();
1999 }
2000 }
2001 }
2002
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 private void copy(CharSequence text) {
2004 try {
2005 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2006 if (clip != null) {
2007 clip.setClipboardText(text);
2008 }
2009 } catch (android.os.RemoteException e) {
2010 Log.e(LOGTAG, "Copy failed", e);
2011 }
2012 }
2013
2014 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 * Resets the browser title-view to whatever it must be
2016 * (for example, if we had a loading error)
2017 * When we have a new page, we call resetTitle, when we
2018 * have to reset the titlebar to whatever it used to be
2019 * (for example, if the user chose to stop loading), we
2020 * call resetTitleAndRevertLockIcon.
2021 */
2022 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002023 mTabControl.getCurrentTab().revertLockIcon();
2024 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 resetTitleIconAndProgress();
2026 }
2027
2028 /**
2029 * Reset the title, favicon, and progress.
2030 */
2031 private void resetTitleIconAndProgress() {
2032 WebView current = mTabControl.getCurrentWebView();
2033 if (current == null) {
2034 return;
2035 }
2036 resetTitleAndIcon(current);
2037 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002038 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 }
2040
2041 // Reset the title and the icon based on the given item.
2042 private void resetTitleAndIcon(WebView view) {
2043 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2044 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04002045 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 setFavicon(item.getFavicon());
2047 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04002048 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002049 setFavicon(null);
2050 }
2051 }
2052
2053 /**
2054 * Sets a title composed of the URL and the title string.
2055 * @param url The URL of the site being loaded.
2056 * @param title The title of the site being loaded.
2057 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002058 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002059 mUrl = url;
2060 mTitle = title;
2061
Leon Scroggins58d56c62010-01-28 15:12:40 -05002062 // If we are in voice search mode, the title has already been set.
2063 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2064 mTitleBar.setDisplayTitle(url);
2065 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 }
2067
2068 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 * @param url The URL to build a title version of the URL from.
2070 * @return The title version of the URL or null if fails.
2071 * The title version of the URL can be either the URL hostname,
2072 * or the hostname with an "https://" prefix (for secure URLs),
2073 * or an empty string if, for example, the URL in question is a
2074 * file:// URL with no hostname.
2075 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002076 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002077 String titleUrl = null;
2078
2079 if (url != null) {
2080 try {
2081 // parse the url string
2082 URL urlObj = new URL(url);
2083 if (urlObj != null) {
2084 titleUrl = "";
2085
2086 String protocol = urlObj.getProtocol();
2087 String host = urlObj.getHost();
2088
2089 if (host != null && 0 < host.length()) {
2090 titleUrl = host;
2091 if (protocol != null) {
2092 // if a secure site, add an "https://" prefix!
2093 if (protocol.equalsIgnoreCase("https")) {
2094 titleUrl = protocol + "://" + host;
2095 }
2096 }
2097 }
2098 }
2099 } catch (MalformedURLException e) {}
2100 }
2101
2102 return titleUrl;
2103 }
2104
2105 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002106 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002107 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002108 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002109 }
2110
2111 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002112 * Close the tab, remove its associated title bar, and adjust mTabControl's
2113 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002114 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002115 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002116 int currentIndex = mTabControl.getCurrentIndex();
2117 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002118 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002119 if (currentIndex >= removeIndex && currentIndex != 0) {
2120 currentIndex--;
2121 }
2122 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002123 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002124 }
2125
2126 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002127 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 if (current == null) {
2129 /*
2130 * Instead of finishing the activity, simply push this to the back
2131 * of the stack and let ActivityManager to choose the foreground
2132 * activity. As BrowserActivity is singleTask, it will be always the
2133 * root of the task. So we can use either true or false for
2134 * moveTaskToBack().
2135 */
2136 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002137 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002138 }
2139 WebView w = current.getWebView();
2140 if (w.canGoBack()) {
2141 w.goBack();
2142 } else {
2143 // Check to see if we are closing a window that was created by
2144 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002145 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002147 switchToTab(mTabControl.getTabIndex(parent));
2148 // Now we close the other tab
2149 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 } else {
2151 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002152 // force the tab's inLoad() to be false as we are going to
2153 // either finish the activity or remove the tab. This will
2154 // ensure pauseWebViewTimers() taking action.
2155 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 if (mTabControl.getTabCount() == 1) {
2157 finish();
2158 return;
2159 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002160 // call pauseWebViewTimers() now, we won't be able to call
2161 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002162 // Temporarily change mActivityInPause to be true as
2163 // pauseWebViewTimers() will do nothing if mActivityInPause
2164 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002165 boolean savedState = mActivityInPause;
2166 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002167 Log.e(LOGTAG, "BrowserActivity is already paused "
2168 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002169 }
2170 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002171 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002172 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 removeTabFromContentView(current);
2174 mTabControl.removeTab(current);
2175 }
2176 /*
2177 * Instead of finishing the activity, simply push this to the back
2178 * of the stack and let ActivityManager to choose the foreground
2179 * activity. As BrowserActivity is singleTask, it will be always the
2180 * root of the task. So we can use either true or false for
2181 * moveTaskToBack().
2182 */
2183 moveTaskToBack(true);
2184 }
2185 }
2186 }
2187
Grace Kloba22ac16e2009-10-07 18:00:23 -07002188 boolean isMenuDown() {
2189 return mMenuIsDown;
2190 }
2191
Grace Kloba5942df02009-09-18 11:48:29 -07002192 @Override
2193 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002194 // Even if MENU is already held down, we need to call to super to open
2195 // the IME on long press.
2196 if (KeyEvent.KEYCODE_MENU == keyCode) {
2197 mMenuIsDown = true;
2198 return super.onKeyDown(keyCode, event);
2199 }
Grace Kloba5942df02009-09-18 11:48:29 -07002200 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2201 // still down, we don't want to trigger the search. Pretend to consume
2202 // the key and do nothing.
2203 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204
Grace Kloba5942df02009-09-18 11:48:29 -07002205 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002206 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002207 // WebView/WebTextView handle the keys in the KeyDown. As
2208 // the Activity's shortcut keys are only handled when WebView
2209 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2210 if (event.isShiftPressed()) {
2211 getTopWindow().pageUp(false);
2212 } else {
2213 getTopWindow().pageDown(false);
2214 }
Grace Kloba5942df02009-09-18 11:48:29 -07002215 return true;
2216 case KeyEvent.KEYCODE_BACK:
2217 if (event.getRepeatCount() == 0) {
2218 event.startTracking();
2219 return true;
2220 } else if (mCustomView == null && mActiveTabsPage == null
2221 && event.isLongPress()) {
2222 bookmarksOrHistoryPicker(true);
2223 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 }
Grace Kloba5942df02009-09-18 11:48:29 -07002225 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 }
Grace Kloba5942df02009-09-18 11:48:29 -07002227 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002228 }
2229
Grace Kloba5942df02009-09-18 11:48:29 -07002230 @Override
2231 public boolean onKeyUp(int keyCode, KeyEvent event) {
2232 switch(keyCode) {
2233 case KeyEvent.KEYCODE_MENU:
2234 mMenuIsDown = false;
2235 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002236 case KeyEvent.KEYCODE_BACK:
2237 if (event.isTracking() && !event.isCanceled()) {
2238 if (mCustomView != null) {
2239 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002240 mTabControl.getCurrentWebView().getWebChromeClient()
2241 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002242 } else if (mActiveTabsPage != null) {
2243 // if tab page is showing, hide it
2244 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002246 WebView subwindow = mTabControl.getCurrentSubWindow();
2247 if (subwindow != null) {
2248 if (subwindow.canGoBack()) {
2249 subwindow.goBack();
2250 } else {
2251 dismissSubWindow(mTabControl.getCurrentTab());
2252 }
2253 } else {
2254 goBackOnePageOrQuit();
2255 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002256 }
Grace Kloba5942df02009-09-18 11:48:29 -07002257 return true;
2258 }
2259 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002260 }
Grace Kloba5942df02009-09-18 11:48:29 -07002261 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002262 }
2263
Leon Scroggins68579392009-09-15 15:31:54 -04002264 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002265 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 resetTitleAndRevertLockIcon();
2267 WebView w = getTopWindow();
2268 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002269 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2270 // same logic here. But for subwindow case, should we call into the main
2271 // WebView's onPageFinished as we never call its onPageStarted and if
2272 // the page finishes itself, we don't call onPageFinished.
2273 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2274 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002275
2276 cancelStopToast();
2277 mStopToast = Toast
2278 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2279 mStopToast.show();
2280 }
2281
Grace Kloba22ac16e2009-10-07 18:00:23 -07002282 boolean didUserStopLoading() {
2283 return mDidStopLoad;
2284 }
2285
The Android Open Source Project0c908882009-03-03 19:32:16 -08002286 private void cancelStopToast() {
2287 if (mStopToast != null) {
2288 mStopToast.cancel();
2289 mStopToast = null;
2290 }
2291 }
2292
Grace Kloba22ac16e2009-10-07 18:00:23 -07002293 // called by a UI or non-UI thread to post the message
2294 public void postMessage(int what, int arg1, int arg2, Object obj,
2295 long delayMillis) {
2296 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2297 obj), delayMillis);
2298 }
2299
2300 // called by a UI or non-UI thread to remove the message
2301 void removeMessages(int what, Object object) {
2302 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002303 }
2304
2305 // public message ids
2306 public final static int LOAD_URL = 1001;
2307 public final static int STOP_LOAD = 1002;
2308
2309 // Message Ids
2310 private static final int FOCUS_NODE_HREF = 102;
2311 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002312 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002313
Grace Kloba22ac16e2009-10-07 18:00:23 -07002314 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002315
The Android Open Source Project0c908882009-03-03 19:32:16 -08002316 // Private handler for handling javascript and saving passwords
2317 private Handler mHandler = new Handler() {
2318
2319 public void handleMessage(Message msg) {
2320 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002321 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002322 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002323 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002324 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002325 if (url == null || url.length() == 0) {
2326 break;
2327 }
2328 HashMap focusNodeMap = (HashMap) msg.obj;
2329 WebView view = (WebView) focusNodeMap.get("webview");
2330 // Only apply the action if the top window did not change.
2331 if (getTopWindow() != view) {
2332 break;
2333 }
2334 switch (msg.arg1) {
2335 case R.id.open_context_menu_id:
2336 case R.id.view_image_context_menu_id:
2337 loadURL(getTopWindow(), url);
2338 break;
2339 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002340 final Tab parent = mTabControl.getCurrentTab();
2341 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002342 if (newTab != parent) {
2343 parent.addChildTab(newTab);
2344 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002345 break;
2346 case R.id.bookmark_context_menu_id:
2347 Intent intent = new Intent(BrowserActivity.this,
2348 AddBookmarkPage.class);
2349 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002350 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 startActivity(intent);
2352 break;
2353 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002354 // See if this site has been visited before
2355 StringBuilder sb = new StringBuilder(
2356 Browser.BookmarkColumns.URL + " = ");
2357 DatabaseUtils.appendEscapedSQLString(sb, url);
2358 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2359 Browser.HISTORY_PROJECTION,
2360 sb.toString(),
2361 null,
2362 null);
2363 if (c.moveToFirst()) {
2364 // The site has been visited before, so grab the
2365 // info from the database.
2366 Bitmap favicon = null;
2367 Bitmap thumbnail = null;
2368 String linkTitle = c.getString(Browser.
2369 HISTORY_PROJECTION_TITLE_INDEX);
2370 byte[] data = c.getBlob(Browser.
2371 HISTORY_PROJECTION_FAVICON_INDEX);
2372 if (data != null) {
2373 favicon = BitmapFactory.decodeByteArray(
2374 data, 0, data.length);
2375 }
2376 data = c.getBlob(Browser.
2377 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2378 if (data != null) {
2379 thumbnail = BitmapFactory.decodeByteArray(
2380 data, 0, data.length);
2381 }
2382 sharePage(BrowserActivity.this,
2383 linkTitle, url, favicon, thumbnail);
2384 } else {
2385 Browser.sendString(BrowserActivity.this, url,
2386 getString(
2387 R.string.choosertitle_sharevia));
2388 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002389 break;
2390 case R.id.copy_link_context_menu_id:
2391 copy(url);
2392 break;
2393 case R.id.save_link_context_menu_id:
2394 case R.id.download_context_menu_id:
2395 onDownloadStartNoStream(url, null, null, null, -1);
2396 break;
2397 }
2398 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002399 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002400
2401 case LOAD_URL:
2402 loadURL(getTopWindow(), (String) msg.obj);
2403 break;
2404
2405 case STOP_LOAD:
2406 stopLoading();
2407 break;
2408
2409 case CANCEL_CREDS_REQUEST:
2410 resumeAfterCredentials();
2411 break;
2412
The Android Open Source Project0c908882009-03-03 19:32:16 -08002413 case RELEASE_WAKELOCK:
2414 if (mWakeLock.isHeld()) {
2415 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002416 // if we reach here, Browser should be still in the
2417 // background loading after WAKELOCK_TIMEOUT (5-min).
2418 // To avoid burning the battery, stop loading.
2419 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002420 }
2421 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002422
2423 case UPDATE_BOOKMARK_THUMBNAIL:
2424 WebView view = (WebView) msg.obj;
2425 if (view != null) {
2426 updateScreenshot(view);
2427 }
2428 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002429 }
2430 }
2431 };
2432
Leon Scroggins96afcb12009-12-10 12:35:56 -05002433 /**
2434 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2435 * an {@link Intent} to launch the Activity chooser.
2436 * @param c Context used to launch a new Activity.
2437 * @param title Title of the page. Stored in the Intent with
2438 * {@link Browser#EXTRA_SHARE_TITLE}
2439 * @param url URL of the page. Stored in the Intent with
2440 * {@link Intent#EXTRA_TEXT}
2441 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2442 * with {@link Browser#EXTRA_SHARE_FAVICON}
2443 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2444 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2445 */
2446 public static final void sharePage(Context c, String title, String url,
2447 Bitmap favicon, Bitmap screenshot) {
2448 Intent send = new Intent(Intent.ACTION_SEND);
2449 send.setType("text/plain");
2450 send.putExtra(Intent.EXTRA_TEXT, url);
2451 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2452 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2453 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2454 try {
2455 c.startActivity(Intent.createChooser(send, c.getString(
2456 R.string.choosertitle_sharevia)));
2457 } catch(android.content.ActivityNotFoundException ex) {
2458 // if no app handles it, do nothing
2459 }
2460 }
2461
Leon Scroggins89c6d362009-07-15 16:54:37 -04002462 private void updateScreenshot(WebView view) {
2463 // If this is a bookmarked site, add a screenshot to the database.
2464 // FIXME: When should we update? Every time?
2465 // FIXME: Would like to make sure there is actually something to
2466 // draw, but the API for that (WebViewCore.pictureReady()) is not
2467 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002468
Patrick Scott3918d442009-08-04 13:22:29 -04002469 ContentResolver cr = getContentResolver();
2470 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002471 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002472 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002473 boolean succeed = c.moveToFirst();
2474 ContentValues values = null;
2475 while (succeed) {
2476 if (values == null) {
2477 final ByteArrayOutputStream os
2478 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002479 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002480 if (bm == null) {
2481 c.close();
2482 return;
2483 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002484 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2485 values = new ContentValues();
2486 values.put(Browser.BookmarkColumns.THUMBNAIL,
2487 os.toByteArray());
2488 }
2489 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2490 c.getInt(0)), values, null, null);
2491 succeed = c.moveToNext();
2492 }
2493 c.close();
2494 }
2495 }
2496
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002497 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002498 * Values for the size of the thumbnail created when taking a screenshot.
2499 * Lazily initialized. Instead of using these directly, use
2500 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002501 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002502 private static int THUMBNAIL_WIDTH = 0;
2503 private static int THUMBNAIL_HEIGHT = 0;
2504
2505 /**
2506 * Return the desired width for thumbnail screenshots, which are stored in
2507 * the database, and used on the bookmarks screen.
2508 * @param context Context for finding out the density of the screen.
2509 * @return int desired width for thumbnail screenshot.
2510 */
2511 /* package */ static int getDesiredThumbnailWidth(Context context) {
2512 if (THUMBNAIL_WIDTH == 0) {
2513 float density = context.getResources().getDisplayMetrics().density;
2514 THUMBNAIL_WIDTH = (int) (90 * density);
2515 THUMBNAIL_HEIGHT = (int) (80 * density);
2516 }
2517 return THUMBNAIL_WIDTH;
2518 }
2519
2520 /**
2521 * Return the desired height for thumbnail screenshots, which are stored in
2522 * the database, and used on the bookmarks screen.
2523 * @param context Context for finding out the density of the screen.
2524 * @return int desired height for thumbnail screenshot.
2525 */
2526 /* package */ static int getDesiredThumbnailHeight(Context context) {
2527 // To ensure that they are both initialized.
2528 getDesiredThumbnailWidth(context);
2529 return THUMBNAIL_HEIGHT;
2530 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002531
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002532 private Bitmap createScreenshot(WebView view) {
2533 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002534 if (thumbnail == null) {
2535 return null;
2536 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002537 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2538 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002539 Canvas canvas = new Canvas(bm);
2540 // May need to tweak these values to determine what is the
2541 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002542 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002543 int thumbnailHeight = thumbnail.getHeight();
2544 float scaleFactorX = 1.0f;
2545 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002546 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002547 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002548 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002549 } else {
2550 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002551 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002552
2553 if (view.getWidth() > view.getHeight() &&
2554 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2555 // If the device is in landscape and the page is shorter
2556 // than the height of the view, stretch the thumbnail to fill the
2557 // space.
2558 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2559 (float)thumbnailHeight;
2560 } else {
2561 // In the portrait case, this looks nice.
2562 scaleFactorY = scaleFactorX;
2563 }
2564
2565 canvas.scale(scaleFactorX, scaleFactorY);
2566
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002567 thumbnail.draw(canvas);
2568 return bm;
2569 }
2570
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002572 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002573 //-------------------------------------------------------------------------
2574
2575 // Use in overrideUrlLoading
2576 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2577 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2578 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2579 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2580
Grace Kloba22ac16e2009-10-07 18:00:23 -07002581 void onPageStarted(WebView view, String url, Bitmap favicon) {
2582 // when BrowserActivity just starts, onPageStarted may be called before
2583 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2584 // to start the timer. As we won't switch tabs while an activity is in
2585 // pause state, we can ensure calling resume and pause in pair.
2586 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 resetLockIcon(url);
2589 setUrlTitle(url, null);
2590 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002591 // Keep this initial progress in sync with initialProgressValue (* 100)
2592 // in ProgressTracker.cpp
2593 // Show some progress so that the user knows the page is beginning to
2594 // load
2595 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002596 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002598
Grace Kloba22ac16e2009-10-07 18:00:23 -07002599 if (mSettings.isTracing()) {
2600 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002601 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 WebAddress uri = new WebAddress(url);
2603 host = uri.mHost;
2604 } catch (android.net.ParseException ex) {
2605 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002606 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002607 host = host.replace('.', '_');
2608 host += ".trace";
2609 mInTrace = true;
2610 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2611 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612
Grace Kloba22ac16e2009-10-07 18:00:23 -07002613 // Performance probe
2614 if (false) {
2615 mStart = SystemClock.uptimeMillis();
2616 mProcessStart = Process.getElapsedCpuTime();
2617 long[] sysCpu = new long[7];
2618 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2619 sysCpu, null)) {
2620 mUserStart = sysCpu[0] + sysCpu[1];
2621 mSystemStart = sysCpu[2];
2622 mIdleStart = sysCpu[3];
2623 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2624 }
2625 mUiStart = SystemClock.currentThreadTimeMillis();
2626 }
2627 }
2628
2629 void onPageFinished(WebView view, String url) {
2630 // Reset the title and icon in case we stopped a provisional load.
2631 resetTitleAndIcon(view);
2632 // Update the lock icon image only once we are done loading
2633 updateLockIconToLatest();
2634 // pause the WebView timer and release the wake lock if it is finished
2635 // while BrowserActivity is in pause state.
2636 if (mActivityInPause && pauseWebViewTimers()) {
2637 if (mWakeLock.isHeld()) {
2638 mHandler.removeMessages(RELEASE_WAKELOCK);
2639 mWakeLock.release();
2640 }
2641 }
2642
2643 // Performance probe
2644 if (false) {
2645 long[] sysCpu = new long[7];
2646 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2647 sysCpu, null)) {
2648 String uiInfo = "UI thread used "
2649 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2650 + " ms";
2651 if (LOGD_ENABLED) {
2652 Log.d(LOGTAG, uiInfo);
2653 }
2654 //The string that gets written to the log
2655 String performanceString = "It took total "
2656 + (SystemClock.uptimeMillis() - mStart)
2657 + " ms clock time to load the page."
2658 + "\nbrowser process used "
2659 + (Process.getElapsedCpuTime() - mProcessStart)
2660 + " ms, user processes used "
2661 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2662 + " ms, kernel used "
2663 + (sysCpu[2] - mSystemStart) * 10
2664 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2665 + " ms and irq took "
2666 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2667 * 10 + " ms, " + uiInfo;
2668 if (LOGD_ENABLED) {
2669 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2670 }
2671 if (url != null) {
2672 // strip the url to maintain consistency
2673 String newUrl = new String(url);
2674 if (newUrl.startsWith("http://www.")) {
2675 newUrl = newUrl.substring(11);
2676 } else if (newUrl.startsWith("http://")) {
2677 newUrl = newUrl.substring(7);
2678 } else if (newUrl.startsWith("https://www.")) {
2679 newUrl = newUrl.substring(12);
2680 } else if (newUrl.startsWith("https://")) {
2681 newUrl = newUrl.substring(8);
2682 }
2683 if (LOGD_ENABLED) {
2684 Log.d(LOGTAG, newUrl + " loaded");
2685 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002686 }
2687 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002689
Grace Kloba22ac16e2009-10-07 18:00:23 -07002690 if (mInTrace) {
2691 mInTrace = false;
2692 Debug.stopMethodTracing();
2693 }
2694 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002695
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 boolean shouldOverrideUrlLoading(WebView view, String url) {
2697 if (url.startsWith(SCHEME_WTAI)) {
2698 // wtai://wp/mc;number
2699 // number=string(phone-number)
2700 if (url.startsWith(SCHEME_WTAI_MC)) {
2701 Intent intent = new Intent(Intent.ACTION_VIEW,
2702 Uri.parse(WebView.SCHEME_TEL +
2703 url.substring(SCHEME_WTAI_MC.length())));
2704 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002705 return true;
2706 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002707 // wtai://wp/sd;dtmf
2708 // dtmf=string(dialstring)
2709 if (url.startsWith(SCHEME_WTAI_SD)) {
2710 // TODO: only send when there is active voice connection
2711 return false;
2712 }
2713 // wtai://wp/ap;number;name
2714 // number=string(phone-number)
2715 // name=string
2716 if (url.startsWith(SCHEME_WTAI_AP)) {
2717 // TODO
2718 return false;
2719 }
2720 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002721
Grace Kloba22ac16e2009-10-07 18:00:23 -07002722 // The "about:" schemes are internal to the browser; don't want these to
2723 // be dispatched to other apps.
2724 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002725 return false;
2726 }
2727
Grace Kloba22ac16e2009-10-07 18:00:23 -07002728 Intent intent;
2729 // perform generic parsing of the URI to turn it into an Intent.
2730 try {
2731 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2732 } catch (URISyntaxException ex) {
2733 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2734 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002735 }
2736
Grace Kloba22ac16e2009-10-07 18:00:23 -07002737 // check whether the intent can be resolved. If not, we will see
2738 // whether we can download it from the Market.
2739 if (getPackageManager().resolveActivity(intent, 0) == null) {
2740 String packagename = intent.getPackage();
2741 if (packagename != null) {
2742 intent = new Intent(Intent.ACTION_VIEW, Uri
2743 .parse("market://search?q=pname:" + packagename));
2744 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2745 startActivity(intent);
2746 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002747 } else {
2748 return false;
2749 }
2750 }
2751
Grace Kloba22ac16e2009-10-07 18:00:23 -07002752 // sanitize the Intent, ensuring web pages can not bypass browser
2753 // security (only access to BROWSABLE activities).
2754 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2755 intent.setComponent(null);
2756 try {
2757 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002758 return true;
2759 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002760 } catch (ActivityNotFoundException ex) {
2761 // ignore the error. If no application can handle the URL,
2762 // eg about:blank, assume the browser can handle it.
2763 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764
Grace Kloba22ac16e2009-10-07 18:00:23 -07002765 if (mMenuIsDown) {
2766 openTab(url);
2767 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002768 return true;
2769 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002770 return false;
2771 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002772
Grace Kloba22ac16e2009-10-07 18:00:23 -07002773 // -------------------------------------------------------------------------
2774 // Helper function for WebChromeClient
2775 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 void onProgressChanged(WebView view, int newProgress) {
2778 mTitleBar.setProgress(newProgress);
2779 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002780
Grace Kloba22ac16e2009-10-07 18:00:23 -07002781 if (newProgress == 100) {
2782 // onProgressChanged() may continue to be called after the main
2783 // frame has finished loading, as any remaining sub frames continue
2784 // to load. We'll only get called once though with newProgress as
2785 // 100 when everything is loaded. (onPageFinished is called once
2786 // when the main frame completes loading regardless of the state of
2787 // any sub frames so calls to onProgressChanges may continue after
2788 // onPageFinished has executed)
2789 if (mInLoad) {
2790 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002791 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002792 // If the options menu is open, leave the title bar
2793 if (!mOptionsMenuOpen || !mIconView) {
2794 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002797 } else if (!mInLoad) {
2798 // onPageFinished may have already been called but a subframe is
2799 // still loading and updating the progress. Reset mInLoad and update
2800 // the menu items.
2801 mInLoad = true;
2802 updateInLoadMenuItems();
2803 if (!mOptionsMenuOpen || mIconView) {
2804 // This page has begun to load, so show the title bar
2805 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002806 }
2807 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002808 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002809
Grace Kloba22ac16e2009-10-07 18:00:23 -07002810 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002811 // if a view already exists then immediately terminate the new one
2812 if (mCustomView != null) {
2813 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002814 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002815 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002816
2817 // Add the custom view to its container.
2818 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2819 mCustomView = view;
2820 mCustomViewCallback = callback;
2821 // Save the menu state and set it to empty while the custom
2822 // view is showing.
2823 mOldMenuState = mMenuState;
2824 mMenuState = EMPTY_MENU;
2825 // Hide the content view.
2826 mContentView.setVisibility(View.GONE);
2827 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002828 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002829 mCustomViewContainer.setVisibility(View.VISIBLE);
2830 mCustomViewContainer.bringToFront();
2831 }
2832
2833 void onHideCustomView() {
2834 if (mCustomView == null)
2835 return;
2836
2837 // Hide the custom view.
2838 mCustomView.setVisibility(View.GONE);
2839 // Remove the custom view from its container.
2840 mCustomViewContainer.removeView(mCustomView);
2841 mCustomView = null;
2842 // Reset the old menu state.
2843 mMenuState = mOldMenuState;
2844 mOldMenuState = EMPTY_MENU;
2845 mCustomViewContainer.setVisibility(View.GONE);
2846 mCustomViewCallback.onCustomViewHidden();
2847 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002848 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002849 mContentView.setVisibility(View.VISIBLE);
2850 }
2851
2852 Bitmap getDefaultVideoPoster() {
2853 if (mDefaultVideoPoster == null) {
2854 mDefaultVideoPoster = BitmapFactory.decodeResource(
2855 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002856 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002857 return mDefaultVideoPoster;
2858 }
Patrick Scott3918d442009-08-04 13:22:29 -04002859
Grace Kloba22ac16e2009-10-07 18:00:23 -07002860 View getVideoLoadingProgressView() {
2861 if (mVideoProgressView == null) {
2862 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2863 mVideoProgressView = inflater.inflate(
2864 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002865 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002866 return mVideoProgressView;
2867 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002868
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002869 /*
2870 * The Object used to inform the WebView of the file to upload.
2871 */
2872 private ValueCallback<Uri> mUploadMessage;
2873
Grace Kloba22ac16e2009-10-07 18:00:23 -07002874 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2875 if (mUploadMessage != null) return;
2876 mUploadMessage = uploadMsg;
2877 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2878 i.addCategory(Intent.CATEGORY_OPENABLE);
2879 i.setType("*/*");
2880 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2881 getString(R.string.choose_upload)), FILE_SELECTED);
2882 }
2883
2884 // -------------------------------------------------------------------------
2885 // Implement functions for DownloadListener
2886 // -------------------------------------------------------------------------
2887
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 /**
2889 * Notify the host application a download should be done, or that
2890 * the data should be streamed if a streaming viewer is available.
2891 * @param url The full url to the content that should be downloaded
2892 * @param contentDisposition Content-disposition http header, if
2893 * present.
2894 * @param mimetype The mimetype of the content reported by the server
2895 * @param contentLength The file size reported by the server
2896 */
2897 public void onDownloadStart(String url, String userAgent,
2898 String contentDisposition, String mimetype, long contentLength) {
2899 // if we're dealing wih A/V content that's not explicitly marked
2900 // for download, check if it's streamable.
2901 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002902 || !contentDisposition.regionMatches(
2903 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002904 // query the package manager to see if there's a registered handler
2905 // that matches.
2906 Intent intent = new Intent(Intent.ACTION_VIEW);
2907 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002908 ResolveInfo info = getPackageManager().resolveActivity(intent,
2909 PackageManager.MATCH_DEFAULT_ONLY);
2910 if (info != null) {
2911 ComponentName myName = getComponentName();
2912 // If we resolved to ourselves, we don't want to attempt to
2913 // load the url only to try and download it again.
2914 if (!myName.getPackageName().equals(
2915 info.activityInfo.packageName)
2916 || !myName.getClassName().equals(
2917 info.activityInfo.name)) {
2918 // someone (other than us) knows how to handle this mime
2919 // type with this scheme, don't download.
2920 try {
2921 startActivity(intent);
2922 return;
2923 } catch (ActivityNotFoundException ex) {
2924 if (LOGD_ENABLED) {
2925 Log.d(LOGTAG, "activity not found for " + mimetype
2926 + " over " + Uri.parse(url).getScheme(),
2927 ex);
2928 }
2929 // Best behavior is to fall back to a download in this
2930 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002931 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002932 }
2933 }
2934 }
2935 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2936 }
2937
2938 /**
2939 * Notify the host application a download should be done, even if there
2940 * is a streaming viewer available for thise type.
2941 * @param url The full url to the content that should be downloaded
2942 * @param contentDisposition Content-disposition http header, if
2943 * present.
2944 * @param mimetype The mimetype of the content reported by the server
2945 * @param contentLength The file size reported by the server
2946 */
2947 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2948 String contentDisposition, String mimetype, long contentLength) {
2949
2950 String filename = URLUtil.guessFileName(url,
2951 contentDisposition, mimetype);
2952
2953 // Check to see if we have an SDCard
2954 String status = Environment.getExternalStorageState();
2955 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2956 int title;
2957 String msg;
2958
2959 // Check to see if the SDCard is busy, same as the music app
2960 if (status.equals(Environment.MEDIA_SHARED)) {
2961 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2962 title = R.string.download_sdcard_busy_dlg_title;
2963 } else {
2964 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2965 title = R.string.download_no_sdcard_dlg_title;
2966 }
2967
2968 new AlertDialog.Builder(this)
2969 .setTitle(title)
2970 .setIcon(android.R.drawable.ic_dialog_alert)
2971 .setMessage(msg)
2972 .setPositiveButton(R.string.ok, null)
2973 .show();
2974 return;
2975 }
2976
2977 // java.net.URI is a lot stricter than KURL so we have to undo
2978 // KURL's percent-encoding and redo the encoding using java.net.URI.
2979 URI uri = null;
2980 try {
2981 // Undo the percent-encoding that KURL may have done.
2982 String newUrl = new String(URLUtil.decode(url.getBytes()));
2983 // Parse the url into pieces
2984 WebAddress w = new WebAddress(newUrl);
2985 String frag = null;
2986 String query = null;
2987 String path = w.mPath;
2988 // Break the path into path, query, and fragment
2989 if (path.length() > 0) {
2990 // Strip the fragment
2991 int idx = path.lastIndexOf('#');
2992 if (idx != -1) {
2993 frag = path.substring(idx + 1);
2994 path = path.substring(0, idx);
2995 }
2996 idx = path.lastIndexOf('?');
2997 if (idx != -1) {
2998 query = path.substring(idx + 1);
2999 path = path.substring(0, idx);
3000 }
3001 }
3002 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3003 query, frag);
3004 } catch (Exception e) {
3005 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3006 return;
3007 }
3008
3009 // XXX: Have to use the old url since the cookies were stored using the
3010 // old percent-encoded url.
3011 String cookies = CookieManager.getInstance().getCookie(url);
3012
3013 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003014 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3015 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3016 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3017 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003018 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003019 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003020 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003021 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3022 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3023 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3024 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3025 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003026 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003027 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003028 }
3029 if (mimetype == null) {
3030 // We must have long pressed on a link or image to download it. We
3031 // are not sure of the mimetype in this case, so do a head request
3032 new FetchUrlMimeType(this).execute(values);
3033 } else {
3034 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08003035 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 }
3037
3038 }
3039
Grace Kloba22ac16e2009-10-07 18:00:23 -07003040 // -------------------------------------------------------------------------
3041
The Android Open Source Project0c908882009-03-03 19:32:16 -08003042 /**
3043 * Resets the lock icon. This method is called when we start a new load and
3044 * know the url to be loaded.
3045 */
3046 private void resetLockIcon(String url) {
3047 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07003048 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003049 updateLockIconImage(LOCK_ICON_UNSECURE);
3050 }
3051
The Android Open Source Project0c908882009-03-03 19:32:16 -08003052 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003053 * Update the lock icon to correspond to our latest state.
3054 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003055 private void updateLockIconToLatest() {
3056 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04003057 }
3058
3059 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08003060 * Updates the lock-icon image in the title-bar.
3061 */
3062 private void updateLockIconImage(int lockIconType) {
3063 Drawable d = null;
3064 if (lockIconType == LOCK_ICON_SECURE) {
3065 d = mSecLockIcon;
3066 } else if (lockIconType == LOCK_ICON_MIXED) {
3067 d = mMixLockIcon;
3068 }
Leon Scroggins68579392009-09-15 15:31:54 -04003069 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04003070 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 }
3072
3073 /**
3074 * Displays a page-info dialog.
3075 * @param tab The tab to show info about
3076 * @param fromShowSSLCertificateOnError The flag that indicates whether
3077 * this dialog was opened from the SSL-certificate-on-error dialog or
3078 * not. This is important, since we need to know whether to return to
3079 * the parent dialog or simply dismiss.
3080 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003081 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003082 final boolean fromShowSSLCertificateOnError) {
3083 final LayoutInflater factory = LayoutInflater
3084 .from(this);
3085
3086 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3087
3088 final WebView view = tab.getWebView();
3089
3090 String url = null;
3091 String title = null;
3092
3093 if (view == null) {
3094 url = tab.getUrl();
3095 title = tab.getTitle();
3096 } else if (view == mTabControl.getCurrentWebView()) {
3097 // Use the cached title and url if this is the current WebView
3098 url = mUrl;
3099 title = mTitle;
3100 } else {
3101 url = view.getUrl();
3102 title = view.getTitle();
3103 }
3104
3105 if (url == null) {
3106 url = "";
3107 }
3108 if (title == null) {
3109 title = "";
3110 }
3111
3112 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3113 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3114
3115 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003116 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003117
3118 AlertDialog.Builder alertDialogBuilder =
3119 new AlertDialog.Builder(this)
3120 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3121 .setView(pageInfoView)
3122 .setPositiveButton(
3123 R.string.ok,
3124 new DialogInterface.OnClickListener() {
3125 public void onClick(DialogInterface dialog,
3126 int whichButton) {
3127 mPageInfoDialog = null;
3128 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003129
3130 // if we came here from the SSL error dialog
3131 if (fromShowSSLCertificateOnError) {
3132 // go back to the SSL error dialog
3133 showSSLCertificateOnError(
3134 mSSLCertificateOnErrorView,
3135 mSSLCertificateOnErrorHandler,
3136 mSSLCertificateOnErrorError);
3137 }
3138 }
3139 })
3140 .setOnCancelListener(
3141 new DialogInterface.OnCancelListener() {
3142 public void onCancel(DialogInterface dialog) {
3143 mPageInfoDialog = null;
3144 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003145
3146 // if we came here from the SSL error dialog
3147 if (fromShowSSLCertificateOnError) {
3148 // go back to the SSL error dialog
3149 showSSLCertificateOnError(
3150 mSSLCertificateOnErrorView,
3151 mSSLCertificateOnErrorHandler,
3152 mSSLCertificateOnErrorError);
3153 }
3154 }
3155 });
3156
3157 // if we have a main top-level page SSL certificate set or a certificate
3158 // error
3159 if (fromShowSSLCertificateOnError ||
3160 (view != null && view.getCertificate() != null)) {
3161 // add a 'View Certificate' button
3162 alertDialogBuilder.setNeutralButton(
3163 R.string.view_certificate,
3164 new DialogInterface.OnClickListener() {
3165 public void onClick(DialogInterface dialog,
3166 int whichButton) {
3167 mPageInfoDialog = null;
3168 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003169
3170 // if we came here from the SSL error dialog
3171 if (fromShowSSLCertificateOnError) {
3172 // go back to the SSL error dialog
3173 showSSLCertificateOnError(
3174 mSSLCertificateOnErrorView,
3175 mSSLCertificateOnErrorHandler,
3176 mSSLCertificateOnErrorError);
3177 } else {
3178 // otherwise, display the top-most certificate from
3179 // the chain
3180 if (view.getCertificate() != null) {
3181 showSSLCertificate(tab);
3182 }
3183 }
3184 }
3185 });
3186 }
3187
3188 mPageInfoDialog = alertDialogBuilder.show();
3189 }
3190
3191 /**
3192 * Displays the main top-level page SSL certificate dialog
3193 * (accessible from the Page-Info dialog).
3194 * @param tab The tab to show certificate for.
3195 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003196 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003197 final View certificateView =
3198 inflateCertificateView(tab.getWebView().getCertificate());
3199 if (certificateView == null) {
3200 return;
3201 }
3202
3203 LayoutInflater factory = LayoutInflater.from(this);
3204
3205 final LinearLayout placeholder =
3206 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3207
3208 LinearLayout ll = (LinearLayout) factory.inflate(
3209 R.layout.ssl_success, placeholder);
3210 ((TextView)ll.findViewById(R.id.success))
3211 .setText(R.string.ssl_certificate_is_valid);
3212
3213 mSSLCertificateView = tab;
3214 mSSLCertificateDialog =
3215 new AlertDialog.Builder(this)
3216 .setTitle(R.string.ssl_certificate).setIcon(
3217 R.drawable.ic_dialog_browser_certificate_secure)
3218 .setView(certificateView)
3219 .setPositiveButton(R.string.ok,
3220 new DialogInterface.OnClickListener() {
3221 public void onClick(DialogInterface dialog,
3222 int whichButton) {
3223 mSSLCertificateDialog = null;
3224 mSSLCertificateView = null;
3225
3226 showPageInfo(tab, false);
3227 }
3228 })
3229 .setOnCancelListener(
3230 new DialogInterface.OnCancelListener() {
3231 public void onCancel(DialogInterface dialog) {
3232 mSSLCertificateDialog = null;
3233 mSSLCertificateView = null;
3234
3235 showPageInfo(tab, false);
3236 }
3237 })
3238 .show();
3239 }
3240
3241 /**
3242 * Displays the SSL error certificate dialog.
3243 * @param view The target web-view.
3244 * @param handler The SSL error handler responsible for cancelling the
3245 * connection that resulted in an SSL error or proceeding per user request.
3246 * @param error The SSL error object.
3247 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003248 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003249 final WebView view, final SslErrorHandler handler, final SslError error) {
3250
3251 final View certificateView =
3252 inflateCertificateView(error.getCertificate());
3253 if (certificateView == null) {
3254 return;
3255 }
3256
3257 LayoutInflater factory = LayoutInflater.from(this);
3258
3259 final LinearLayout placeholder =
3260 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3261
3262 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3263 LinearLayout ll = (LinearLayout)factory
3264 .inflate(R.layout.ssl_warning, placeholder);
3265 ((TextView)ll.findViewById(R.id.warning))
3266 .setText(R.string.ssl_untrusted);
3267 }
3268
3269 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3270 LinearLayout ll = (LinearLayout)factory
3271 .inflate(R.layout.ssl_warning, placeholder);
3272 ((TextView)ll.findViewById(R.id.warning))
3273 .setText(R.string.ssl_mismatch);
3274 }
3275
3276 if (error.hasError(SslError.SSL_EXPIRED)) {
3277 LinearLayout ll = (LinearLayout)factory
3278 .inflate(R.layout.ssl_warning, placeholder);
3279 ((TextView)ll.findViewById(R.id.warning))
3280 .setText(R.string.ssl_expired);
3281 }
3282
3283 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3284 LinearLayout ll = (LinearLayout)factory
3285 .inflate(R.layout.ssl_warning, placeholder);
3286 ((TextView)ll.findViewById(R.id.warning))
3287 .setText(R.string.ssl_not_yet_valid);
3288 }
3289
3290 mSSLCertificateOnErrorHandler = handler;
3291 mSSLCertificateOnErrorView = view;
3292 mSSLCertificateOnErrorError = error;
3293 mSSLCertificateOnErrorDialog =
3294 new AlertDialog.Builder(this)
3295 .setTitle(R.string.ssl_certificate).setIcon(
3296 R.drawable.ic_dialog_browser_certificate_partially_secure)
3297 .setView(certificateView)
3298 .setPositiveButton(R.string.ok,
3299 new DialogInterface.OnClickListener() {
3300 public void onClick(DialogInterface dialog,
3301 int whichButton) {
3302 mSSLCertificateOnErrorDialog = null;
3303 mSSLCertificateOnErrorView = null;
3304 mSSLCertificateOnErrorHandler = null;
3305 mSSLCertificateOnErrorError = null;
3306
Grace Kloba22ac16e2009-10-07 18:00:23 -07003307 view.getWebViewClient().onReceivedSslError(
3308 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003309 }
3310 })
3311 .setNeutralButton(R.string.page_info_view,
3312 new DialogInterface.OnClickListener() {
3313 public void onClick(DialogInterface dialog,
3314 int whichButton) {
3315 mSSLCertificateOnErrorDialog = null;
3316
3317 // do not clear the dialog state: we will
3318 // need to show the dialog again once the
3319 // user is done exploring the page-info details
3320
3321 showPageInfo(mTabControl.getTabFromView(view),
3322 true);
3323 }
3324 })
3325 .setOnCancelListener(
3326 new DialogInterface.OnCancelListener() {
3327 public void onCancel(DialogInterface dialog) {
3328 mSSLCertificateOnErrorDialog = null;
3329 mSSLCertificateOnErrorView = null;
3330 mSSLCertificateOnErrorHandler = null;
3331 mSSLCertificateOnErrorError = null;
3332
Grace Kloba22ac16e2009-10-07 18:00:23 -07003333 view.getWebViewClient().onReceivedSslError(
3334 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003335 }
3336 })
3337 .show();
3338 }
3339
3340 /**
3341 * Inflates the SSL certificate view (helper method).
3342 * @param certificate The SSL certificate.
3343 * @return The resultant certificate view with issued-to, issued-by,
3344 * issued-on, expires-on, and possibly other fields set.
3345 * If the input certificate is null, returns null.
3346 */
3347 private View inflateCertificateView(SslCertificate certificate) {
3348 if (certificate == null) {
3349 return null;
3350 }
3351
3352 LayoutInflater factory = LayoutInflater.from(this);
3353
3354 View certificateView = factory.inflate(
3355 R.layout.ssl_certificate, null);
3356
3357 // issued to:
3358 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3359 if (issuedTo != null) {
3360 ((TextView) certificateView.findViewById(R.id.to_common))
3361 .setText(issuedTo.getCName());
3362 ((TextView) certificateView.findViewById(R.id.to_org))
3363 .setText(issuedTo.getOName());
3364 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3365 .setText(issuedTo.getUName());
3366 }
3367
3368 // issued by:
3369 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3370 if (issuedBy != null) {
3371 ((TextView) certificateView.findViewById(R.id.by_common))
3372 .setText(issuedBy.getCName());
3373 ((TextView) certificateView.findViewById(R.id.by_org))
3374 .setText(issuedBy.getOName());
3375 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3376 .setText(issuedBy.getUName());
3377 }
3378
3379 // issued on:
3380 String issuedOn = reformatCertificateDate(
3381 certificate.getValidNotBefore());
3382 ((TextView) certificateView.findViewById(R.id.issued_on))
3383 .setText(issuedOn);
3384
3385 // expires on:
3386 String expiresOn = reformatCertificateDate(
3387 certificate.getValidNotAfter());
3388 ((TextView) certificateView.findViewById(R.id.expires_on))
3389 .setText(expiresOn);
3390
3391 return certificateView;
3392 }
3393
3394 /**
3395 * Re-formats the certificate date (Date.toString()) string to
3396 * a properly localized date string.
3397 * @return Properly localized version of the certificate date string and
3398 * the original certificate date string if fails to localize.
3399 * If the original string is null, returns an empty string "".
3400 */
3401 private String reformatCertificateDate(String certificateDate) {
3402 String reformattedDate = null;
3403
3404 if (certificateDate != null) {
3405 Date date = null;
3406 try {
3407 date = java.text.DateFormat.getInstance().parse(certificateDate);
3408 } catch (ParseException e) {
3409 date = null;
3410 }
3411
3412 if (date != null) {
3413 reformattedDate =
3414 DateFormat.getDateFormat(this).format(date);
3415 }
3416 }
3417
3418 return reformattedDate != null ? reformattedDate :
3419 (certificateDate != null ? certificateDate : "");
3420 }
3421
3422 /**
3423 * Displays an http-authentication dialog.
3424 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003425 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003426 final String host, final String realm, final String title,
3427 final String name, final String password, int focusId) {
3428 LayoutInflater factory = LayoutInflater.from(this);
3429 final View v = factory
3430 .inflate(R.layout.http_authentication, null);
3431 if (name != null) {
3432 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3433 }
3434 if (password != null) {
3435 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3436 }
3437
3438 String titleText = title;
3439 if (titleText == null) {
3440 titleText = getText(R.string.sign_in_to).toString().replace(
3441 "%s1", host).replace("%s2", realm);
3442 }
3443
3444 mHttpAuthHandler = handler;
3445 AlertDialog dialog = new AlertDialog.Builder(this)
3446 .setTitle(titleText)
3447 .setIcon(android.R.drawable.ic_dialog_alert)
3448 .setView(v)
3449 .setPositiveButton(R.string.action,
3450 new DialogInterface.OnClickListener() {
3451 public void onClick(DialogInterface dialog,
3452 int whichButton) {
3453 String nm = ((EditText) v
3454 .findViewById(R.id.username_edit))
3455 .getText().toString();
3456 String pw = ((EditText) v
3457 .findViewById(R.id.password_edit))
3458 .getText().toString();
3459 BrowserActivity.this.setHttpAuthUsernamePassword
3460 (host, realm, nm, pw);
3461 handler.proceed(nm, pw);
3462 mHttpAuthenticationDialog = null;
3463 mHttpAuthHandler = null;
3464 }})
3465 .setNegativeButton(R.string.cancel,
3466 new DialogInterface.OnClickListener() {
3467 public void onClick(DialogInterface dialog,
3468 int whichButton) {
3469 handler.cancel();
3470 BrowserActivity.this.resetTitleAndRevertLockIcon();
3471 mHttpAuthenticationDialog = null;
3472 mHttpAuthHandler = null;
3473 }})
3474 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3475 public void onCancel(DialogInterface dialog) {
3476 handler.cancel();
3477 BrowserActivity.this.resetTitleAndRevertLockIcon();
3478 mHttpAuthenticationDialog = null;
3479 mHttpAuthHandler = null;
3480 }})
3481 .create();
3482 // Make the IME appear when the dialog is displayed if applicable.
3483 dialog.getWindow().setSoftInputMode(
3484 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3485 dialog.show();
3486 if (focusId != 0) {
3487 dialog.findViewById(focusId).requestFocus();
3488 } else {
3489 v.findViewById(R.id.username_edit).requestFocus();
3490 }
3491 mHttpAuthenticationDialog = dialog;
3492 }
3493
3494 public int getProgress() {
3495 WebView w = mTabControl.getCurrentWebView();
3496 if (w != null) {
3497 return w.getProgress();
3498 } else {
3499 return 100;
3500 }
3501 }
3502
3503 /**
3504 * Set HTTP authentication password.
3505 *
3506 * @param host The host for the password
3507 * @param realm The realm for the password
3508 * @param username The username for the password. If it is null, it means
3509 * password can't be saved.
3510 * @param password The password
3511 */
3512 public void setHttpAuthUsernamePassword(String host, String realm,
3513 String username,
3514 String password) {
3515 WebView w = mTabControl.getCurrentWebView();
3516 if (w != null) {
3517 w.setHttpAuthUsernamePassword(host, realm, username, password);
3518 }
3519 }
3520
3521 /**
3522 * connectivity manager says net has come or gone... inform the user
3523 * @param up true if net has come up, false if net has gone down
3524 */
3525 public void onNetworkToggle(boolean up) {
3526 if (up == mIsNetworkUp) {
3527 return;
3528 } else if (up) {
3529 mIsNetworkUp = true;
3530 if (mAlertDialog != null) {
3531 mAlertDialog.cancel();
3532 mAlertDialog = null;
3533 }
3534 } else {
3535 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003536 if (mInLoad) {
3537 createAndShowNetworkDialog();
3538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539 }
3540 WebView w = mTabControl.getCurrentWebView();
3541 if (w != null) {
3542 w.setNetworkAvailable(up);
3543 }
3544 }
3545
Grace Kloba22ac16e2009-10-07 18:00:23 -07003546 boolean isNetworkUp() {
3547 return mIsNetworkUp;
3548 }
3549
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003550 // This method shows the network dialog alerting the user that the net is
3551 // down. It will only show the dialog if mAlertDialog is null.
3552 private void createAndShowNetworkDialog() {
3553 if (mAlertDialog == null) {
3554 mAlertDialog = new AlertDialog.Builder(this)
3555 .setTitle(R.string.loadSuspendedTitle)
3556 .setMessage(R.string.loadSuspended)
3557 .setPositiveButton(R.string.ok, null)
3558 .show();
3559 }
3560 }
3561
The Android Open Source Project0c908882009-03-03 19:32:16 -08003562 @Override
3563 protected void onActivityResult(int requestCode, int resultCode,
3564 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003565 if (getTopWindow() == null) return;
3566
The Android Open Source Project0c908882009-03-03 19:32:16 -08003567 switch (requestCode) {
3568 case COMBO_PAGE:
3569 if (resultCode == RESULT_OK && intent != null) {
3570 String data = intent.getAction();
3571 Bundle extras = intent.getExtras();
3572 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003573 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003574 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003575 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003577 dismissSubWindow(currentTab);
3578 if (data != null && data.length() != 0) {
3579 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003580 }
3581 }
3582 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003583 // Deliberately fall through to PREFERENCES_PAGE, since the
3584 // same extra may be attached to the COMBO_PAGE
3585 case PREFERENCES_PAGE:
3586 if (resultCode == RESULT_OK && intent != null) {
3587 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3588 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3589 mTabControl.removeParentChildRelationShips();
3590 }
3591 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003592 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003593 // Choose a file from the file picker.
3594 case FILE_SELECTED:
3595 if (null == mUploadMessage) break;
3596 Uri result = intent == null || resultCode != RESULT_OK ? null
3597 : intent.getData();
3598 mUploadMessage.onReceiveValue(result);
3599 mUploadMessage = null;
3600 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 default:
3602 break;
3603 }
Leon Scroggins30444232009-09-04 18:36:20 -04003604 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003605 }
3606
3607 /*
3608 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003609 * menu to see the download window. It shows the download window on top of
3610 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003611 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003612 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 Intent intent = new Intent(this,
3614 BrowserDownloadPage.class);
3615 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003616 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617
3618 }
3619
Leon Scroggins160a7e72009-08-14 18:28:01 -04003620 /**
3621 * Open the Go page.
3622 * @param startWithHistory If true, open starting on the history tab.
3623 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003624 */
Leon Scroggins30444232009-09-04 18:36:20 -04003625 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 WebView current = mTabControl.getCurrentWebView();
3627 if (current == null) {
3628 return;
3629 }
3630 Intent intent = new Intent(this,
3631 CombinedBookmarkHistoryActivity.class);
3632 String title = current.getTitle();
3633 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003634 Bitmap thumbnail = createScreenshot(current);
3635
The Android Open Source Project0c908882009-03-03 19:32:16 -08003636 // Just in case the user opens bookmarks before a page finishes loading
3637 // so the current history item, and therefore the page, is null.
3638 if (null == url) {
3639 url = mLastEnteredUrl;
3640 // This can happen.
3641 if (null == url) {
3642 url = mSettings.getHomePage();
3643 }
3644 }
3645 // In case the web page has not yet received its associated title.
3646 if (title == null) {
3647 title = url;
3648 }
3649 intent.putExtra("title", title);
3650 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003651 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003652 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003653 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003654 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 if (startWithHistory) {
3656 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3657 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3658 }
3659 startActivityForResult(intent, COMBO_PAGE);
3660 }
3661
3662 // Called when loading from context menu or LOAD_URL message
3663 private void loadURL(WebView view, String url) {
3664 // In case the user enters nothing.
3665 if (url != null && url.length() != 0 && view != null) {
3666 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003667 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003668 view.loadUrl(url);
3669 }
3670 }
3671 }
3672
The Android Open Source Project0c908882009-03-03 19:32:16 -08003673 private String smartUrlFilter(Uri inUri) {
3674 if (inUri != null) {
3675 return smartUrlFilter(inUri.toString());
3676 }
3677 return null;
3678 }
3679
Feng Qianb34f87a2009-03-24 21:27:26 -07003680 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003681 "(?i)" + // switch on case insensitive matching
3682 "(" + // begin group for schema
3683 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003684 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003685 ")" +
3686 "(.*)" );
3687
3688 /**
3689 * Attempts to determine whether user input is a URL or search
3690 * terms. Anything with a space is passed to search.
3691 *
3692 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3693 * "Http://" converts to "http://"
3694 *
3695 * @return Original or modified URL
3696 *
3697 */
3698 String smartUrlFilter(String url) {
3699
3700 String inUrl = url.trim();
3701 boolean hasSpace = inUrl.indexOf(' ') != -1;
3702
3703 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3704 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003705 // force scheme to lowercase
3706 String scheme = matcher.group(1);
3707 String lcScheme = scheme.toLowerCase();
3708 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003709 inUrl = lcScheme + matcher.group(2);
3710 }
3711 if (hasSpace) {
3712 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003713 }
3714 return inUrl;
3715 }
3716 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003717 // FIXME: Is this the correct place to add to searches?
3718 // what if someone else calls this function?
3719 int shortcut = parseUrlShortcut(inUrl);
3720 if (shortcut != SHORTCUT_INVALID) {
3721 Browser.addSearchUrl(mResolver, inUrl);
3722 String query = inUrl.substring(2);
3723 switch (shortcut) {
3724 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003725 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003726 case SHORTCUT_WIKIPEDIA_SEARCH:
3727 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3728 case SHORTCUT_DICTIONARY_SEARCH:
3729 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3730 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003731 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003732 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003733 }
3734 }
3735 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003736 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003737 return URLUtil.guessUrl(inUrl);
3738 }
3739 }
3740
3741 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003742 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003743 }
3744
Ben Murdochbff2d602009-07-01 20:19:05 +01003745 /* package */ void setShouldShowErrorConsole(boolean flag) {
3746 if (flag == mShouldShowErrorConsole) {
3747 // Nothing to do.
3748 return;
3749 }
3750
3751 mShouldShowErrorConsole = flag;
3752
Grace Kloba22ac16e2009-10-07 18:00:23 -07003753 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3754 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003755
3756 if (flag) {
3757 // Setting the show state of the console will cause it's the layout to be inflated.
3758 if (errorConsole.numberOfErrors() > 0) {
3759 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3760 } else {
3761 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3762 }
3763
3764 // Now we can add it to the main view.
3765 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003766 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003767 ViewGroup.LayoutParams.WRAP_CONTENT));
3768 } else {
3769 mErrorConsoleContainer.removeView(errorConsole);
3770 }
3771
3772 }
3773
Grace Kloba22ac16e2009-10-07 18:00:23 -07003774 boolean shouldShowErrorConsole() {
3775 return mShouldShowErrorConsole;
3776 }
3777
Andrei Popescu163ab742009-10-20 17:58:23 +01003778 private void setStatusBarVisibility(boolean visible) {
3779 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3780 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3781 }
3782
Andrei Popescu56199cc2010-01-12 22:39:16 +00003783
3784 private void sendNetworkType(String type, String subtype) {
3785 WebView w = mTabControl.getCurrentWebView();
3786 if (w != null) {
3787 w.setNetworkType(type, subtype);
3788 }
3789 }
3790
Grace Klobaeb6eef42009-09-15 17:56:32 -07003791 final static int LOCK_ICON_UNSECURE = 0;
3792 final static int LOCK_ICON_SECURE = 1;
3793 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794
The Android Open Source Project0c908882009-03-03 19:32:16 -08003795 private BrowserSettings mSettings;
3796 private TabControl mTabControl;
3797 private ContentResolver mResolver;
3798 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003799 private View mCustomView;
3800 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003801 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802
3803 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3804 // view, we should rewrite this.
3805 private int mCurrentMenuState = 0;
3806 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003807 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003808 private static final int EMPTY_MENU = -1;
3809 private Menu mMenu;
3810
3811 private FindDialog mFindDialog;
3812 // Used to prevent chording to result in firing two shortcuts immediately
3813 // one after another. Fixes bug 1211714.
3814 boolean mCanChord;
3815
3816 private boolean mInLoad;
3817 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003818 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003819
The Android Open Source Project0c908882009-03-03 19:32:16 -08003820 private boolean mActivityInPause = true;
3821
3822 private boolean mMenuIsDown;
3823
The Android Open Source Project0c908882009-03-03 19:32:16 -08003824 private static boolean mInTrace;
3825
3826 // Performance probe
3827 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3828 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3829 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3830 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3831 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3832 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3833 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3834 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3835 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3836 };
3837
3838 private long mStart;
3839 private long mProcessStart;
3840 private long mUserStart;
3841 private long mSystemStart;
3842 private long mIdleStart;
3843 private long mIrqStart;
3844
3845 private long mUiStart;
3846
3847 private Drawable mMixLockIcon;
3848 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849
3850 /* hold a ref so we can auto-cancel if necessary */
3851 private AlertDialog mAlertDialog;
3852
3853 // Wait for credentials before loading google.com
3854 private ProgressDialog mCredsDlg;
3855
3856 // The up-to-date URL and title (these can be different from those stored
3857 // in WebView, since it takes some time for the information in WebView to
3858 // get updated)
3859 private String mUrl;
3860 private String mTitle;
3861
3862 // As PageInfo has different style for landscape / portrait, we have
3863 // to re-open it when configuration changed
3864 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003865 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003866 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3867 // dialog, we should not just dismiss it, but should get back to the
3868 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003869 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003870
3871 // as SSLCertificateOnError has different style for landscape / portrait,
3872 // we have to re-open it when configuration changed
3873 private AlertDialog mSSLCertificateOnErrorDialog;
3874 private WebView mSSLCertificateOnErrorView;
3875 private SslErrorHandler mSSLCertificateOnErrorHandler;
3876 private SslError mSSLCertificateOnErrorError;
3877
3878 // as SSLCertificate has different style for landscape / portrait, we
3879 // have to re-open it when configuration changed
3880 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003881 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003882
3883 // as HttpAuthentication has different style for landscape / portrait, we
3884 // have to re-open it when configuration changed
3885 private AlertDialog mHttpAuthenticationDialog;
3886 private HttpAuthHandler mHttpAuthHandler;
3887
3888 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3889 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003890 ViewGroup.LayoutParams.MATCH_PARENT,
3891 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003892 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3893 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003894 ViewGroup.LayoutParams.MATCH_PARENT,
3895 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003896 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003897 // Google search
3898 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 // Wikipedia search
3900 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3901 // Dictionary search
3902 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3903 // Google Mobile Local search
3904 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3905
3906 final static String QUERY_PLACE_HOLDER = "%s";
3907
3908 // "source" parameter for Google search through search key
3909 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3910 // "source" parameter for Google search through goto menu
3911 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3912 // "source" parameter for Google search through simplily type
3913 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3914 // "source" parameter for Google search suggested by the browser
3915 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3916 // "source" parameter for Google search from unknown source
3917 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3918
3919 private final static String LOGTAG = "browser";
3920
The Android Open Source Project0c908882009-03-03 19:32:16 -08003921 private String mLastEnteredUrl;
3922
3923 private PowerManager.WakeLock mWakeLock;
3924 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3925
3926 private Toast mStopToast;
3927
Leon Scroggins68579392009-09-15 15:31:54 -04003928 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003929
Ben Murdochbff2d602009-07-01 20:19:05 +01003930 private LinearLayout mErrorConsoleContainer = null;
3931 private boolean mShouldShowErrorConsole = false;
3932
The Android Open Source Project0c908882009-03-03 19:32:16 -08003933 // As the ids are dynamically created, we can't guarantee that they will
3934 // be in sequence, so this static array maps ids to a window number.
3935 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3936 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3937 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3938 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3939
3940 // monitor platform changes
3941 private IntentFilter mNetworkStateChangedFilter;
3942 private BroadcastReceiver mNetworkStateIntentReceiver;
3943
Grace Klobab4da0ad2009-05-14 14:45:40 -07003944 private BroadcastReceiver mPackageInstallationReceiver;
3945
The Android Open Source Project0c908882009-03-03 19:32:16 -08003946 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003947 final static int COMBO_PAGE = 1;
3948 final static int DOWNLOAD_PAGE = 2;
3949 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003950 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003951
Andrei Popescu540035d2009-09-18 18:59:20 +01003952 // the default <video> poster
3953 private Bitmap mDefaultVideoPoster;
3954 // the video progress view
3955 private View mVideoProgressView;
3956
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003957 /**
3958 * A UrlData class to abstract how the content will be set to WebView.
3959 * This base class uses loadUrl to show the content.
3960 */
3961 private static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003962 final String mUrl;
3963 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003964 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003965
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003966 UrlData(String url) {
3967 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003968 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003969 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003970 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003971
Leon Scroggins58d56c62010-01-28 15:12:40 -05003972 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003973 this.mUrl = url;
3974 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003975 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3976 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003977 this.mVoiceIntent = intent;
3978 } else {
3979 this.mVoiceIntent = null;
3980 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003981 }
3982
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003983 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003984 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003985 }
3986
Leon Scroggins58d56c62010-01-28 15:12:40 -05003987 public void loadIn(Tab t) {
3988 if (mVoiceIntent != null) {
3989 t.activateVoiceSearchMode(mVoiceIntent);
3990 } else {
3991 t.getWebView().loadUrl(mUrl, mHeaders);
3992 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003993 }
3994 };
3995
Leon Scroggins1f005d32009-08-10 17:36:42 -04003996 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003997}