blob: 6cdd112aadca81b25834c6e6a4ed65fccc9eb45d [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;
26import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040027import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentValues;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070033import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080034import android.content.pm.PackageManager;
35import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.res.Configuration;
37import android.content.res.Resources;
38import android.database.Cursor;
The Android Open Source Project0c908882009-03-03 19:32:16 -080039import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010040import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080041import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040043import android.graphics.PixelFormat;
44import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.net.ConnectivityManager;
47import android.net.Uri;
48import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.http.SslCertificate;
50import android.net.http.SslError;
51import android.os.AsyncTask;
52import android.os.Bundle;
53import android.os.Debug;
54import android.os.Environment;
55import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080056import android.os.Message;
57import android.os.PowerManager;
58import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080059import android.os.ServiceManager;
60import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040062import android.provider.ContactsContract;
63import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080064import android.provider.Downloads;
65import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.text.IClipboard;
67import android.text.TextUtils;
68import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040069import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080070import android.util.Log;
71import android.view.ContextMenu;
72import android.view.Gravity;
73import android.view.KeyEvent;
74import android.view.LayoutInflater;
75import android.view.Menu;
76import android.view.MenuInflater;
77import android.view.MenuItem;
78import android.view.View;
79import android.view.ViewGroup;
80import android.view.Window;
81import android.view.WindowManager;
82import android.view.ContextMenu.ContextMenuInfo;
83import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080084import android.webkit.CookieManager;
85import android.webkit.CookieSyncManager;
86import android.webkit.DownloadListener;
87import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070088import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080089import android.webkit.SslErrorHandler;
90import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010091import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080092import android.webkit.WebChromeClient;
93import android.webkit.WebHistoryItem;
94import android.webkit.WebIconDatabase;
95import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -080096import android.widget.EditText;
97import android.widget.FrameLayout;
98import android.widget.LinearLayout;
99import android.widget.TextView;
100import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800101import android.accounts.Account;
102import android.accounts.AccountManager;
103import android.accounts.AccountManagerFuture;
104import android.accounts.AuthenticatorException;
105import android.accounts.OperationCanceledException;
106import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800107
Dan Egnor5ee906c2009-11-18 12:11:49 -0800108import com.android.common.Patterns;
109
Dan Egnor5ee906c2009-11-18 12:11:49 -0800110import com.google.android.googlelogin.GoogleLoginServiceConstants;
111
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400112import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000114import java.io.IOException;
115import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800116import java.net.MalformedURLException;
117import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700118import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.net.URL;
120import java.net.URLEncoder;
121import java.text.ParseException;
122import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800123import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800124import java.util.regex.Matcher;
125import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126
127public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800128 implements View.OnCreateContextMenuListener, DownloadListener,
129 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800130
Dave Bort31a6d1c2009-04-13 15:56:49 -0700131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
133 */
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
137
Satish Sampath565505b2009-05-29 15:37:27 +0100138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
144
Fred Quintana752b6562009-12-18 10:18:26 -0800145 private Account[] mAccountsGoogle;
146 private Account[] mAccountsPreferHosted;
147
148 private void startReadOfGoogleAccounts() {
149 mAccountsGoogle = null;
150 mAccountsPreferHosted = null;
151
152 AccountManager.get(this).getAccountsByTypeAndFeatures(
153 GoogleLoginServiceConstants.ACCOUNT_TYPE,
154 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
155 this, null);
156 }
157
158 /** This implements AccountManagerCallback<Account[]> */
159 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
160 try {
161 if (mAccountsGoogle == null) {
162 mAccountsGoogle = accountManagerFuture.getResult();
163
164 AccountManager.get(this).getAccountsByTypeAndFeatures(
165 GoogleLoginServiceConstants.ACCOUNT_TYPE,
166 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
167 this, null);
168 } else {
169 mAccountsPreferHosted = accountManagerFuture.getResult();
170 setupHomePage();
171 }
172 } catch (OperationCanceledException e) {
173 setupHomePage();
174 } catch (IOException e) {
175 setupHomePage();
176 } catch (AuthenticatorException e) {
177 setupHomePage();
178 }
179 }
180
The Android Open Source Project0c908882009-03-03 19:32:16 -0800181 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800182 // get the default home page
183 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800184
Fred Quintana752b6562009-12-18 10:18:26 -0800185 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
186 // three cases:
187 //
188 // hostedUser == googleUser
189 // The device has only a google account
190 //
191 // hostedUser != googleUser
192 // The device has a hosted account and a google account
193 //
194 // hostedUser != null, googleUser == null
195 // The device has only a hosted account (so far)
196 String hostedUser = mAccountsPreferHosted.length == 0
197 ? null
198 : mAccountsPreferHosted[0].name;
199 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800200
Fred Quintana752b6562009-12-18 10:18:26 -0800201 // developers might have no accounts at all
202 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700203
Fred Quintana752b6562009-12-18 10:18:26 -0800204 if (googleUser == null || !hostedUser.equals(googleUser)) {
205 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
206 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800207 }
Fred Quintana752b6562009-12-18 10:18:26 -0800208 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800209
Fred Quintana752b6562009-12-18 10:18:26 -0800210 mSettings.setHomePage(BrowserActivity.this, homepage);
211 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800212 }
213
Cary Clarka9771242009-08-11 16:42:26 -0400214 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800215 @Override
216 public Void doInBackground(File... files) {
217 if (files != null) {
218 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400219 if (!f.delete()) {
220 Log.e(LOGTAG, f.getPath() + " was not deleted");
221 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800222 }
223 }
224 return null;
225 }
226 }
227
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400228 /**
229 * This layout holds everything you see below the status bar, including the
230 * error console, the custom view container, and the webviews.
231 */
232 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400233
Grace Kloba22ac16e2009-10-07 18:00:23 -0700234 @Override
235 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700236 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800237 Log.v(LOGTAG, this + " onStart");
238 }
239 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800240 // test the browser in OpenGL
241 // requestWindowFeature(Window.FEATURE_OPENGL);
242
243 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
244
245 mResolver = getContentResolver();
246
Grace Kloba0923d692009-09-23 21:37:25 -0700247 // If this was a web search request, pass it on to the default web
248 // search provider and finish this activity.
249 if (handleWebSearchIntent(getIntent())) {
250 finish();
251 return;
252 }
253
The Android Open Source Project0c908882009-03-03 19:32:16 -0800254 mSecLockIcon = Resources.getSystem().getDrawable(
255 android.R.drawable.ic_secure);
256 mMixLockIcon = Resources.getSystem().getDrawable(
257 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800258
Leon Scroggins81db3662009-06-04 17:45:11 -0400259 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
260 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400261 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
262 .inflate(R.layout.custom_screen, null);
263 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
264 R.id.main_content);
265 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
266 .findViewById(R.id.error_console);
267 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
268 .findViewById(R.id.fullscreen_custom_content);
269 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400270 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400271 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800272
273 // Create the tab control and our initial tab
274 mTabControl = new TabControl(this);
275
276 // Open the icon database and retain all the bookmark urls for favicons
277 retainIconsOnStartup();
278
279 // Keep a settings instance handy.
280 mSettings = BrowserSettings.getInstance();
281 mSettings.setTabControl(mTabControl);
282 mSettings.loadFromDb(this);
283
284 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
285 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
286
Grace Klobaa34f6862009-07-31 16:28:17 -0700287 /* enables registration for changes in network status from
288 http stack */
289 mNetworkStateChangedFilter = new IntentFilter();
290 mNetworkStateChangedFilter.addAction(
291 ConnectivityManager.CONNECTIVITY_ACTION);
292 mNetworkStateIntentReceiver = new BroadcastReceiver() {
293 @Override
294 public void onReceive(Context context, Intent intent) {
295 if (intent.getAction().equals(
296 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700297 boolean noConnectivity = intent.getBooleanExtra(
298 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
299 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700300 }
301 }
302 };
303
Grace Kloba615c6c92009-08-03 10:22:44 -0700304 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
305 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
306 filter.addDataScheme("package");
307 mPackageInstallationReceiver = new BroadcastReceiver() {
308 @Override
309 public void onReceive(Context context, Intent intent) {
310 final String action = intent.getAction();
311 final String packageName = intent.getData()
312 .getSchemeSpecificPart();
313 final boolean replacing = intent.getBooleanExtra(
314 Intent.EXTRA_REPLACING, false);
315 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
316 // if it is replacing, refreshPlugins() when adding
317 return;
318 }
319 PackageManager pm = BrowserActivity.this.getPackageManager();
320 PackageInfo pkgInfo = null;
321 try {
322 pkgInfo = pm.getPackageInfo(packageName,
323 PackageManager.GET_PERMISSIONS);
324 } catch (PackageManager.NameNotFoundException e) {
325 return;
326 }
327 if (pkgInfo != null) {
328 String permissions[] = pkgInfo.requestedPermissions;
329 if (permissions == null) {
330 return;
331 }
332 boolean permissionOk = false;
333 for (String permit : permissions) {
334 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
335 permissionOk = true;
336 break;
337 }
338 }
339 if (permissionOk) {
340 PluginManager.getInstance(BrowserActivity.this)
341 .refreshPlugins(
342 Intent.ACTION_PACKAGE_ADDED
343 .equals(action));
344 }
345 }
346 }
347 };
348 registerReceiver(mPackageInstallationReceiver, filter);
349
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350 if (!mTabControl.restoreState(icicle)) {
351 // clear up the thumbnail directory if we can't restore the state as
352 // none of the files in the directory are referenced any more.
353 new ClearThumbnails().execute(
354 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700355 // there is no quit on Android. But if we can't restore the state,
356 // we can treat it as a new Browser, remove the old session cookies.
357 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800358 final Intent intent = getIntent();
359 final Bundle extra = intent.getExtras();
360 // Create an initial tab.
361 // If the intent is ACTION_VIEW and data is not null, the Browser is
362 // invoked to view the content by another application. In this case,
363 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700364 UrlData urlData = getUrlDataFromIntent(intent);
365
Grace Kloba22ac16e2009-10-07 18:00:23 -0700366 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800367 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700368 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700369 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800370 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800371 attachTabToContentView(t);
372 WebView webView = t.getWebView();
373 if (extra != null) {
374 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
375 if (scale > 0 && scale <= 1000) {
376 webView.setInitialScale(scale);
377 }
378 }
379 // If we are not restoring from an icicle, then there is a high
380 // likely hood this is the first run. So, check to see if the
381 // homepage needs to be configured and copy any plugins from our
382 // asset directory to the data partition.
383 if ((extra == null || !extra.getBoolean("testing"))
384 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800385 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700388 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400389 if (mSettings.isLoginInitialized()) {
390 webView.loadUrl(mSettings.getHomePage());
391 } else {
392 waitForCredentials();
393 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800394 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700395 if (extra != null) {
396 urlData.setPostData(extra
397 .getByteArray(Browser.EXTRA_POST_DATA));
398 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700399 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800400 }
401 } else {
402 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400403 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404 attachTabToContentView(mTabControl.getCurrentTab());
405 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700406
Feng Qianb3c02da2009-06-29 15:58:08 -0700407 // Read JavaScript flags if it exists.
408 String jsFlags = mSettings.getJsFlags();
409 if (jsFlags.trim().length() != 0) {
410 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
411 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800412 }
413
414 @Override
415 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700416 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800417 // When a tab is closed on exit, the current tab index is set to -1.
418 // Reset before proceed as Browser requires the current tab to be set.
419 if (current == null) {
420 // Try to reset the tab in case the index was incorrect.
421 current = mTabControl.getTab(0);
422 if (current == null) {
423 // No tabs at all so just ignore this intent.
424 return;
425 }
426 mTabControl.setCurrentTab(current);
427 attachTabToContentView(current);
428 resetTitleAndIcon(current.getWebView());
429 }
430 final String action = intent.getAction();
431 final int flags = intent.getFlags();
432 if (Intent.ACTION_MAIN.equals(action) ||
433 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
434 // just resume the browser
435 return;
436 }
437 if (Intent.ACTION_VIEW.equals(action)
438 || Intent.ACTION_SEARCH.equals(action)
439 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
440 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100441 // If this was a search request (e.g. search query directly typed into the address bar),
442 // pass it on to the default web search provider.
443 if (handleWebSearchIntent(intent)) {
444 return;
445 }
446
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700447 UrlData urlData = getUrlDataFromIntent(intent);
448 if (urlData.isEmpty()) {
449 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800450 }
Grace Kloba81678d92009-06-30 07:09:56 -0700451 urlData.setPostData(intent
452 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700453
Grace Klobacc634032009-07-28 15:58:19 -0700454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
456 if (Intent.ACTION_VIEW.equals(action)
457 && !getPackageName().equals(appId)
458 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700459 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700460 if (appTab != null) {
461 Log.i(LOGTAG, "Reusing tab for " + appId);
462 // Dismiss the subwindow if applicable.
463 dismissSubWindow(appTab);
464 // Since we might kill the WebView, remove it from the
465 // content view first.
466 removeTabFromContentView(appTab);
467 // Recreate the main WebView after destroying the old one.
468 // If the WebView has the same original url and is on that
469 // page, it can be reused.
470 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700471 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100472
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700473 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400474 switchToTab(mTabControl.getTabIndex(appTab));
475 if (needsLoad) {
476 urlData.loadIn(appTab.getWebView());
477 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700478 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400479 // If the tab was the current tab, we have to attach
480 // it to the view system again.
481 attachTabToContentView(appTab);
482 if (needsLoad) {
483 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700484 }
485 }
486 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400487 } else {
488 // No matching application tab, try to find a regular tab
489 // with a matching url.
490 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400491 if (appTab != null) {
492 if (current != appTab) {
493 switchToTab(mTabControl.getTabIndex(appTab));
494 }
495 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400496 } else {
497 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
498 // will be opened in a new tab unless we have reached
499 // MAX_TABS. Then the url will be opened in the current
500 // tab. If a new tab is created, it will have "true" for
501 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400502 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400503 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700504 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800505 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800506 if (!urlData.isEmpty()
507 && urlData.mUrl.startsWith("about:debug")) {
508 if ("about:debug.dom".equals(urlData.mUrl)) {
509 current.getWebView().dumpDomTree(false);
510 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
511 current.getWebView().dumpDomTree(true);
512 } else if ("about:debug.render".equals(urlData.mUrl)) {
513 current.getWebView().dumpRenderTree(false);
514 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
515 current.getWebView().dumpRenderTree(true);
516 } else if ("about:debug.display".equals(urlData.mUrl)) {
517 current.getWebView().dumpDisplayTree();
518 } else {
519 mSettings.toggleDebugSettings();
520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 return;
522 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400523 // Get rid of the subwindow if it exists
524 dismissSubWindow(current);
525 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800526 }
527 }
528 }
529
Satish Sampath565505b2009-05-29 15:37:27 +0100530 private int parseUrlShortcut(String url) {
531 if (url == null) return SHORTCUT_INVALID;
532
533 // FIXME: quick search, need to be customized by setting
534 if (url.length() > 2 && url.charAt(1) == ' ') {
535 switch (url.charAt(0)) {
536 case 'g': return SHORTCUT_GOOGLE_SEARCH;
537 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
538 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
539 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
540 }
541 }
542 return SHORTCUT_INVALID;
543 }
544
545 /**
546 * Launches the default web search activity with the query parameters if the given intent's data
547 * are identified as plain search terms and not URLs/shortcuts.
548 * @return true if the intent was handled and web search activity was launched, false if not.
549 */
550 private boolean handleWebSearchIntent(Intent intent) {
551 if (intent == null) return false;
552
553 String url = null;
554 final String action = intent.getAction();
555 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700556 Uri data = intent.getData();
557 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100558 } else if (Intent.ACTION_SEARCH.equals(action)
559 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
560 || Intent.ACTION_WEB_SEARCH.equals(action)) {
561 url = intent.getStringExtra(SearchManager.QUERY);
562 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100563 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
564 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100565 }
566
567 /**
568 * Launches the default web search activity with the query parameters if the given url string
569 * was identified as plain search terms and not URL/shortcut.
570 * @return true if the request was handled and web search activity was launched, false if not.
571 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100572 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100573 if (inUrl == null) return false;
574
575 // In general, we shouldn't modify URL from Intent.
576 // But currently, we get the user-typed URL from search box as well.
577 String url = fixUrl(inUrl).trim();
578
579 // URLs and site specific search shortcuts are handled by the regular flow of control, so
580 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800581 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100582 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100583 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
584 return false;
585 }
586
587 Browser.updateVisitedHistory(mResolver, url, false);
588 Browser.addSearchUrl(mResolver, url);
589
590 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
591 intent.addCategory(Intent.CATEGORY_DEFAULT);
592 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100593 if (appData != null) {
594 intent.putExtra(SearchManager.APP_DATA, appData);
595 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100596 if (extraData != null) {
597 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
598 }
Grace Klobacc634032009-07-28 15:58:19 -0700599 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100600 startActivity(intent);
601
602 return true;
603 }
604
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700605 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800606 String url = null;
607 if (intent != null) {
608 final String action = intent.getAction();
609 if (Intent.ACTION_VIEW.equals(action)) {
610 url = smartUrlFilter(intent.getData());
611 if (url != null && url.startsWith("content:")) {
612 /* Append mimetype so webview knows how to display */
613 String mimeType = intent.resolveType(getContentResolver());
614 if (mimeType != null) {
615 url += "?" + mimeType;
616 }
617 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700618 if ("inline:".equals(url)) {
619 return new InlinedUrlData(
620 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
621 intent.getType(),
622 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
623 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
624 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800625 } else if (Intent.ACTION_SEARCH.equals(action)
626 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
627 || Intent.ACTION_WEB_SEARCH.equals(action)) {
628 url = intent.getStringExtra(SearchManager.QUERY);
629 if (url != null) {
630 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500631 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800632 // In general, we shouldn't modify URL from Intent.
633 // But currently, we get the user-typed URL from search box as well.
634 url = fixUrl(url);
635 url = smartUrlFilter(url);
636 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
637 if (url.contains(searchSource)) {
638 String source = null;
639 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
640 if (appData != null) {
641 source = appData.getString(SearchManager.SOURCE);
642 }
643 if (TextUtils.isEmpty(source)) {
644 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
645 }
646 url = url.replace(searchSource, "&source=android-"+source+"&");
647 }
648 }
649 }
650 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700651 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800652 }
653
654 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400655 // FIXME: Converting the url to lower case
656 // duplicates functionality in smartUrlFilter().
657 // However, changing all current callers of fixUrl to
658 // call smartUrlFilter in addition may have unwanted
659 // consequences, and is deferred for now.
660 int colon = inUrl.indexOf(':');
661 boolean allLower = true;
662 for (int index = 0; index < colon; index++) {
663 char ch = inUrl.charAt(index);
664 if (!Character.isLetter(ch)) {
665 break;
666 }
667 allLower &= Character.isLowerCase(ch);
668 if (index == colon - 1 && !allLower) {
669 inUrl = inUrl.substring(0, colon).toLowerCase()
670 + inUrl.substring(colon);
671 }
672 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800673 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
674 return inUrl;
675 if (inUrl.startsWith("http:") ||
676 inUrl.startsWith("https:")) {
677 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
678 inUrl = inUrl.replaceFirst("/", "//");
679 } else inUrl = inUrl.replaceFirst(":", "://");
680 }
681 return inUrl;
682 }
683
Grace Kloba22ac16e2009-10-07 18:00:23 -0700684 @Override
685 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800686 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700687 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800688 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
689 }
690
691 if (!mActivityInPause) {
692 Log.e(LOGTAG, "BrowserActivity is already resumed.");
693 return;
694 }
695
Mike Reed7bfa63b2009-05-28 11:08:32 -0400696 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800697 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400698 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800699
700 if (mWakeLock.isHeld()) {
701 mHandler.removeMessages(RELEASE_WAKELOCK);
702 mWakeLock.release();
703 }
704
705 if (mCredsDlg != null) {
706 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
707 // In case credential request never comes back
708 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
709 }
710 }
711
712 registerReceiver(mNetworkStateIntentReceiver,
713 mNetworkStateChangedFilter);
714 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800715 }
716
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400717 /**
718 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400719 * would change its appearance, use a different TitleBar to show overlayed
720 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400721 */
722 private TitleBar mFakeTitleBar;
723
724 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400725 * Holder for the fake title bar. It will have a foreground shadow, as well
726 * as a white background, so the fake title bar looks like the real one.
727 */
728 private ViewGroup mFakeTitleBarHolder;
729
730 /**
731 * Layout parameters for the fake title bar within mFakeTitleBarHolder
732 */
733 private FrameLayout.LayoutParams mFakeTitleBarParams
734 = new FrameLayout.LayoutParams(
Leon Scrogginsc01e4a82009-09-16 14:41:00 -0400735 ViewGroup.LayoutParams.FILL_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400736 ViewGroup.LayoutParams.WRAP_CONTENT);
737 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400738 * Keeps track of whether the options menu is open. This is important in
739 * determining whether to show or hide the title bar overlay.
740 */
741 private boolean mOptionsMenuOpen;
742
743 /**
744 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
745 * of whether the configuration has changed. The first onMenuOpened call
746 * after a configuration change is simply a reopening of the same menu
747 * (i.e. mIconView did not change).
748 */
749 private boolean mConfigChanged;
750
751 /**
752 * Whether or not the options menu is in its smaller, icon menu form. When
753 * true, we want the title bar overlay to be up. When false, we do not.
754 * Only meaningful if mOptionsMenuOpen is true.
755 */
756 private boolean mIconView;
757
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400758 @Override
759 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400760 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
761 if (mOptionsMenuOpen) {
762 if (mConfigChanged) {
763 // We do not need to make any changes to the state of the
764 // title bar, since the only thing that happened was a
765 // change in orientation
766 mConfigChanged = false;
767 } else {
768 if (mIconView) {
769 // Switching the menu to expanded view, so hide the
770 // title bar.
771 hideFakeTitleBar();
772 mIconView = false;
773 } else {
774 // Switching the menu back to icon view, so show the
775 // title bar once again.
776 showFakeTitleBar();
777 mIconView = true;
778 }
779 }
780 } else {
781 // The options menu is closed, so open it, and show the title
782 showFakeTitleBar();
783 mOptionsMenuOpen = true;
784 mConfigChanged = false;
785 mIconView = true;
786 }
787 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400788 return true;
789 }
790
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400791 /**
792 * Special class used exclusively for the shadow drawn underneath the fake
793 * title bar. The shadow does not need to be drawn if the WebView
794 * underneath is scrolled to the top, because it will draw directly on top
795 * of the embedded shadow.
796 */
797 private static class Shadow extends View {
798 private WebView mWebView;
799
800 public Shadow(Context context, AttributeSet attrs) {
801 super(context, attrs);
802 }
803
804 public void setWebView(WebView view) {
805 mWebView = view;
806 }
807
808 @Override
809 public void draw(Canvas canvas) {
810 // In general onDraw is the method to override, but we care about
811 // whether or not the background gets drawn, which happens in draw()
812 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
813 super.draw(canvas);
814 }
815 // Need to invalidate so that if the scroll position changes, we
816 // still draw as appropriate.
817 invalidate();
818 }
819 }
820
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400821 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400822 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400823 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400824 && !mActivityInPause && decor != null
825 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400826 Rect visRect = new Rect();
827 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
828 if (LOGD_ENABLED) {
829 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
830 }
831 return;
832 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400833
834 WindowManager manager
835 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
836
837 // Add the title bar to the window manager so it can receive touches
838 // while the menu is up
839 WindowManager.LayoutParams params
840 = new WindowManager.LayoutParams(
841 ViewGroup.LayoutParams.FILL_PARENT,
842 ViewGroup.LayoutParams.WRAP_CONTENT,
843 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
844 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400845 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400846 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400847 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400848 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400849 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400850 // XXX : Without providing an offset, the fake title bar will be
851 // placed underneath the status bar. Use the global visible rect
852 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400853 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400854 // Add a holder for the title bar. It also holds a shadow to show
855 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400856 if (mFakeTitleBarHolder == null) {
857 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
858 .inflate(R.layout.title_bar_bg, null);
859 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400860 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
861 R.id.shadow);
862 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400863 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400864 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400865 }
866 }
867
868 @Override
869 public void onOptionsMenuClosed(Menu menu) {
870 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400871 if (!mInLoad) {
872 hideFakeTitleBar();
873 } else if (!mIconView) {
874 // The page is currently loading, and we are in expanded mode, so
875 // we were not showing the menu. Show it once again. It will be
876 // removed when the page finishes.
877 showFakeTitleBar();
878 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400879 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700880
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400881 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400882 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400883 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
884 mFakeTitleBarHolder.getLayoutParams();
885 WebView mainView = mTabControl.getCurrentWebView();
886 // Although we decided whether or not to animate based on the current
887 // scroll position, the scroll position may have changed since the
888 // fake title bar was displayed. Make sure it has the appropriate
889 // animation/lack thereof before removing.
890 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400891 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400892 WindowManager manager
893 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400894 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400895 mFakeTitleBarHolder.removeView(mFakeTitleBar);
896 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400897 }
898
The Android Open Source Project0c908882009-03-03 19:32:16 -0800899 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400900 * Special method for the fake title bar to call when displaying its context
901 * menu, since it is in its own Window, and its parent does not show a
902 * context menu.
903 */
904 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400905 if (null == mTitleBar.getParent()) {
906 return;
907 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400908 openContextMenu(mTitleBar);
909 }
910
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400911 @Override
912 public void onContextMenuClosed(Menu menu) {
913 super.onContextMenuClosed(menu);
914 if (mInLoad) {
915 showFakeTitleBar();
916 }
917 }
918
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400919 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800920 * onSaveInstanceState(Bundle map)
921 * onSaveInstanceState is called right before onStop(). The map contains
922 * the saved state.
923 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700924 @Override
925 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700926 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
928 }
929 // the default implementation requires each view to have an id. As the
930 // browser handles the state itself and it doesn't use id for the views,
931 // don't call the default implementation. Otherwise it will trigger the
932 // warning like this, "couldn't save which view has focus because the
933 // focused view XXX has no id".
934
935 // Save all the tabs
936 mTabControl.saveState(outState);
937 }
938
Grace Kloba22ac16e2009-10-07 18:00:23 -0700939 @Override
940 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800941 super.onPause();
942
943 if (mActivityInPause) {
944 Log.e(LOGTAG, "BrowserActivity is already paused.");
945 return;
946 }
947
Mike Reed7bfa63b2009-05-28 11:08:32 -0400948 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800949 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400950 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800951 mWakeLock.acquire();
952 mHandler.sendMessageDelayed(mHandler
953 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
954 }
955
956 // Clear the credentials toast if it is up
957 if (mCredsDlg != null && mCredsDlg.isShowing()) {
958 mCredsDlg.dismiss();
959 }
960 mCredsDlg = null;
961
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400962 // FIXME: This removes the active tabs page and resets the menu to
963 // MAIN_MENU. A better solution might be to do this work in onNewIntent
964 // but then we would need to save it in onSaveInstanceState and restore
965 // it in onCreate/onRestoreInstanceState
966 if (mActiveTabsPage != null) {
967 removeActiveTabPage(true);
968 }
969
The Android Open Source Project0c908882009-03-03 19:32:16 -0800970 cancelStopToast();
971
972 // unregister network state listener
973 unregisterReceiver(mNetworkStateIntentReceiver);
974 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 }
976
Grace Kloba22ac16e2009-10-07 18:00:23 -0700977 @Override
978 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700979 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800980 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
981 }
982 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700983
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400984 if (mUploadMessage != null) {
985 mUploadMessage.onReceiveValue(null);
986 mUploadMessage = null;
987 }
988
Grace Kloba0923d692009-09-23 21:37:25 -0700989 if (mTabControl == null) return;
990
Grace Kloba1fc98a32009-10-21 13:23:08 -0700991 // Remove the fake title bar if it is there
992 hideFakeTitleBar();
993
The Android Open Source Project0c908882009-03-03 19:32:16 -0800994 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700995 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700996 if (t != null) {
997 dismissSubWindow(t);
998 removeTabFromContentView(t);
999 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001000 // Destroy all the tabs
1001 mTabControl.destroy();
1002 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003
Grace Klobab4da0ad2009-05-14 14:45:40 -07001004 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001005 }
1006
1007 @Override
1008 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001009 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 super.onConfigurationChanged(newConfig);
1011
1012 if (mPageInfoDialog != null) {
1013 mPageInfoDialog.dismiss();
1014 showPageInfo(
1015 mPageInfoView,
1016 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1017 }
1018 if (mSSLCertificateDialog != null) {
1019 mSSLCertificateDialog.dismiss();
1020 showSSLCertificate(
1021 mSSLCertificateView);
1022 }
1023 if (mSSLCertificateOnErrorDialog != null) {
1024 mSSLCertificateOnErrorDialog.dismiss();
1025 showSSLCertificateOnError(
1026 mSSLCertificateOnErrorView,
1027 mSSLCertificateOnErrorHandler,
1028 mSSLCertificateOnErrorError);
1029 }
1030 if (mHttpAuthenticationDialog != null) {
1031 String title = ((TextView) mHttpAuthenticationDialog
1032 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1033 .toString();
1034 String name = ((TextView) mHttpAuthenticationDialog
1035 .findViewById(R.id.username_edit)).getText().toString();
1036 String password = ((TextView) mHttpAuthenticationDialog
1037 .findViewById(R.id.password_edit)).getText().toString();
1038 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1039 .getId();
1040 mHttpAuthenticationDialog.dismiss();
1041 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1042 name, password, focusId);
1043 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 }
1045
Grace Kloba22ac16e2009-10-07 18:00:23 -07001046 @Override
1047 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 super.onLowMemory();
1049 mTabControl.freeMemory();
1050 }
1051
Mike Reed7bfa63b2009-05-28 11:08:32 -04001052 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001053 Tab tab = mTabControl.getCurrentTab();
1054 boolean inLoad = tab.inLoad();
1055 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001056 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001057 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001058 if (w != null) {
1059 w.resumeTimers();
1060 }
1061 return true;
1062 } else {
1063 return false;
1064 }
1065 }
1066
Mike Reed7bfa63b2009-05-28 11:08:32 -04001067 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001068 Tab tab = mTabControl.getCurrentTab();
1069 boolean inLoad = tab.inLoad();
1070 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 CookieSyncManager.getInstance().stopSync();
1072 WebView w = mTabControl.getCurrentWebView();
1073 if (w != null) {
1074 w.pauseTimers();
1075 }
1076 return true;
1077 } else {
1078 return false;
1079 }
1080 }
1081
Leon Scroggins1f005d32009-08-10 17:36:42 -04001082 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001083 /*
1084 * This function is called when we are launching for the first time. We
1085 * are waiting for the login credentials before loading Google home
1086 * pages. This way the user will be logged in straight away.
1087 */
1088 private void waitForCredentials() {
1089 // Show a toast
1090 mCredsDlg = new ProgressDialog(this);
1091 mCredsDlg.setIndeterminate(true);
1092 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1093 // If the user cancels the operation, then cancel the Google
1094 // Credentials request.
1095 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1096 mCredsDlg.show();
1097
1098 // We set a timeout for the retrieval of credentials in onResume()
1099 // as that is when we have freed up some CPU time to get
1100 // the login credentials.
1101 }
1102
1103 /*
1104 * If we have received the credentials or we have timed out and we are
1105 * showing the credentials dialog, then it is time to move on.
1106 */
1107 private void resumeAfterCredentials() {
1108 if (mCredsDlg == null) {
1109 return;
1110 }
1111
1112 // Clear the toast
1113 if (mCredsDlg.isShowing()) {
1114 mCredsDlg.dismiss();
1115 }
1116 mCredsDlg = null;
1117
1118 // Clear any pending timeout
1119 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1120
1121 // Load the page
1122 WebView w = mTabControl.getCurrentWebView();
1123 if (w != null) {
1124 w.loadUrl(mSettings.getHomePage());
1125 }
1126
1127 // Update the settings, need to do this last as it can take a moment
1128 // to persist the settings. In the mean time we could be loading
1129 // content.
1130 mSettings.setLoginInitialized(this);
1131 }
1132
1133 // Open the icon database and retain all the icons for visited sites.
1134 private void retainIconsOnStartup() {
1135 final WebIconDatabase db = WebIconDatabase.getInstance();
1136 db.open(getDir("icons", 0).getPath());
1137 try {
1138 Cursor c = Browser.getAllBookmarks(mResolver);
1139 if (!c.moveToFirst()) {
1140 c.deactivate();
1141 return;
1142 }
1143 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1144 do {
1145 String url = c.getString(urlIndex);
1146 db.retainIconForPageUrl(url);
1147 } while (c.moveToNext());
1148 c.deactivate();
1149 } catch (IllegalStateException e) {
1150 Log.e(LOGTAG, "retainIconsOnStartup", e);
1151 }
1152 }
1153
1154 // Helper method for getting the top window.
1155 WebView getTopWindow() {
1156 return mTabControl.getCurrentTopWebView();
1157 }
1158
Grace Kloba22ac16e2009-10-07 18:00:23 -07001159 TabControl getTabControl() {
1160 return mTabControl;
1161 }
1162
The Android Open Source Project0c908882009-03-03 19:32:16 -08001163 @Override
1164 public boolean onCreateOptionsMenu(Menu menu) {
1165 super.onCreateOptionsMenu(menu);
1166
1167 MenuInflater inflater = getMenuInflater();
1168 inflater.inflate(R.menu.browser, menu);
1169 mMenu = menu;
1170 updateInLoadMenuItems();
1171 return true;
1172 }
1173
1174 /**
1175 * As the menu can be open when loading state changes
1176 * we must manually update the state of the stop/reload menu
1177 * item
1178 */
1179 private void updateInLoadMenuItems() {
1180 if (mMenu == null) {
1181 return;
1182 }
1183 MenuItem src = mInLoad ?
1184 mMenu.findItem(R.id.stop_menu_id):
1185 mMenu.findItem(R.id.reload_menu_id);
1186 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1187 dest.setIcon(src.getIcon());
1188 dest.setTitle(src.getTitle());
1189 }
1190
1191 @Override
1192 public boolean onContextItemSelected(MenuItem item) {
1193 // chording is not an issue with context menus, but we use the same
1194 // options selector, so set mCanChord to true so we can access them.
1195 mCanChord = true;
1196 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001197 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001198 // For the context menu from the title bar
1199 case R.id.title_bar_share_page_url:
1200 case R.id.title_bar_copy_page_url:
1201 WebView mainView = mTabControl.getCurrentWebView();
1202 if (null == mainView) {
1203 return false;
1204 }
1205 if (id == R.id.title_bar_share_page_url) {
1206 Browser.sendString(this, mainView.getUrl());
1207 } else {
1208 copy(mainView.getUrl());
1209 }
1210 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001211 // -- Browser context menu
1212 case R.id.open_context_menu_id:
1213 case R.id.open_newtab_context_menu_id:
1214 case R.id.bookmark_context_menu_id:
1215 case R.id.save_link_context_menu_id:
1216 case R.id.share_link_context_menu_id:
1217 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001218 final WebView webView = getTopWindow();
1219 if (null == webView) {
1220 return false;
1221 }
1222 final HashMap hrefMap = new HashMap();
1223 hrefMap.put("webview", webView);
1224 final Message msg = mHandler.obtainMessage(
1225 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001226 webView.requestFocusNodeHref(msg);
1227 break;
1228
1229 default:
1230 // For other context menus
1231 return onOptionsItemSelected(item);
1232 }
1233 mCanChord = false;
1234 return true;
1235 }
1236
1237 private Bundle createGoogleSearchSourceBundle(String source) {
1238 Bundle bundle = new Bundle();
1239 bundle.putString(SearchManager.SOURCE, source);
1240 return bundle;
1241 }
1242
1243 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001244 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001245 */
1246 @Override
1247 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001248 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001249 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001250 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001251 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001252 return true;
1253 }
1254
1255 @Override
1256 public void startSearch(String initialQuery, boolean selectInitialQuery,
1257 Bundle appSearchData, boolean globalSearch) {
1258 if (appSearchData == null) {
1259 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1260 }
1261 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1262 }
1263
Leon Scroggins1f005d32009-08-10 17:36:42 -04001264 /**
1265 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1266 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001267 * @param index Index of the tab to change to, as defined by
1268 * mTabControl.getTabIndex(Tab t).
1269 * @return boolean True if we successfully switched to a different tab. If
1270 * the indexth tab is null, or if that tab is the same as
1271 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001272 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001273 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001274 Tab tab = mTabControl.getTab(index);
1275 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001276 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001277 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001278 }
1279 if (currentTab != null) {
1280 // currentTab may be null if it was just removed. In that case,
1281 // we do not need to remove it
1282 removeTabFromContentView(currentTab);
1283 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 mTabControl.setCurrentTab(tab);
1285 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001286 resetTitleIconAndProgress();
1287 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001288 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001289 }
1290
Grace Kloba22ac16e2009-10-07 18:00:23 -07001291 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001292 return openTabAndShow(mSettings.getHomePage(), false, null);
1293 }
1294
Leon Scroggins1f005d32009-08-10 17:36:42 -04001295 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001296 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001297 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001298 // This is the last tab. Open a new one, with the home
1299 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001300 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001301 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001302 return;
1303 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001304 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001305 int indexToShow = -1;
1306 if (parent != null) {
1307 indexToShow = mTabControl.getTabIndex(parent);
1308 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001309 final int currentIndex = mTabControl.getCurrentIndex();
1310 // Try to move to the tab to the right
1311 indexToShow = currentIndex + 1;
1312 if (indexToShow > mTabControl.getTabCount() - 1) {
1313 // Try to move to the tab to the left
1314 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 }
1316 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001317 if (switchToTab(indexToShow)) {
1318 // Close window
1319 closeTab(current);
1320 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001321 }
1322
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001323 private ActiveTabsPage mActiveTabsPage;
1324
1325 /**
1326 * Remove the active tabs page.
1327 * @param needToAttach If true, the active tabs page did not attach a tab
1328 * to the content view, so we need to do that here.
1329 */
1330 /* package */ void removeActiveTabPage(boolean needToAttach) {
1331 mContentView.removeView(mActiveTabsPage);
1332 mActiveTabsPage = null;
1333 mMenuState = R.id.MAIN_MENU;
1334 if (needToAttach) {
1335 attachTabToContentView(mTabControl.getCurrentTab());
1336 }
1337 getTopWindow().requestFocus();
1338 }
1339
The Android Open Source Project0c908882009-03-03 19:32:16 -08001340 @Override
1341 public boolean onOptionsItemSelected(MenuItem item) {
1342 if (!mCanChord) {
1343 // The user has already fired a shortcut with this hold down of the
1344 // menu key.
1345 return false;
1346 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001347 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001348 return false;
1349 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001350 if (mMenuIsDown) {
1351 // The shortcut action consumes the MENU. Even if it is still down,
1352 // it won't trigger the next shortcut action. In the case of the
1353 // shortcut action triggering a new activity, like Bookmarks, we
1354 // won't get onKeyUp for MENU. So it is important to reset it here.
1355 mMenuIsDown = false;
1356 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001357 switch (item.getItemId()) {
1358 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001359 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001360 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001361 break;
1362
Leon Scroggins64b80f32009-08-07 12:03:34 -04001363 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001364 onSearchRequested();
1365 break;
1366
1367 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001368 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001369 break;
1370
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001371 case R.id.active_tabs_menu_id:
1372 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1373 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001374 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001375 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1376 mActiveTabsPage.requestFocus();
1377 mMenuState = EMPTY_MENU;
1378 break;
1379
Leon Scroggins1f005d32009-08-10 17:36:42 -04001380 case R.id.add_bookmark_menu_id:
1381 Intent i = new Intent(BrowserActivity.this,
1382 AddBookmarkPage.class);
1383 WebView w = getTopWindow();
1384 i.putExtra("url", w.getUrl());
1385 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001386 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001387 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001388 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001389 break;
1390
1391 case R.id.stop_reload_menu_id:
1392 if (mInLoad) {
1393 stopLoading();
1394 } else {
1395 getTopWindow().reload();
1396 }
1397 break;
1398
1399 case R.id.back_menu_id:
1400 getTopWindow().goBack();
1401 break;
1402
1403 case R.id.forward_menu_id:
1404 getTopWindow().goForward();
1405 break;
1406
1407 case R.id.close_menu_id:
1408 // Close the subwindow if it exists.
1409 if (mTabControl.getCurrentSubWindow() != null) {
1410 dismissSubWindow(mTabControl.getCurrentTab());
1411 break;
1412 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001413 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001414 break;
1415
1416 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001417 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001418 if (current != null) {
1419 dismissSubWindow(current);
1420 current.getWebView().loadUrl(mSettings.getHomePage());
1421 }
1422 break;
1423
1424 case R.id.preferences_menu_id:
1425 Intent intent = new Intent(this,
1426 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001427 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1428 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001429 startActivityForResult(intent, PREFERENCES_PAGE);
1430 break;
1431
1432 case R.id.find_menu_id:
1433 if (null == mFindDialog) {
1434 mFindDialog = new FindDialog(this);
1435 }
1436 mFindDialog.setWebView(getTopWindow());
1437 mFindDialog.show();
1438 mMenuState = EMPTY_MENU;
1439 break;
1440
1441 case R.id.select_text_id:
1442 getTopWindow().emulateShiftHeld();
1443 break;
1444 case R.id.page_info_menu_id:
1445 showPageInfo(mTabControl.getCurrentTab(), false);
1446 break;
1447
1448 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001449 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001450 break;
1451
1452 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001453 Browser.sendString(this, getTopWindow().getUrl(),
1454 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 break;
1456
1457 case R.id.dump_nav_menu_id:
1458 getTopWindow().debugDump();
1459 break;
1460
1461 case R.id.zoom_in_menu_id:
1462 getTopWindow().zoomIn();
1463 break;
1464
1465 case R.id.zoom_out_menu_id:
1466 getTopWindow().zoomOut();
1467 break;
1468
1469 case R.id.view_downloads_menu_id:
1470 viewDownloads(null);
1471 break;
1472
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 case R.id.window_one_menu_id:
1474 case R.id.window_two_menu_id:
1475 case R.id.window_three_menu_id:
1476 case R.id.window_four_menu_id:
1477 case R.id.window_five_menu_id:
1478 case R.id.window_six_menu_id:
1479 case R.id.window_seven_menu_id:
1480 case R.id.window_eight_menu_id:
1481 {
1482 int menuid = item.getItemId();
1483 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1484 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001485 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001486 if (desiredTab != null &&
1487 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001488 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001489 }
1490 break;
1491 }
1492 }
1493 }
1494 break;
1495
1496 default:
1497 if (!super.onOptionsItemSelected(item)) {
1498 return false;
1499 }
1500 // Otherwise fall through.
1501 }
1502 mCanChord = false;
1503 return true;
1504 }
1505
1506 public void closeFind() {
1507 mMenuState = R.id.MAIN_MENU;
1508 }
1509
Grace Kloba22ac16e2009-10-07 18:00:23 -07001510 @Override
1511 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001512 // This happens when the user begins to hold down the menu key, so
1513 // allow them to chord to get a shortcut.
1514 mCanChord = true;
1515 // Note: setVisible will decide whether an item is visible; while
1516 // setEnabled() will decide whether an item is enabled, which also means
1517 // whether the matching shortcut key will function.
1518 super.onPrepareOptionsMenu(menu);
1519 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001520 case EMPTY_MENU:
1521 if (mCurrentMenuState != mMenuState) {
1522 menu.setGroupVisible(R.id.MAIN_MENU, false);
1523 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1524 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001525 }
1526 break;
1527 default:
1528 if (mCurrentMenuState != mMenuState) {
1529 menu.setGroupVisible(R.id.MAIN_MENU, true);
1530 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1531 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 }
1533 final WebView w = getTopWindow();
1534 boolean canGoBack = false;
1535 boolean canGoForward = false;
1536 boolean isHome = false;
1537 if (w != null) {
1538 canGoBack = w.canGoBack();
1539 canGoForward = w.canGoForward();
1540 isHome = mSettings.getHomePage().equals(w.getUrl());
1541 }
1542 final MenuItem back = menu.findItem(R.id.back_menu_id);
1543 back.setEnabled(canGoBack);
1544
1545 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1546 home.setEnabled(!isHome);
1547
1548 menu.findItem(R.id.forward_menu_id)
1549 .setEnabled(canGoForward);
1550
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001551 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001552 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001553
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 // decide whether to show the share link option
1555 PackageManager pm = getPackageManager();
1556 Intent send = new Intent(Intent.ACTION_SEND);
1557 send.setType("text/plain");
1558 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1559 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1560
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 boolean isNavDump = mSettings.isNavDump();
1562 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1563 nav.setVisible(isNavDump);
1564 nav.setEnabled(isNavDump);
1565 break;
1566 }
1567 mCurrentMenuState = mMenuState;
1568 return true;
1569 }
1570
1571 @Override
1572 public void onCreateContextMenu(ContextMenu menu, View v,
1573 ContextMenuInfo menuInfo) {
1574 WebView webview = (WebView) v;
1575 WebView.HitTestResult result = webview.getHitTestResult();
1576 if (result == null) {
1577 return;
1578 }
1579
1580 int type = result.getType();
1581 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1582 Log.w(LOGTAG,
1583 "We should not show context menu when nothing is touched");
1584 return;
1585 }
1586 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1587 // let TextView handles context menu
1588 return;
1589 }
1590
1591 // Note, http://b/issue?id=1106666 is requesting that
1592 // an inflated menu can be used again. This is not available
1593 // yet, so inflate each time (yuk!)
1594 MenuInflater inflater = getMenuInflater();
1595 inflater.inflate(R.menu.browsercontext, menu);
1596
1597 // Show the correct menu group
1598 String extra = result.getExtra();
1599 menu.setGroupVisible(R.id.PHONE_MENU,
1600 type == WebView.HitTestResult.PHONE_TYPE);
1601 menu.setGroupVisible(R.id.EMAIL_MENU,
1602 type == WebView.HitTestResult.EMAIL_TYPE);
1603 menu.setGroupVisible(R.id.GEO_MENU,
1604 type == WebView.HitTestResult.GEO_TYPE);
1605 menu.setGroupVisible(R.id.IMAGE_MENU,
1606 type == WebView.HitTestResult.IMAGE_TYPE
1607 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1608 menu.setGroupVisible(R.id.ANCHOR_MENU,
1609 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1610 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1611
1612 // Setup custom handling depending on the type
1613 switch (type) {
1614 case WebView.HitTestResult.PHONE_TYPE:
1615 menu.setHeaderTitle(Uri.decode(extra));
1616 menu.findItem(R.id.dial_context_menu_id).setIntent(
1617 new Intent(Intent.ACTION_VIEW, Uri
1618 .parse(WebView.SCHEME_TEL + extra)));
1619 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1620 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001621 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001622 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1623 addIntent);
1624 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1625 new Copy(extra));
1626 break;
1627
1628 case WebView.HitTestResult.EMAIL_TYPE:
1629 menu.setHeaderTitle(extra);
1630 menu.findItem(R.id.email_context_menu_id).setIntent(
1631 new Intent(Intent.ACTION_VIEW, Uri
1632 .parse(WebView.SCHEME_MAILTO + extra)));
1633 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1634 new Copy(extra));
1635 break;
1636
1637 case WebView.HitTestResult.GEO_TYPE:
1638 menu.setHeaderTitle(extra);
1639 menu.findItem(R.id.map_context_menu_id).setIntent(
1640 new Intent(Intent.ACTION_VIEW, Uri
1641 .parse(WebView.SCHEME_GEO
1642 + URLEncoder.encode(extra))));
1643 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1644 new Copy(extra));
1645 break;
1646
1647 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1648 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1649 TextView titleView = (TextView) LayoutInflater.from(this)
1650 .inflate(android.R.layout.browser_link_context_header,
1651 null);
1652 titleView.setText(extra);
1653 menu.setHeaderView(titleView);
1654 // decide whether to show the open link in new tab option
1655 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001656 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001657 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1658 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001659 PackageManager pm = getPackageManager();
1660 Intent send = new Intent(Intent.ACTION_SEND);
1661 send.setType("text/plain");
1662 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1663 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1664 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1665 break;
1666 }
1667 // otherwise fall through to handle image part
1668 case WebView.HitTestResult.IMAGE_TYPE:
1669 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1670 menu.setHeaderTitle(extra);
1671 }
1672 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1673 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1674 menu.findItem(R.id.download_context_menu_id).
1675 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001676 menu.findItem(R.id.set_wallpaper_context_menu_id).
1677 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001678 break;
1679
1680 default:
1681 Log.w(LOGTAG, "We should not get here.");
1682 break;
1683 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001684 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001685 }
1686
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001688 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001689 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001690 // Attach the container that contains the main WebView and any other UI
1691 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001692 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001693
1694 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001695 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001696 if (errorConsole.numberOfErrors() == 0) {
1697 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1698 } else {
1699 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1700 }
1701
1702 mErrorConsoleContainer.addView(errorConsole,
1703 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1704 ViewGroup.LayoutParams.WRAP_CONTENT));
1705 }
1706
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001707 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001708 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001709 // Request focus on the top window.
1710 t.getTopWindow().requestFocus();
1711 }
1712
1713 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001714 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001715 t.attachSubWindow(mContentView);
1716 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001717 }
1718
1719 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001720 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001721 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001722 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001723
Grace Kloba22ac16e2009-10-07 18:00:23 -07001724 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1725 if (errorConsole != null) {
1726 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727 }
1728
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001729 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001730 if (view != null) {
1731 view.setEmbeddedTitleBar(null);
1732 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001733 }
1734
1735 // Remove the sub window if it exists. Also called by TabControl when the
1736 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001737 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001738 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001739 // dismiss the subwindow. This will destroy the WebView.
1740 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001741 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001742 }
1743
Leon Scroggins1f005d32009-08-10 17:36:42 -04001744 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001745 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001747 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001748 }
1749
1750 // This method does a ton of stuff. It will attempt to create a new tab
1751 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001752 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1754 String appId) {
1755 final Tab currentTab = mTabControl.getCurrentTab();
1756 if (mTabControl.canCreateNewTab()) {
1757 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1758 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001759 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001760 // If the last tab was removed from the active tabs page, currentTab
1761 // will be null.
1762 if (currentTab != null) {
1763 removeTabFromContentView(currentTab);
1764 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001765 // We must set the new tab as the current tab to reflect the old
1766 // animation behavior.
1767 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001768 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001769 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001770 urlData.loadIn(webview);
1771 }
1772 return tab;
1773 } else {
1774 // Get rid of the subwindow if it exists
1775 dismissSubWindow(currentTab);
1776 if (!urlData.isEmpty()) {
1777 // Load the given url.
1778 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001779 }
1780 }
Grace Klobac9181842009-04-14 08:53:22 -07001781 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 }
1783
Grace Kloba22ac16e2009-10-07 18:00:23 -07001784 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001785 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001786 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001787 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001788 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001789 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001790 }
Grace Klobac9181842009-04-14 08:53:22 -07001791 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001793 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 }
1795 }
1796
1797 private class Copy implements OnMenuItemClickListener {
1798 private CharSequence mText;
1799
1800 public boolean onMenuItemClick(MenuItem item) {
1801 copy(mText);
1802 return true;
1803 }
1804
1805 public Copy(CharSequence toCopy) {
1806 mText = toCopy;
1807 }
1808 }
1809
1810 private class Download implements OnMenuItemClickListener {
1811 private String mText;
1812
1813 public boolean onMenuItemClick(MenuItem item) {
1814 onDownloadStartNoStream(mText, null, null, null, -1);
1815 return true;
1816 }
1817
1818 public Download(String toDownload) {
1819 mText = toDownload;
1820 }
1821 }
1822
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001823 private class SetAsWallpaper extends Thread implements
1824 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1825 private URL mUrl;
1826 private ProgressDialog mWallpaperProgress;
1827 private boolean mCanceled = false;
1828
1829 public SetAsWallpaper(String url) {
1830 try {
1831 mUrl = new URL(url);
1832 } catch (MalformedURLException e) {
1833 mUrl = null;
1834 }
1835 }
1836
1837 public void onCancel(DialogInterface dialog) {
1838 mCanceled = true;
1839 }
1840
1841 public boolean onMenuItemClick(MenuItem item) {
1842 if (mUrl != null) {
1843 // The user may have tried to set a image with a large file size as their
1844 // background so it may take a few moments to perform the operation. Display
1845 // a progress spinner while it is working.
1846 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1847 mWallpaperProgress.setIndeterminate(true);
1848 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1849 mWallpaperProgress.setCancelable(true);
1850 mWallpaperProgress.setOnCancelListener(this);
1851 mWallpaperProgress.show();
1852 start();
1853 }
1854 return true;
1855 }
1856
1857 public void run() {
1858 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1859 try {
1860 // TODO: This will cause the resource to be downloaded again, when we
1861 // should in most cases be able to grab it from the cache. To fix this
1862 // we should query WebCore to see if we can access a cached version and
1863 // instead open an input stream on that. This pattern could also be used
1864 // in the download manager where the same problem exists.
1865 InputStream inputstream = mUrl.openStream();
1866 if (inputstream != null) {
1867 setWallpaper(inputstream);
1868 }
1869 } catch (IOException e) {
1870 Log.e(LOGTAG, "Unable to set new wallpaper");
1871 // Act as though the user canceled the operation so we try to
1872 // restore the old wallpaper.
1873 mCanceled = true;
1874 }
1875
1876 if (mCanceled) {
1877 // Restore the old wallpaper if the user cancelled whilst we were setting
1878 // the new wallpaper.
1879 int width = oldWallpaper.getIntrinsicWidth();
1880 int height = oldWallpaper.getIntrinsicHeight();
1881 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1882 Canvas canvas = new Canvas(bm);
1883 oldWallpaper.setBounds(0, 0, width, height);
1884 oldWallpaper.draw(canvas);
1885 try {
1886 setWallpaper(bm);
1887 } catch (IOException e) {
1888 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1889 }
1890 mCanceled = false;
1891 }
1892
1893 if (mWallpaperProgress.isShowing()) {
1894 mWallpaperProgress.dismiss();
1895 }
1896 }
1897 }
1898
The Android Open Source Project0c908882009-03-03 19:32:16 -08001899 private void copy(CharSequence text) {
1900 try {
1901 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1902 if (clip != null) {
1903 clip.setClipboardText(text);
1904 }
1905 } catch (android.os.RemoteException e) {
1906 Log.e(LOGTAG, "Copy failed", e);
1907 }
1908 }
1909
1910 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001911 * Resets the browser title-view to whatever it must be
1912 * (for example, if we had a loading error)
1913 * When we have a new page, we call resetTitle, when we
1914 * have to reset the titlebar to whatever it used to be
1915 * (for example, if the user chose to stop loading), we
1916 * call resetTitleAndRevertLockIcon.
1917 */
1918 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001919 mTabControl.getCurrentTab().revertLockIcon();
1920 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001921 resetTitleIconAndProgress();
1922 }
1923
1924 /**
1925 * Reset the title, favicon, and progress.
1926 */
1927 private void resetTitleIconAndProgress() {
1928 WebView current = mTabControl.getCurrentWebView();
1929 if (current == null) {
1930 return;
1931 }
1932 resetTitleAndIcon(current);
1933 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001934 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001935 }
1936
1937 // Reset the title and the icon based on the given item.
1938 private void resetTitleAndIcon(WebView view) {
1939 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1940 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001941 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001942 setFavicon(item.getFavicon());
1943 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001944 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 setFavicon(null);
1946 }
1947 }
1948
1949 /**
1950 * Sets a title composed of the URL and the title string.
1951 * @param url The URL of the site being loaded.
1952 * @param title The title of the site being loaded.
1953 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001954 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 mUrl = url;
1956 mTitle = title;
1957
Leon Scroggins68579392009-09-15 15:31:54 -04001958 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001959 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001960 }
1961
1962 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 * @param url The URL to build a title version of the URL from.
1964 * @return The title version of the URL or null if fails.
1965 * The title version of the URL can be either the URL hostname,
1966 * or the hostname with an "https://" prefix (for secure URLs),
1967 * or an empty string if, for example, the URL in question is a
1968 * file:// URL with no hostname.
1969 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001970 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001971 String titleUrl = null;
1972
1973 if (url != null) {
1974 try {
1975 // parse the url string
1976 URL urlObj = new URL(url);
1977 if (urlObj != null) {
1978 titleUrl = "";
1979
1980 String protocol = urlObj.getProtocol();
1981 String host = urlObj.getHost();
1982
1983 if (host != null && 0 < host.length()) {
1984 titleUrl = host;
1985 if (protocol != null) {
1986 // if a secure site, add an "https://" prefix!
1987 if (protocol.equalsIgnoreCase("https")) {
1988 titleUrl = protocol + "://" + host;
1989 }
1990 }
1991 }
1992 }
1993 } catch (MalformedURLException e) {}
1994 }
1995
1996 return titleUrl;
1997 }
1998
1999 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002000 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002001 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002002 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002003 }
2004
2005 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002006 * Close the tab, remove its associated title bar, and adjust mTabControl's
2007 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002008 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002009 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002010 int currentIndex = mTabControl.getCurrentIndex();
2011 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002012 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002013 if (currentIndex >= removeIndex && currentIndex != 0) {
2014 currentIndex--;
2015 }
2016 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002017 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002018 }
2019
2020 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002021 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002022 if (current == null) {
2023 /*
2024 * Instead of finishing the activity, simply push this to the back
2025 * of the stack and let ActivityManager to choose the foreground
2026 * activity. As BrowserActivity is singleTask, it will be always the
2027 * root of the task. So we can use either true or false for
2028 * moveTaskToBack().
2029 */
2030 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002031 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002032 }
2033 WebView w = current.getWebView();
2034 if (w.canGoBack()) {
2035 w.goBack();
2036 } else {
2037 // Check to see if we are closing a window that was created by
2038 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002039 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002040 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002041 switchToTab(mTabControl.getTabIndex(parent));
2042 // Now we close the other tab
2043 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002044 } else {
2045 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002046 // force the tab's inLoad() to be false as we are going to
2047 // either finish the activity or remove the tab. This will
2048 // ensure pauseWebViewTimers() taking action.
2049 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 if (mTabControl.getTabCount() == 1) {
2051 finish();
2052 return;
2053 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002054 // call pauseWebViewTimers() now, we won't be able to call
2055 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002056 // Temporarily change mActivityInPause to be true as
2057 // pauseWebViewTimers() will do nothing if mActivityInPause
2058 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002059 boolean savedState = mActivityInPause;
2060 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002061 Log.e(LOGTAG, "BrowserActivity is already paused "
2062 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002063 }
2064 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002065 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002066 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002067 removeTabFromContentView(current);
2068 mTabControl.removeTab(current);
2069 }
2070 /*
2071 * Instead of finishing the activity, simply push this to the back
2072 * of the stack and let ActivityManager to choose the foreground
2073 * activity. As BrowserActivity is singleTask, it will be always the
2074 * root of the task. So we can use either true or false for
2075 * moveTaskToBack().
2076 */
2077 moveTaskToBack(true);
2078 }
2079 }
2080 }
2081
Grace Kloba22ac16e2009-10-07 18:00:23 -07002082 boolean isMenuDown() {
2083 return mMenuIsDown;
2084 }
2085
Grace Kloba5942df02009-09-18 11:48:29 -07002086 @Override
2087 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002088 // Even if MENU is already held down, we need to call to super to open
2089 // the IME on long press.
2090 if (KeyEvent.KEYCODE_MENU == keyCode) {
2091 mMenuIsDown = true;
2092 return super.onKeyDown(keyCode, event);
2093 }
Grace Kloba5942df02009-09-18 11:48:29 -07002094 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2095 // still down, we don't want to trigger the search. Pretend to consume
2096 // the key and do nothing.
2097 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002098
Grace Kloba5942df02009-09-18 11:48:29 -07002099 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002100 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002101 // WebView/WebTextView handle the keys in the KeyDown. As
2102 // the Activity's shortcut keys are only handled when WebView
2103 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2104 if (event.isShiftPressed()) {
2105 getTopWindow().pageUp(false);
2106 } else {
2107 getTopWindow().pageDown(false);
2108 }
Grace Kloba5942df02009-09-18 11:48:29 -07002109 return true;
2110 case KeyEvent.KEYCODE_BACK:
2111 if (event.getRepeatCount() == 0) {
2112 event.startTracking();
2113 return true;
2114 } else if (mCustomView == null && mActiveTabsPage == null
2115 && event.isLongPress()) {
2116 bookmarksOrHistoryPicker(true);
2117 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 }
Grace Kloba5942df02009-09-18 11:48:29 -07002119 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120 }
Grace Kloba5942df02009-09-18 11:48:29 -07002121 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 }
2123
Grace Kloba5942df02009-09-18 11:48:29 -07002124 @Override
2125 public boolean onKeyUp(int keyCode, KeyEvent event) {
2126 switch(keyCode) {
2127 case KeyEvent.KEYCODE_MENU:
2128 mMenuIsDown = false;
2129 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002130 case KeyEvent.KEYCODE_BACK:
2131 if (event.isTracking() && !event.isCanceled()) {
2132 if (mCustomView != null) {
2133 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002134 mTabControl.getCurrentWebView().getWebChromeClient()
2135 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002136 } else if (mActiveTabsPage != null) {
2137 // if tab page is showing, hide it
2138 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002139 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002140 WebView subwindow = mTabControl.getCurrentSubWindow();
2141 if (subwindow != null) {
2142 if (subwindow.canGoBack()) {
2143 subwindow.goBack();
2144 } else {
2145 dismissSubWindow(mTabControl.getCurrentTab());
2146 }
2147 } else {
2148 goBackOnePageOrQuit();
2149 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 }
Grace Kloba5942df02009-09-18 11:48:29 -07002151 return true;
2152 }
2153 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 }
Grace Kloba5942df02009-09-18 11:48:29 -07002155 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
2157
Leon Scroggins68579392009-09-15 15:31:54 -04002158 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002159 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002160 resetTitleAndRevertLockIcon();
2161 WebView w = getTopWindow();
2162 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002163 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2164 // same logic here. But for subwindow case, should we call into the main
2165 // WebView's onPageFinished as we never call its onPageStarted and if
2166 // the page finishes itself, we don't call onPageFinished.
2167 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2168 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169
2170 cancelStopToast();
2171 mStopToast = Toast
2172 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2173 mStopToast.show();
2174 }
2175
Grace Kloba22ac16e2009-10-07 18:00:23 -07002176 boolean didUserStopLoading() {
2177 return mDidStopLoad;
2178 }
2179
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 private void cancelStopToast() {
2181 if (mStopToast != null) {
2182 mStopToast.cancel();
2183 mStopToast = null;
2184 }
2185 }
2186
Grace Kloba22ac16e2009-10-07 18:00:23 -07002187 // called by a UI or non-UI thread to post the message
2188 public void postMessage(int what, int arg1, int arg2, Object obj,
2189 long delayMillis) {
2190 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2191 obj), delayMillis);
2192 }
2193
2194 // called by a UI or non-UI thread to remove the message
2195 void removeMessages(int what, Object object) {
2196 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197 }
2198
2199 // public message ids
2200 public final static int LOAD_URL = 1001;
2201 public final static int STOP_LOAD = 1002;
2202
2203 // Message Ids
2204 private static final int FOCUS_NODE_HREF = 102;
2205 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002206 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002207
Grace Kloba22ac16e2009-10-07 18:00:23 -07002208 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002209
The Android Open Source Project0c908882009-03-03 19:32:16 -08002210 // Private handler for handling javascript and saving passwords
2211 private Handler mHandler = new Handler() {
2212
2213 public void handleMessage(Message msg) {
2214 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002215 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002216 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002218 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002219 if (url == null || url.length() == 0) {
2220 break;
2221 }
2222 HashMap focusNodeMap = (HashMap) msg.obj;
2223 WebView view = (WebView) focusNodeMap.get("webview");
2224 // Only apply the action if the top window did not change.
2225 if (getTopWindow() != view) {
2226 break;
2227 }
2228 switch (msg.arg1) {
2229 case R.id.open_context_menu_id:
2230 case R.id.view_image_context_menu_id:
2231 loadURL(getTopWindow(), url);
2232 break;
2233 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002234 final Tab parent = mTabControl.getCurrentTab();
2235 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002236 if (newTab != parent) {
2237 parent.addChildTab(newTab);
2238 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002239 break;
2240 case R.id.bookmark_context_menu_id:
2241 Intent intent = new Intent(BrowserActivity.this,
2242 AddBookmarkPage.class);
2243 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002244 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 startActivity(intent);
2246 break;
2247 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002248 Browser.sendString(BrowserActivity.this, url,
2249 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002250 break;
2251 case R.id.copy_link_context_menu_id:
2252 copy(url);
2253 break;
2254 case R.id.save_link_context_menu_id:
2255 case R.id.download_context_menu_id:
2256 onDownloadStartNoStream(url, null, null, null, -1);
2257 break;
2258 }
2259 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002260 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261
2262 case LOAD_URL:
2263 loadURL(getTopWindow(), (String) msg.obj);
2264 break;
2265
2266 case STOP_LOAD:
2267 stopLoading();
2268 break;
2269
2270 case CANCEL_CREDS_REQUEST:
2271 resumeAfterCredentials();
2272 break;
2273
The Android Open Source Project0c908882009-03-03 19:32:16 -08002274 case RELEASE_WAKELOCK:
2275 if (mWakeLock.isHeld()) {
2276 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002277 // if we reach here, Browser should be still in the
2278 // background loading after WAKELOCK_TIMEOUT (5-min).
2279 // To avoid burning the battery, stop loading.
2280 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 }
2282 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002283
2284 case UPDATE_BOOKMARK_THUMBNAIL:
2285 WebView view = (WebView) msg.obj;
2286 if (view != null) {
2287 updateScreenshot(view);
2288 }
2289 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002290 }
2291 }
2292 };
2293
Leon Scroggins89c6d362009-07-15 16:54:37 -04002294 private void updateScreenshot(WebView view) {
2295 // If this is a bookmarked site, add a screenshot to the database.
2296 // FIXME: When should we update? Every time?
2297 // FIXME: Would like to make sure there is actually something to
2298 // draw, but the API for that (WebViewCore.pictureReady()) is not
2299 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002300
Patrick Scott3918d442009-08-04 13:22:29 -04002301 ContentResolver cr = getContentResolver();
2302 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002303 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002304 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002305 boolean succeed = c.moveToFirst();
2306 ContentValues values = null;
2307 while (succeed) {
2308 if (values == null) {
2309 final ByteArrayOutputStream os
2310 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002311 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002312 if (bm == null) {
2313 c.close();
2314 return;
2315 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002316 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2317 values = new ContentValues();
2318 values.put(Browser.BookmarkColumns.THUMBNAIL,
2319 os.toByteArray());
2320 }
2321 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2322 c.getInt(0)), values, null, null);
2323 succeed = c.moveToNext();
2324 }
2325 c.close();
2326 }
2327 }
2328
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002329 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002330 * Values for the size of the thumbnail created when taking a screenshot.
2331 * Lazily initialized. Instead of using these directly, use
2332 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002333 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002334 private static int THUMBNAIL_WIDTH = 0;
2335 private static int THUMBNAIL_HEIGHT = 0;
2336
2337 /**
2338 * Return the desired width for thumbnail screenshots, which are stored in
2339 * the database, and used on the bookmarks screen.
2340 * @param context Context for finding out the density of the screen.
2341 * @return int desired width for thumbnail screenshot.
2342 */
2343 /* package */ static int getDesiredThumbnailWidth(Context context) {
2344 if (THUMBNAIL_WIDTH == 0) {
2345 float density = context.getResources().getDisplayMetrics().density;
2346 THUMBNAIL_WIDTH = (int) (90 * density);
2347 THUMBNAIL_HEIGHT = (int) (80 * density);
2348 }
2349 return THUMBNAIL_WIDTH;
2350 }
2351
2352 /**
2353 * Return the desired height for thumbnail screenshots, which are stored in
2354 * the database, and used on the bookmarks screen.
2355 * @param context Context for finding out the density of the screen.
2356 * @return int desired height for thumbnail screenshot.
2357 */
2358 /* package */ static int getDesiredThumbnailHeight(Context context) {
2359 // To ensure that they are both initialized.
2360 getDesiredThumbnailWidth(context);
2361 return THUMBNAIL_HEIGHT;
2362 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002363
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002364 private Bitmap createScreenshot(WebView view) {
2365 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002366 if (thumbnail == null) {
2367 return null;
2368 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002369 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2370 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002371 Canvas canvas = new Canvas(bm);
2372 // May need to tweak these values to determine what is the
2373 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002374 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002375 int thumbnailHeight = thumbnail.getHeight();
2376 float scaleFactorX = 1.0f;
2377 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002378 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002379 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002380 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002381 } else {
2382 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002383 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002384
2385 if (view.getWidth() > view.getHeight() &&
2386 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2387 // If the device is in landscape and the page is shorter
2388 // than the height of the view, stretch the thumbnail to fill the
2389 // space.
2390 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2391 (float)thumbnailHeight;
2392 } else {
2393 // In the portrait case, this looks nice.
2394 scaleFactorY = scaleFactorX;
2395 }
2396
2397 canvas.scale(scaleFactorX, scaleFactorY);
2398
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002399 thumbnail.draw(canvas);
2400 return bm;
2401 }
2402
The Android Open Source Project0c908882009-03-03 19:32:16 -08002403 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002404 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002405 //-------------------------------------------------------------------------
2406
2407 // Use in overrideUrlLoading
2408 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2409 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2410 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2411 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2412
Grace Kloba22ac16e2009-10-07 18:00:23 -07002413 void onPageStarted(WebView view, String url, Bitmap favicon) {
2414 // when BrowserActivity just starts, onPageStarted may be called before
2415 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2416 // to start the timer. As we won't switch tabs while an activity is in
2417 // pause state, we can ensure calling resume and pause in pair.
2418 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002419
Grace Kloba22ac16e2009-10-07 18:00:23 -07002420 resetLockIcon(url);
2421 setUrlTitle(url, null);
2422 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002423 // Keep this initial progress in sync with initialProgressValue (* 100)
2424 // in ProgressTracker.cpp
2425 // Show some progress so that the user knows the page is beginning to
2426 // load
2427 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002428 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002429 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002430
Grace Kloba22ac16e2009-10-07 18:00:23 -07002431 if (mSettings.isTracing()) {
2432 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002433 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002434 WebAddress uri = new WebAddress(url);
2435 host = uri.mHost;
2436 } catch (android.net.ParseException ex) {
2437 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002438 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002439 host = host.replace('.', '_');
2440 host += ".trace";
2441 mInTrace = true;
2442 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2443 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002444
Grace Kloba22ac16e2009-10-07 18:00:23 -07002445 // Performance probe
2446 if (false) {
2447 mStart = SystemClock.uptimeMillis();
2448 mProcessStart = Process.getElapsedCpuTime();
2449 long[] sysCpu = new long[7];
2450 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2451 sysCpu, null)) {
2452 mUserStart = sysCpu[0] + sysCpu[1];
2453 mSystemStart = sysCpu[2];
2454 mIdleStart = sysCpu[3];
2455 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2456 }
2457 mUiStart = SystemClock.currentThreadTimeMillis();
2458 }
2459 }
2460
2461 void onPageFinished(WebView view, String url) {
2462 // Reset the title and icon in case we stopped a provisional load.
2463 resetTitleAndIcon(view);
2464 // Update the lock icon image only once we are done loading
2465 updateLockIconToLatest();
2466 // pause the WebView timer and release the wake lock if it is finished
2467 // while BrowserActivity is in pause state.
2468 if (mActivityInPause && pauseWebViewTimers()) {
2469 if (mWakeLock.isHeld()) {
2470 mHandler.removeMessages(RELEASE_WAKELOCK);
2471 mWakeLock.release();
2472 }
2473 }
2474
2475 // Performance probe
2476 if (false) {
2477 long[] sysCpu = new long[7];
2478 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2479 sysCpu, null)) {
2480 String uiInfo = "UI thread used "
2481 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2482 + " ms";
2483 if (LOGD_ENABLED) {
2484 Log.d(LOGTAG, uiInfo);
2485 }
2486 //The string that gets written to the log
2487 String performanceString = "It took total "
2488 + (SystemClock.uptimeMillis() - mStart)
2489 + " ms clock time to load the page."
2490 + "\nbrowser process used "
2491 + (Process.getElapsedCpuTime() - mProcessStart)
2492 + " ms, user processes used "
2493 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2494 + " ms, kernel used "
2495 + (sysCpu[2] - mSystemStart) * 10
2496 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2497 + " ms and irq took "
2498 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2499 * 10 + " ms, " + uiInfo;
2500 if (LOGD_ENABLED) {
2501 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2502 }
2503 if (url != null) {
2504 // strip the url to maintain consistency
2505 String newUrl = new String(url);
2506 if (newUrl.startsWith("http://www.")) {
2507 newUrl = newUrl.substring(11);
2508 } else if (newUrl.startsWith("http://")) {
2509 newUrl = newUrl.substring(7);
2510 } else if (newUrl.startsWith("https://www.")) {
2511 newUrl = newUrl.substring(12);
2512 } else if (newUrl.startsWith("https://")) {
2513 newUrl = newUrl.substring(8);
2514 }
2515 if (LOGD_ENABLED) {
2516 Log.d(LOGTAG, newUrl + " loaded");
2517 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002518 }
2519 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002520 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002521
Grace Kloba22ac16e2009-10-07 18:00:23 -07002522 if (mInTrace) {
2523 mInTrace = false;
2524 Debug.stopMethodTracing();
2525 }
2526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002527
Grace Kloba22ac16e2009-10-07 18:00:23 -07002528 boolean shouldOverrideUrlLoading(WebView view, String url) {
2529 if (url.startsWith(SCHEME_WTAI)) {
2530 // wtai://wp/mc;number
2531 // number=string(phone-number)
2532 if (url.startsWith(SCHEME_WTAI_MC)) {
2533 Intent intent = new Intent(Intent.ACTION_VIEW,
2534 Uri.parse(WebView.SCHEME_TEL +
2535 url.substring(SCHEME_WTAI_MC.length())));
2536 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002537 return true;
2538 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002539 // wtai://wp/sd;dtmf
2540 // dtmf=string(dialstring)
2541 if (url.startsWith(SCHEME_WTAI_SD)) {
2542 // TODO: only send when there is active voice connection
2543 return false;
2544 }
2545 // wtai://wp/ap;number;name
2546 // number=string(phone-number)
2547 // name=string
2548 if (url.startsWith(SCHEME_WTAI_AP)) {
2549 // TODO
2550 return false;
2551 }
2552 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002553
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 // The "about:" schemes are internal to the browser; don't want these to
2555 // be dispatched to other apps.
2556 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002557 return false;
2558 }
2559
Grace Kloba22ac16e2009-10-07 18:00:23 -07002560 Intent intent;
2561 // perform generic parsing of the URI to turn it into an Intent.
2562 try {
2563 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2564 } catch (URISyntaxException ex) {
2565 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2566 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002567 }
2568
Grace Kloba22ac16e2009-10-07 18:00:23 -07002569 // check whether the intent can be resolved. If not, we will see
2570 // whether we can download it from the Market.
2571 if (getPackageManager().resolveActivity(intent, 0) == null) {
2572 String packagename = intent.getPackage();
2573 if (packagename != null) {
2574 intent = new Intent(Intent.ACTION_VIEW, Uri
2575 .parse("market://search?q=pname:" + packagename));
2576 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2577 startActivity(intent);
2578 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002579 } else {
2580 return false;
2581 }
2582 }
2583
Grace Kloba22ac16e2009-10-07 18:00:23 -07002584 // sanitize the Intent, ensuring web pages can not bypass browser
2585 // security (only access to BROWSABLE activities).
2586 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2587 intent.setComponent(null);
2588 try {
2589 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590 return true;
2591 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002592 } catch (ActivityNotFoundException ex) {
2593 // ignore the error. If no application can handle the URL,
2594 // eg about:blank, assume the browser can handle it.
2595 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002596
Grace Kloba22ac16e2009-10-07 18:00:23 -07002597 if (mMenuIsDown) {
2598 openTab(url);
2599 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002600 return true;
2601 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002602 return false;
2603 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604
Grace Kloba22ac16e2009-10-07 18:00:23 -07002605 // -------------------------------------------------------------------------
2606 // Helper function for WebChromeClient
2607 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002608
Grace Kloba22ac16e2009-10-07 18:00:23 -07002609 void onProgressChanged(WebView view, int newProgress) {
2610 mTitleBar.setProgress(newProgress);
2611 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002612
Grace Kloba22ac16e2009-10-07 18:00:23 -07002613 if (newProgress == 100) {
2614 // onProgressChanged() may continue to be called after the main
2615 // frame has finished loading, as any remaining sub frames continue
2616 // to load. We'll only get called once though with newProgress as
2617 // 100 when everything is loaded. (onPageFinished is called once
2618 // when the main frame completes loading regardless of the state of
2619 // any sub frames so calls to onProgressChanges may continue after
2620 // onPageFinished has executed)
2621 if (mInLoad) {
2622 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002623 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002624 // If the options menu is open, leave the title bar
2625 if (!mOptionsMenuOpen || !mIconView) {
2626 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002627 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002628 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 } else if (!mInLoad) {
2630 // onPageFinished may have already been called but a subframe is
2631 // still loading and updating the progress. Reset mInLoad and update
2632 // the menu items.
2633 mInLoad = true;
2634 updateInLoadMenuItems();
2635 if (!mOptionsMenuOpen || mIconView) {
2636 // This page has begun to load, so show the title bar
2637 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638 }
2639 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002640 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002641
Grace Kloba22ac16e2009-10-07 18:00:23 -07002642 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002643 // if a view already exists then immediately terminate the new one
2644 if (mCustomView != null) {
2645 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002647 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002648
2649 // Add the custom view to its container.
2650 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2651 mCustomView = view;
2652 mCustomViewCallback = callback;
2653 // Save the menu state and set it to empty while the custom
2654 // view is showing.
2655 mOldMenuState = mMenuState;
2656 mMenuState = EMPTY_MENU;
2657 // Hide the content view.
2658 mContentView.setVisibility(View.GONE);
2659 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002660 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002661 mCustomViewContainer.setVisibility(View.VISIBLE);
2662 mCustomViewContainer.bringToFront();
2663 }
2664
2665 void onHideCustomView() {
2666 if (mCustomView == null)
2667 return;
2668
2669 // Hide the custom view.
2670 mCustomView.setVisibility(View.GONE);
2671 // Remove the custom view from its container.
2672 mCustomViewContainer.removeView(mCustomView);
2673 mCustomView = null;
2674 // Reset the old menu state.
2675 mMenuState = mOldMenuState;
2676 mOldMenuState = EMPTY_MENU;
2677 mCustomViewContainer.setVisibility(View.GONE);
2678 mCustomViewCallback.onCustomViewHidden();
2679 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002680 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002681 mContentView.setVisibility(View.VISIBLE);
2682 }
2683
2684 Bitmap getDefaultVideoPoster() {
2685 if (mDefaultVideoPoster == null) {
2686 mDefaultVideoPoster = BitmapFactory.decodeResource(
2687 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002688 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002689 return mDefaultVideoPoster;
2690 }
Patrick Scott3918d442009-08-04 13:22:29 -04002691
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 View getVideoLoadingProgressView() {
2693 if (mVideoProgressView == null) {
2694 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2695 mVideoProgressView = inflater.inflate(
2696 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002697 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 return mVideoProgressView;
2699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002700
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002701 /*
2702 * The Object used to inform the WebView of the file to upload.
2703 */
2704 private ValueCallback<Uri> mUploadMessage;
2705
Grace Kloba22ac16e2009-10-07 18:00:23 -07002706 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2707 if (mUploadMessage != null) return;
2708 mUploadMessage = uploadMsg;
2709 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2710 i.addCategory(Intent.CATEGORY_OPENABLE);
2711 i.setType("*/*");
2712 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2713 getString(R.string.choose_upload)), FILE_SELECTED);
2714 }
2715
2716 // -------------------------------------------------------------------------
2717 // Implement functions for DownloadListener
2718 // -------------------------------------------------------------------------
2719
The Android Open Source Project0c908882009-03-03 19:32:16 -08002720 /**
2721 * Notify the host application a download should be done, or that
2722 * the data should be streamed if a streaming viewer is available.
2723 * @param url The full url to the content that should be downloaded
2724 * @param contentDisposition Content-disposition http header, if
2725 * present.
2726 * @param mimetype The mimetype of the content reported by the server
2727 * @param contentLength The file size reported by the server
2728 */
2729 public void onDownloadStart(String url, String userAgent,
2730 String contentDisposition, String mimetype, long contentLength) {
2731 // if we're dealing wih A/V content that's not explicitly marked
2732 // for download, check if it's streamable.
2733 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002734 || !contentDisposition.regionMatches(
2735 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736 // query the package manager to see if there's a registered handler
2737 // that matches.
2738 Intent intent = new Intent(Intent.ACTION_VIEW);
2739 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002740 ResolveInfo info = getPackageManager().resolveActivity(intent,
2741 PackageManager.MATCH_DEFAULT_ONLY);
2742 if (info != null) {
2743 ComponentName myName = getComponentName();
2744 // If we resolved to ourselves, we don't want to attempt to
2745 // load the url only to try and download it again.
2746 if (!myName.getPackageName().equals(
2747 info.activityInfo.packageName)
2748 || !myName.getClassName().equals(
2749 info.activityInfo.name)) {
2750 // someone (other than us) knows how to handle this mime
2751 // type with this scheme, don't download.
2752 try {
2753 startActivity(intent);
2754 return;
2755 } catch (ActivityNotFoundException ex) {
2756 if (LOGD_ENABLED) {
2757 Log.d(LOGTAG, "activity not found for " + mimetype
2758 + " over " + Uri.parse(url).getScheme(),
2759 ex);
2760 }
2761 // Best behavior is to fall back to a download in this
2762 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002763 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002764 }
2765 }
2766 }
2767 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2768 }
2769
2770 /**
2771 * Notify the host application a download should be done, even if there
2772 * is a streaming viewer available for thise type.
2773 * @param url The full url to the content that should be downloaded
2774 * @param contentDisposition Content-disposition http header, if
2775 * present.
2776 * @param mimetype The mimetype of the content reported by the server
2777 * @param contentLength The file size reported by the server
2778 */
2779 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2780 String contentDisposition, String mimetype, long contentLength) {
2781
2782 String filename = URLUtil.guessFileName(url,
2783 contentDisposition, mimetype);
2784
2785 // Check to see if we have an SDCard
2786 String status = Environment.getExternalStorageState();
2787 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2788 int title;
2789 String msg;
2790
2791 // Check to see if the SDCard is busy, same as the music app
2792 if (status.equals(Environment.MEDIA_SHARED)) {
2793 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2794 title = R.string.download_sdcard_busy_dlg_title;
2795 } else {
2796 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2797 title = R.string.download_no_sdcard_dlg_title;
2798 }
2799
2800 new AlertDialog.Builder(this)
2801 .setTitle(title)
2802 .setIcon(android.R.drawable.ic_dialog_alert)
2803 .setMessage(msg)
2804 .setPositiveButton(R.string.ok, null)
2805 .show();
2806 return;
2807 }
2808
2809 // java.net.URI is a lot stricter than KURL so we have to undo
2810 // KURL's percent-encoding and redo the encoding using java.net.URI.
2811 URI uri = null;
2812 try {
2813 // Undo the percent-encoding that KURL may have done.
2814 String newUrl = new String(URLUtil.decode(url.getBytes()));
2815 // Parse the url into pieces
2816 WebAddress w = new WebAddress(newUrl);
2817 String frag = null;
2818 String query = null;
2819 String path = w.mPath;
2820 // Break the path into path, query, and fragment
2821 if (path.length() > 0) {
2822 // Strip the fragment
2823 int idx = path.lastIndexOf('#');
2824 if (idx != -1) {
2825 frag = path.substring(idx + 1);
2826 path = path.substring(0, idx);
2827 }
2828 idx = path.lastIndexOf('?');
2829 if (idx != -1) {
2830 query = path.substring(idx + 1);
2831 path = path.substring(0, idx);
2832 }
2833 }
2834 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2835 query, frag);
2836 } catch (Exception e) {
2837 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2838 return;
2839 }
2840
2841 // XXX: Have to use the old url since the cookies were stored using the
2842 // old percent-encoded url.
2843 String cookies = CookieManager.getInstance().getCookie(url);
2844
2845 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002846 values.put(Downloads.COLUMN_URI, uri.toString());
2847 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2848 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2849 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002850 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002851 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002852 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002853 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2854 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2855 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2856 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002858 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 }
2860 if (mimetype == null) {
2861 // We must have long pressed on a link or image to download it. We
2862 // are not sure of the mimetype in this case, so do a head request
2863 new FetchUrlMimeType(this).execute(values);
2864 } else {
2865 final Uri contentUri =
2866 getContentResolver().insert(Downloads.CONTENT_URI, values);
2867 viewDownloads(contentUri);
2868 }
2869
2870 }
2871
Grace Kloba22ac16e2009-10-07 18:00:23 -07002872 // -------------------------------------------------------------------------
2873
The Android Open Source Project0c908882009-03-03 19:32:16 -08002874 /**
2875 * Resets the lock icon. This method is called when we start a new load and
2876 * know the url to be loaded.
2877 */
2878 private void resetLockIcon(String url) {
2879 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002880 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002881 updateLockIconImage(LOCK_ICON_UNSECURE);
2882 }
2883
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002885 * Update the lock icon to correspond to our latest state.
2886 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 private void updateLockIconToLatest() {
2888 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002889 }
2890
2891 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002892 * Updates the lock-icon image in the title-bar.
2893 */
2894 private void updateLockIconImage(int lockIconType) {
2895 Drawable d = null;
2896 if (lockIconType == LOCK_ICON_SECURE) {
2897 d = mSecLockIcon;
2898 } else if (lockIconType == LOCK_ICON_MIXED) {
2899 d = mMixLockIcon;
2900 }
Leon Scroggins68579392009-09-15 15:31:54 -04002901 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002902 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002903 }
2904
2905 /**
2906 * Displays a page-info dialog.
2907 * @param tab The tab to show info about
2908 * @param fromShowSSLCertificateOnError The flag that indicates whether
2909 * this dialog was opened from the SSL-certificate-on-error dialog or
2910 * not. This is important, since we need to know whether to return to
2911 * the parent dialog or simply dismiss.
2912 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002913 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002914 final boolean fromShowSSLCertificateOnError) {
2915 final LayoutInflater factory = LayoutInflater
2916 .from(this);
2917
2918 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2919
2920 final WebView view = tab.getWebView();
2921
2922 String url = null;
2923 String title = null;
2924
2925 if (view == null) {
2926 url = tab.getUrl();
2927 title = tab.getTitle();
2928 } else if (view == mTabControl.getCurrentWebView()) {
2929 // Use the cached title and url if this is the current WebView
2930 url = mUrl;
2931 title = mTitle;
2932 } else {
2933 url = view.getUrl();
2934 title = view.getTitle();
2935 }
2936
2937 if (url == null) {
2938 url = "";
2939 }
2940 if (title == null) {
2941 title = "";
2942 }
2943
2944 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2945 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2946
2947 mPageInfoView = tab;
2948 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2949
2950 AlertDialog.Builder alertDialogBuilder =
2951 new AlertDialog.Builder(this)
2952 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2953 .setView(pageInfoView)
2954 .setPositiveButton(
2955 R.string.ok,
2956 new DialogInterface.OnClickListener() {
2957 public void onClick(DialogInterface dialog,
2958 int whichButton) {
2959 mPageInfoDialog = null;
2960 mPageInfoView = null;
2961 mPageInfoFromShowSSLCertificateOnError = null;
2962
2963 // if we came here from the SSL error dialog
2964 if (fromShowSSLCertificateOnError) {
2965 // go back to the SSL error dialog
2966 showSSLCertificateOnError(
2967 mSSLCertificateOnErrorView,
2968 mSSLCertificateOnErrorHandler,
2969 mSSLCertificateOnErrorError);
2970 }
2971 }
2972 })
2973 .setOnCancelListener(
2974 new DialogInterface.OnCancelListener() {
2975 public void onCancel(DialogInterface dialog) {
2976 mPageInfoDialog = null;
2977 mPageInfoView = null;
2978 mPageInfoFromShowSSLCertificateOnError = null;
2979
2980 // if we came here from the SSL error dialog
2981 if (fromShowSSLCertificateOnError) {
2982 // go back to the SSL error dialog
2983 showSSLCertificateOnError(
2984 mSSLCertificateOnErrorView,
2985 mSSLCertificateOnErrorHandler,
2986 mSSLCertificateOnErrorError);
2987 }
2988 }
2989 });
2990
2991 // if we have a main top-level page SSL certificate set or a certificate
2992 // error
2993 if (fromShowSSLCertificateOnError ||
2994 (view != null && view.getCertificate() != null)) {
2995 // add a 'View Certificate' button
2996 alertDialogBuilder.setNeutralButton(
2997 R.string.view_certificate,
2998 new DialogInterface.OnClickListener() {
2999 public void onClick(DialogInterface dialog,
3000 int whichButton) {
3001 mPageInfoDialog = null;
3002 mPageInfoView = null;
3003 mPageInfoFromShowSSLCertificateOnError = null;
3004
3005 // if we came here from the SSL error dialog
3006 if (fromShowSSLCertificateOnError) {
3007 // go back to the SSL error dialog
3008 showSSLCertificateOnError(
3009 mSSLCertificateOnErrorView,
3010 mSSLCertificateOnErrorHandler,
3011 mSSLCertificateOnErrorError);
3012 } else {
3013 // otherwise, display the top-most certificate from
3014 // the chain
3015 if (view.getCertificate() != null) {
3016 showSSLCertificate(tab);
3017 }
3018 }
3019 }
3020 });
3021 }
3022
3023 mPageInfoDialog = alertDialogBuilder.show();
3024 }
3025
3026 /**
3027 * Displays the main top-level page SSL certificate dialog
3028 * (accessible from the Page-Info dialog).
3029 * @param tab The tab to show certificate for.
3030 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003031 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003032 final View certificateView =
3033 inflateCertificateView(tab.getWebView().getCertificate());
3034 if (certificateView == null) {
3035 return;
3036 }
3037
3038 LayoutInflater factory = LayoutInflater.from(this);
3039
3040 final LinearLayout placeholder =
3041 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3042
3043 LinearLayout ll = (LinearLayout) factory.inflate(
3044 R.layout.ssl_success, placeholder);
3045 ((TextView)ll.findViewById(R.id.success))
3046 .setText(R.string.ssl_certificate_is_valid);
3047
3048 mSSLCertificateView = tab;
3049 mSSLCertificateDialog =
3050 new AlertDialog.Builder(this)
3051 .setTitle(R.string.ssl_certificate).setIcon(
3052 R.drawable.ic_dialog_browser_certificate_secure)
3053 .setView(certificateView)
3054 .setPositiveButton(R.string.ok,
3055 new DialogInterface.OnClickListener() {
3056 public void onClick(DialogInterface dialog,
3057 int whichButton) {
3058 mSSLCertificateDialog = null;
3059 mSSLCertificateView = null;
3060
3061 showPageInfo(tab, false);
3062 }
3063 })
3064 .setOnCancelListener(
3065 new DialogInterface.OnCancelListener() {
3066 public void onCancel(DialogInterface dialog) {
3067 mSSLCertificateDialog = null;
3068 mSSLCertificateView = null;
3069
3070 showPageInfo(tab, false);
3071 }
3072 })
3073 .show();
3074 }
3075
3076 /**
3077 * Displays the SSL error certificate dialog.
3078 * @param view The target web-view.
3079 * @param handler The SSL error handler responsible for cancelling the
3080 * connection that resulted in an SSL error or proceeding per user request.
3081 * @param error The SSL error object.
3082 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003083 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 final WebView view, final SslErrorHandler handler, final SslError error) {
3085
3086 final View certificateView =
3087 inflateCertificateView(error.getCertificate());
3088 if (certificateView == null) {
3089 return;
3090 }
3091
3092 LayoutInflater factory = LayoutInflater.from(this);
3093
3094 final LinearLayout placeholder =
3095 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3096
3097 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3098 LinearLayout ll = (LinearLayout)factory
3099 .inflate(R.layout.ssl_warning, placeholder);
3100 ((TextView)ll.findViewById(R.id.warning))
3101 .setText(R.string.ssl_untrusted);
3102 }
3103
3104 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3105 LinearLayout ll = (LinearLayout)factory
3106 .inflate(R.layout.ssl_warning, placeholder);
3107 ((TextView)ll.findViewById(R.id.warning))
3108 .setText(R.string.ssl_mismatch);
3109 }
3110
3111 if (error.hasError(SslError.SSL_EXPIRED)) {
3112 LinearLayout ll = (LinearLayout)factory
3113 .inflate(R.layout.ssl_warning, placeholder);
3114 ((TextView)ll.findViewById(R.id.warning))
3115 .setText(R.string.ssl_expired);
3116 }
3117
3118 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3119 LinearLayout ll = (LinearLayout)factory
3120 .inflate(R.layout.ssl_warning, placeholder);
3121 ((TextView)ll.findViewById(R.id.warning))
3122 .setText(R.string.ssl_not_yet_valid);
3123 }
3124
3125 mSSLCertificateOnErrorHandler = handler;
3126 mSSLCertificateOnErrorView = view;
3127 mSSLCertificateOnErrorError = error;
3128 mSSLCertificateOnErrorDialog =
3129 new AlertDialog.Builder(this)
3130 .setTitle(R.string.ssl_certificate).setIcon(
3131 R.drawable.ic_dialog_browser_certificate_partially_secure)
3132 .setView(certificateView)
3133 .setPositiveButton(R.string.ok,
3134 new DialogInterface.OnClickListener() {
3135 public void onClick(DialogInterface dialog,
3136 int whichButton) {
3137 mSSLCertificateOnErrorDialog = null;
3138 mSSLCertificateOnErrorView = null;
3139 mSSLCertificateOnErrorHandler = null;
3140 mSSLCertificateOnErrorError = null;
3141
Grace Kloba22ac16e2009-10-07 18:00:23 -07003142 view.getWebViewClient().onReceivedSslError(
3143 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003144 }
3145 })
3146 .setNeutralButton(R.string.page_info_view,
3147 new DialogInterface.OnClickListener() {
3148 public void onClick(DialogInterface dialog,
3149 int whichButton) {
3150 mSSLCertificateOnErrorDialog = null;
3151
3152 // do not clear the dialog state: we will
3153 // need to show the dialog again once the
3154 // user is done exploring the page-info details
3155
3156 showPageInfo(mTabControl.getTabFromView(view),
3157 true);
3158 }
3159 })
3160 .setOnCancelListener(
3161 new DialogInterface.OnCancelListener() {
3162 public void onCancel(DialogInterface dialog) {
3163 mSSLCertificateOnErrorDialog = null;
3164 mSSLCertificateOnErrorView = null;
3165 mSSLCertificateOnErrorHandler = null;
3166 mSSLCertificateOnErrorError = null;
3167
Grace Kloba22ac16e2009-10-07 18:00:23 -07003168 view.getWebViewClient().onReceivedSslError(
3169 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003170 }
3171 })
3172 .show();
3173 }
3174
3175 /**
3176 * Inflates the SSL certificate view (helper method).
3177 * @param certificate The SSL certificate.
3178 * @return The resultant certificate view with issued-to, issued-by,
3179 * issued-on, expires-on, and possibly other fields set.
3180 * If the input certificate is null, returns null.
3181 */
3182 private View inflateCertificateView(SslCertificate certificate) {
3183 if (certificate == null) {
3184 return null;
3185 }
3186
3187 LayoutInflater factory = LayoutInflater.from(this);
3188
3189 View certificateView = factory.inflate(
3190 R.layout.ssl_certificate, null);
3191
3192 // issued to:
3193 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3194 if (issuedTo != null) {
3195 ((TextView) certificateView.findViewById(R.id.to_common))
3196 .setText(issuedTo.getCName());
3197 ((TextView) certificateView.findViewById(R.id.to_org))
3198 .setText(issuedTo.getOName());
3199 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3200 .setText(issuedTo.getUName());
3201 }
3202
3203 // issued by:
3204 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3205 if (issuedBy != null) {
3206 ((TextView) certificateView.findViewById(R.id.by_common))
3207 .setText(issuedBy.getCName());
3208 ((TextView) certificateView.findViewById(R.id.by_org))
3209 .setText(issuedBy.getOName());
3210 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3211 .setText(issuedBy.getUName());
3212 }
3213
3214 // issued on:
3215 String issuedOn = reformatCertificateDate(
3216 certificate.getValidNotBefore());
3217 ((TextView) certificateView.findViewById(R.id.issued_on))
3218 .setText(issuedOn);
3219
3220 // expires on:
3221 String expiresOn = reformatCertificateDate(
3222 certificate.getValidNotAfter());
3223 ((TextView) certificateView.findViewById(R.id.expires_on))
3224 .setText(expiresOn);
3225
3226 return certificateView;
3227 }
3228
3229 /**
3230 * Re-formats the certificate date (Date.toString()) string to
3231 * a properly localized date string.
3232 * @return Properly localized version of the certificate date string and
3233 * the original certificate date string if fails to localize.
3234 * If the original string is null, returns an empty string "".
3235 */
3236 private String reformatCertificateDate(String certificateDate) {
3237 String reformattedDate = null;
3238
3239 if (certificateDate != null) {
3240 Date date = null;
3241 try {
3242 date = java.text.DateFormat.getInstance().parse(certificateDate);
3243 } catch (ParseException e) {
3244 date = null;
3245 }
3246
3247 if (date != null) {
3248 reformattedDate =
3249 DateFormat.getDateFormat(this).format(date);
3250 }
3251 }
3252
3253 return reformattedDate != null ? reformattedDate :
3254 (certificateDate != null ? certificateDate : "");
3255 }
3256
3257 /**
3258 * Displays an http-authentication dialog.
3259 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003260 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003261 final String host, final String realm, final String title,
3262 final String name, final String password, int focusId) {
3263 LayoutInflater factory = LayoutInflater.from(this);
3264 final View v = factory
3265 .inflate(R.layout.http_authentication, null);
3266 if (name != null) {
3267 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3268 }
3269 if (password != null) {
3270 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3271 }
3272
3273 String titleText = title;
3274 if (titleText == null) {
3275 titleText = getText(R.string.sign_in_to).toString().replace(
3276 "%s1", host).replace("%s2", realm);
3277 }
3278
3279 mHttpAuthHandler = handler;
3280 AlertDialog dialog = new AlertDialog.Builder(this)
3281 .setTitle(titleText)
3282 .setIcon(android.R.drawable.ic_dialog_alert)
3283 .setView(v)
3284 .setPositiveButton(R.string.action,
3285 new DialogInterface.OnClickListener() {
3286 public void onClick(DialogInterface dialog,
3287 int whichButton) {
3288 String nm = ((EditText) v
3289 .findViewById(R.id.username_edit))
3290 .getText().toString();
3291 String pw = ((EditText) v
3292 .findViewById(R.id.password_edit))
3293 .getText().toString();
3294 BrowserActivity.this.setHttpAuthUsernamePassword
3295 (host, realm, nm, pw);
3296 handler.proceed(nm, pw);
3297 mHttpAuthenticationDialog = null;
3298 mHttpAuthHandler = null;
3299 }})
3300 .setNegativeButton(R.string.cancel,
3301 new DialogInterface.OnClickListener() {
3302 public void onClick(DialogInterface dialog,
3303 int whichButton) {
3304 handler.cancel();
3305 BrowserActivity.this.resetTitleAndRevertLockIcon();
3306 mHttpAuthenticationDialog = null;
3307 mHttpAuthHandler = null;
3308 }})
3309 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3310 public void onCancel(DialogInterface dialog) {
3311 handler.cancel();
3312 BrowserActivity.this.resetTitleAndRevertLockIcon();
3313 mHttpAuthenticationDialog = null;
3314 mHttpAuthHandler = null;
3315 }})
3316 .create();
3317 // Make the IME appear when the dialog is displayed if applicable.
3318 dialog.getWindow().setSoftInputMode(
3319 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3320 dialog.show();
3321 if (focusId != 0) {
3322 dialog.findViewById(focusId).requestFocus();
3323 } else {
3324 v.findViewById(R.id.username_edit).requestFocus();
3325 }
3326 mHttpAuthenticationDialog = dialog;
3327 }
3328
3329 public int getProgress() {
3330 WebView w = mTabControl.getCurrentWebView();
3331 if (w != null) {
3332 return w.getProgress();
3333 } else {
3334 return 100;
3335 }
3336 }
3337
3338 /**
3339 * Set HTTP authentication password.
3340 *
3341 * @param host The host for the password
3342 * @param realm The realm for the password
3343 * @param username The username for the password. If it is null, it means
3344 * password can't be saved.
3345 * @param password The password
3346 */
3347 public void setHttpAuthUsernamePassword(String host, String realm,
3348 String username,
3349 String password) {
3350 WebView w = mTabControl.getCurrentWebView();
3351 if (w != null) {
3352 w.setHttpAuthUsernamePassword(host, realm, username, password);
3353 }
3354 }
3355
3356 /**
3357 * connectivity manager says net has come or gone... inform the user
3358 * @param up true if net has come up, false if net has gone down
3359 */
3360 public void onNetworkToggle(boolean up) {
3361 if (up == mIsNetworkUp) {
3362 return;
3363 } else if (up) {
3364 mIsNetworkUp = true;
3365 if (mAlertDialog != null) {
3366 mAlertDialog.cancel();
3367 mAlertDialog = null;
3368 }
3369 } else {
3370 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003371 if (mInLoad) {
3372 createAndShowNetworkDialog();
3373 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003374 }
3375 WebView w = mTabControl.getCurrentWebView();
3376 if (w != null) {
3377 w.setNetworkAvailable(up);
3378 }
3379 }
3380
Grace Kloba22ac16e2009-10-07 18:00:23 -07003381 boolean isNetworkUp() {
3382 return mIsNetworkUp;
3383 }
3384
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003385 // This method shows the network dialog alerting the user that the net is
3386 // down. It will only show the dialog if mAlertDialog is null.
3387 private void createAndShowNetworkDialog() {
3388 if (mAlertDialog == null) {
3389 mAlertDialog = new AlertDialog.Builder(this)
3390 .setTitle(R.string.loadSuspendedTitle)
3391 .setMessage(R.string.loadSuspended)
3392 .setPositiveButton(R.string.ok, null)
3393 .show();
3394 }
3395 }
3396
The Android Open Source Project0c908882009-03-03 19:32:16 -08003397 @Override
3398 protected void onActivityResult(int requestCode, int resultCode,
3399 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003400 if (getTopWindow() == null) return;
3401
The Android Open Source Project0c908882009-03-03 19:32:16 -08003402 switch (requestCode) {
3403 case COMBO_PAGE:
3404 if (resultCode == RESULT_OK && intent != null) {
3405 String data = intent.getAction();
3406 Bundle extras = intent.getExtras();
3407 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003408 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003409 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003410 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003412 dismissSubWindow(currentTab);
3413 if (data != null && data.length() != 0) {
3414 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 }
3416 }
3417 }
3418 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003419 // Choose a file from the file picker.
3420 case FILE_SELECTED:
3421 if (null == mUploadMessage) break;
3422 Uri result = intent == null || resultCode != RESULT_OK ? null
3423 : intent.getData();
3424 mUploadMessage.onReceiveValue(result);
3425 mUploadMessage = null;
3426 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003427 default:
3428 break;
3429 }
Leon Scroggins30444232009-09-04 18:36:20 -04003430 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 }
3432
3433 /*
3434 * This method is called as a result of the user selecting the options
3435 * menu to see the download window, or when a download changes state. It
3436 * shows the download window ontop of the current window.
3437 */
3438 /* package */ void viewDownloads(Uri downloadRecord) {
3439 Intent intent = new Intent(this,
3440 BrowserDownloadPage.class);
3441 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003442 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003443
3444 }
3445
Leon Scroggins160a7e72009-08-14 18:28:01 -04003446 /**
3447 * Open the Go page.
3448 * @param startWithHistory If true, open starting on the history tab.
3449 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003450 */
Leon Scroggins30444232009-09-04 18:36:20 -04003451 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 WebView current = mTabControl.getCurrentWebView();
3453 if (current == null) {
3454 return;
3455 }
3456 Intent intent = new Intent(this,
3457 CombinedBookmarkHistoryActivity.class);
3458 String title = current.getTitle();
3459 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003460 Bitmap thumbnail = createScreenshot(current);
3461
The Android Open Source Project0c908882009-03-03 19:32:16 -08003462 // Just in case the user opens bookmarks before a page finishes loading
3463 // so the current history item, and therefore the page, is null.
3464 if (null == url) {
3465 url = mLastEnteredUrl;
3466 // This can happen.
3467 if (null == url) {
3468 url = mSettings.getHomePage();
3469 }
3470 }
3471 // In case the web page has not yet received its associated title.
3472 if (title == null) {
3473 title = url;
3474 }
3475 intent.putExtra("title", title);
3476 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003477 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003478 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003479 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003480 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003481 if (startWithHistory) {
3482 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3483 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3484 }
3485 startActivityForResult(intent, COMBO_PAGE);
3486 }
3487
3488 // Called when loading from context menu or LOAD_URL message
3489 private void loadURL(WebView view, String url) {
3490 // In case the user enters nothing.
3491 if (url != null && url.length() != 0 && view != null) {
3492 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003493 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 view.loadUrl(url);
3495 }
3496 }
3497 }
3498
The Android Open Source Project0c908882009-03-03 19:32:16 -08003499 private String smartUrlFilter(Uri inUri) {
3500 if (inUri != null) {
3501 return smartUrlFilter(inUri.toString());
3502 }
3503 return null;
3504 }
3505
Feng Qianb34f87a2009-03-24 21:27:26 -07003506 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 "(?i)" + // switch on case insensitive matching
3508 "(" + // begin group for schema
3509 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003510 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003511 ")" +
3512 "(.*)" );
3513
3514 /**
3515 * Attempts to determine whether user input is a URL or search
3516 * terms. Anything with a space is passed to search.
3517 *
3518 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3519 * "Http://" converts to "http://"
3520 *
3521 * @return Original or modified URL
3522 *
3523 */
3524 String smartUrlFilter(String url) {
3525
3526 String inUrl = url.trim();
3527 boolean hasSpace = inUrl.indexOf(' ') != -1;
3528
3529 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3530 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003531 // force scheme to lowercase
3532 String scheme = matcher.group(1);
3533 String lcScheme = scheme.toLowerCase();
3534 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003535 inUrl = lcScheme + matcher.group(2);
3536 }
3537 if (hasSpace) {
3538 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539 }
3540 return inUrl;
3541 }
3542 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003543 // FIXME: Is this the correct place to add to searches?
3544 // what if someone else calls this function?
3545 int shortcut = parseUrlShortcut(inUrl);
3546 if (shortcut != SHORTCUT_INVALID) {
3547 Browser.addSearchUrl(mResolver, inUrl);
3548 String query = inUrl.substring(2);
3549 switch (shortcut) {
3550 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003551 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003552 case SHORTCUT_WIKIPEDIA_SEARCH:
3553 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3554 case SHORTCUT_DICTIONARY_SEARCH:
3555 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3556 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003557 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003558 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003559 }
3560 }
3561 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003562 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003563 return URLUtil.guessUrl(inUrl);
3564 }
3565 }
3566
3567 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003568 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003569 }
3570
Ben Murdochbff2d602009-07-01 20:19:05 +01003571 /* package */ void setShouldShowErrorConsole(boolean flag) {
3572 if (flag == mShouldShowErrorConsole) {
3573 // Nothing to do.
3574 return;
3575 }
3576
3577 mShouldShowErrorConsole = flag;
3578
Grace Kloba22ac16e2009-10-07 18:00:23 -07003579 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3580 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003581
3582 if (flag) {
3583 // Setting the show state of the console will cause it's the layout to be inflated.
3584 if (errorConsole.numberOfErrors() > 0) {
3585 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3586 } else {
3587 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3588 }
3589
3590 // Now we can add it to the main view.
3591 mErrorConsoleContainer.addView(errorConsole,
3592 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
3593 ViewGroup.LayoutParams.WRAP_CONTENT));
3594 } else {
3595 mErrorConsoleContainer.removeView(errorConsole);
3596 }
3597
3598 }
3599
Grace Kloba22ac16e2009-10-07 18:00:23 -07003600 boolean shouldShowErrorConsole() {
3601 return mShouldShowErrorConsole;
3602 }
3603
Andrei Popescu163ab742009-10-20 17:58:23 +01003604 private void setStatusBarVisibility(boolean visible) {
3605 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3606 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3607 }
3608
Grace Klobaeb6eef42009-09-15 17:56:32 -07003609 final static int LOCK_ICON_UNSECURE = 0;
3610 final static int LOCK_ICON_SECURE = 1;
3611 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003612
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 private BrowserSettings mSettings;
3614 private TabControl mTabControl;
3615 private ContentResolver mResolver;
3616 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003617 private View mCustomView;
3618 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003619 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003620
3621 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3622 // view, we should rewrite this.
3623 private int mCurrentMenuState = 0;
3624 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003625 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 private static final int EMPTY_MENU = -1;
3627 private Menu mMenu;
3628
3629 private FindDialog mFindDialog;
3630 // Used to prevent chording to result in firing two shortcuts immediately
3631 // one after another. Fixes bug 1211714.
3632 boolean mCanChord;
3633
3634 private boolean mInLoad;
3635 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003636 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003637
The Android Open Source Project0c908882009-03-03 19:32:16 -08003638 private boolean mActivityInPause = true;
3639
3640 private boolean mMenuIsDown;
3641
The Android Open Source Project0c908882009-03-03 19:32:16 -08003642 private static boolean mInTrace;
3643
3644 // Performance probe
3645 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3646 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3647 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3648 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3649 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3650 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3651 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3652 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3653 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3654 };
3655
3656 private long mStart;
3657 private long mProcessStart;
3658 private long mUserStart;
3659 private long mSystemStart;
3660 private long mIdleStart;
3661 private long mIrqStart;
3662
3663 private long mUiStart;
3664
3665 private Drawable mMixLockIcon;
3666 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003667
3668 /* hold a ref so we can auto-cancel if necessary */
3669 private AlertDialog mAlertDialog;
3670
3671 // Wait for credentials before loading google.com
3672 private ProgressDialog mCredsDlg;
3673
3674 // The up-to-date URL and title (these can be different from those stored
3675 // in WebView, since it takes some time for the information in WebView to
3676 // get updated)
3677 private String mUrl;
3678 private String mTitle;
3679
3680 // As PageInfo has different style for landscape / portrait, we have
3681 // to re-open it when configuration changed
3682 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003683 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003684 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3685 // dialog, we should not just dismiss it, but should get back to the
3686 // SSL-certificate-on-error dialog. This flag is used to store this state
3687 private Boolean mPageInfoFromShowSSLCertificateOnError;
3688
3689 // as SSLCertificateOnError has different style for landscape / portrait,
3690 // we have to re-open it when configuration changed
3691 private AlertDialog mSSLCertificateOnErrorDialog;
3692 private WebView mSSLCertificateOnErrorView;
3693 private SslErrorHandler mSSLCertificateOnErrorHandler;
3694 private SslError mSSLCertificateOnErrorError;
3695
3696 // as SSLCertificate has different style for landscape / portrait, we
3697 // have to re-open it when configuration changed
3698 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003699 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003700
3701 // as HttpAuthentication has different style for landscape / portrait, we
3702 // have to re-open it when configuration changed
3703 private AlertDialog mHttpAuthenticationDialog;
3704 private HttpAuthHandler mHttpAuthHandler;
3705
3706 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3707 new FrameLayout.LayoutParams(
3708 ViewGroup.LayoutParams.FILL_PARENT,
3709 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003710 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3711 new FrameLayout.LayoutParams(
3712 ViewGroup.LayoutParams.FILL_PARENT,
3713 ViewGroup.LayoutParams.FILL_PARENT,
3714 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003715 // Google search
3716 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 // Wikipedia search
3718 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3719 // Dictionary search
3720 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3721 // Google Mobile Local search
3722 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3723
3724 final static String QUERY_PLACE_HOLDER = "%s";
3725
3726 // "source" parameter for Google search through search key
3727 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3728 // "source" parameter for Google search through goto menu
3729 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3730 // "source" parameter for Google search through simplily type
3731 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3732 // "source" parameter for Google search suggested by the browser
3733 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3734 // "source" parameter for Google search from unknown source
3735 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3736
3737 private final static String LOGTAG = "browser";
3738
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 private String mLastEnteredUrl;
3740
3741 private PowerManager.WakeLock mWakeLock;
3742 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3743
3744 private Toast mStopToast;
3745
Leon Scroggins68579392009-09-15 15:31:54 -04003746 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003747
Ben Murdochbff2d602009-07-01 20:19:05 +01003748 private LinearLayout mErrorConsoleContainer = null;
3749 private boolean mShouldShowErrorConsole = false;
3750
The Android Open Source Project0c908882009-03-03 19:32:16 -08003751 // As the ids are dynamically created, we can't guarantee that they will
3752 // be in sequence, so this static array maps ids to a window number.
3753 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3754 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3755 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3756 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3757
3758 // monitor platform changes
3759 private IntentFilter mNetworkStateChangedFilter;
3760 private BroadcastReceiver mNetworkStateIntentReceiver;
3761
Grace Klobab4da0ad2009-05-14 14:45:40 -07003762 private BroadcastReceiver mPackageInstallationReceiver;
3763
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003765 final static int COMBO_PAGE = 1;
3766 final static int DOWNLOAD_PAGE = 2;
3767 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003768 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003769
Andrei Popescu540035d2009-09-18 18:59:20 +01003770 // the default <video> poster
3771 private Bitmap mDefaultVideoPoster;
3772 // the video progress view
3773 private View mVideoProgressView;
3774
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003775 /**
3776 * A UrlData class to abstract how the content will be set to WebView.
3777 * This base class uses loadUrl to show the content.
3778 */
3779 private static class UrlData {
3780 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003781 byte[] mPostData;
3782
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003783 UrlData(String url) {
3784 this.mUrl = url;
3785 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003786
3787 void setPostData(byte[] postData) {
3788 mPostData = postData;
3789 }
3790
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003791 boolean isEmpty() {
3792 return mUrl == null || mUrl.length() == 0;
3793 }
3794
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003795 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003796 if (mPostData != null) {
3797 webView.postUrl(mUrl, mPostData);
3798 } else {
3799 webView.loadUrl(mUrl);
3800 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003801 }
3802 };
3803
3804 /**
3805 * A subclass of UrlData class that can display inlined content using
3806 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3807 */
3808 private static class InlinedUrlData extends UrlData {
3809 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3810 super(failUrl);
3811 mInlined = inlined;
3812 mMimeType = mimeType;
3813 mEncoding = encoding;
3814 }
3815 String mMimeType;
3816 String mInlined;
3817 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003818 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003819 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003820 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003821 }
3822
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003823 @Override
3824 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003825 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3826 }
3827 }
3828
Leon Scroggins1f005d32009-08-10 17:36:42 -04003829 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003830}