blob: 87955941d00447c57a3d12926530d3d44088c8d1 [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();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800518 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
519 int index = urlData.mUrl.codePointAt(16) - '0';
520 if (index <= 0 || index > 9) {
521 current.getWebView().setDragTracker(null);
522 } else {
523 current.getWebView().setDragTracker(new MeshTracker(index));
524 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800525 } else {
526 mSettings.toggleDebugSettings();
527 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800528 return;
529 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400530 // Get rid of the subwindow if it exists
531 dismissSubWindow(current);
532 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800533 }
534 }
535 }
536
Satish Sampath565505b2009-05-29 15:37:27 +0100537 private int parseUrlShortcut(String url) {
538 if (url == null) return SHORTCUT_INVALID;
539
540 // FIXME: quick search, need to be customized by setting
541 if (url.length() > 2 && url.charAt(1) == ' ') {
542 switch (url.charAt(0)) {
543 case 'g': return SHORTCUT_GOOGLE_SEARCH;
544 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
545 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
546 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
547 }
548 }
549 return SHORTCUT_INVALID;
550 }
551
552 /**
553 * Launches the default web search activity with the query parameters if the given intent's data
554 * are identified as plain search terms and not URLs/shortcuts.
555 * @return true if the intent was handled and web search activity was launched, false if not.
556 */
557 private boolean handleWebSearchIntent(Intent intent) {
558 if (intent == null) return false;
559
560 String url = null;
561 final String action = intent.getAction();
562 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700563 Uri data = intent.getData();
564 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100565 } else if (Intent.ACTION_SEARCH.equals(action)
566 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
567 || Intent.ACTION_WEB_SEARCH.equals(action)) {
568 url = intent.getStringExtra(SearchManager.QUERY);
569 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100570 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
571 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100572 }
573
574 /**
575 * Launches the default web search activity with the query parameters if the given url string
576 * was identified as plain search terms and not URL/shortcut.
577 * @return true if the request was handled and web search activity was launched, false if not.
578 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100579 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100580 if (inUrl == null) return false;
581
582 // In general, we shouldn't modify URL from Intent.
583 // But currently, we get the user-typed URL from search box as well.
584 String url = fixUrl(inUrl).trim();
585
586 // URLs and site specific search shortcuts are handled by the regular flow of control, so
587 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800588 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100589 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100590 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
591 return false;
592 }
593
594 Browser.updateVisitedHistory(mResolver, url, false);
595 Browser.addSearchUrl(mResolver, url);
596
597 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
598 intent.addCategory(Intent.CATEGORY_DEFAULT);
599 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100600 if (appData != null) {
601 intent.putExtra(SearchManager.APP_DATA, appData);
602 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100603 if (extraData != null) {
604 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
605 }
Grace Klobacc634032009-07-28 15:58:19 -0700606 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100607 startActivity(intent);
608
609 return true;
610 }
611
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700612 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800613 String url = null;
614 if (intent != null) {
615 final String action = intent.getAction();
616 if (Intent.ACTION_VIEW.equals(action)) {
617 url = smartUrlFilter(intent.getData());
618 if (url != null && url.startsWith("content:")) {
619 /* Append mimetype so webview knows how to display */
620 String mimeType = intent.resolveType(getContentResolver());
621 if (mimeType != null) {
622 url += "?" + mimeType;
623 }
624 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700625 if ("inline:".equals(url)) {
626 return new InlinedUrlData(
627 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
628 intent.getType(),
629 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
630 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
631 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800632 } else if (Intent.ACTION_SEARCH.equals(action)
633 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
634 || Intent.ACTION_WEB_SEARCH.equals(action)) {
635 url = intent.getStringExtra(SearchManager.QUERY);
636 if (url != null) {
637 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500638 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800639 // In general, we shouldn't modify URL from Intent.
640 // But currently, we get the user-typed URL from search box as well.
641 url = fixUrl(url);
642 url = smartUrlFilter(url);
643 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
644 if (url.contains(searchSource)) {
645 String source = null;
646 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
647 if (appData != null) {
648 source = appData.getString(SearchManager.SOURCE);
649 }
650 if (TextUtils.isEmpty(source)) {
651 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
652 }
653 url = url.replace(searchSource, "&source=android-"+source+"&");
654 }
655 }
656 }
657 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700658 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800659 }
660
661 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400662 // FIXME: Converting the url to lower case
663 // duplicates functionality in smartUrlFilter().
664 // However, changing all current callers of fixUrl to
665 // call smartUrlFilter in addition may have unwanted
666 // consequences, and is deferred for now.
667 int colon = inUrl.indexOf(':');
668 boolean allLower = true;
669 for (int index = 0; index < colon; index++) {
670 char ch = inUrl.charAt(index);
671 if (!Character.isLetter(ch)) {
672 break;
673 }
674 allLower &= Character.isLowerCase(ch);
675 if (index == colon - 1 && !allLower) {
676 inUrl = inUrl.substring(0, colon).toLowerCase()
677 + inUrl.substring(colon);
678 }
679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
681 return inUrl;
682 if (inUrl.startsWith("http:") ||
683 inUrl.startsWith("https:")) {
684 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
685 inUrl = inUrl.replaceFirst("/", "//");
686 } else inUrl = inUrl.replaceFirst(":", "://");
687 }
688 return inUrl;
689 }
690
Grace Kloba22ac16e2009-10-07 18:00:23 -0700691 @Override
692 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800693 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700694 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800695 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
696 }
697
698 if (!mActivityInPause) {
699 Log.e(LOGTAG, "BrowserActivity is already resumed.");
700 return;
701 }
702
Mike Reed7bfa63b2009-05-28 11:08:32 -0400703 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800704 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400705 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800706
707 if (mWakeLock.isHeld()) {
708 mHandler.removeMessages(RELEASE_WAKELOCK);
709 mWakeLock.release();
710 }
711
712 if (mCredsDlg != null) {
713 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
714 // In case credential request never comes back
715 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
716 }
717 }
718
719 registerReceiver(mNetworkStateIntentReceiver,
720 mNetworkStateChangedFilter);
721 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722 }
723
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400724 /**
725 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400726 * would change its appearance, use a different TitleBar to show overlayed
727 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400728 */
729 private TitleBar mFakeTitleBar;
730
731 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400732 * Holder for the fake title bar. It will have a foreground shadow, as well
733 * as a white background, so the fake title bar looks like the real one.
734 */
735 private ViewGroup mFakeTitleBarHolder;
736
737 /**
738 * Layout parameters for the fake title bar within mFakeTitleBarHolder
739 */
740 private FrameLayout.LayoutParams mFakeTitleBarParams
741 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800742 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400743 ViewGroup.LayoutParams.WRAP_CONTENT);
744 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400745 * Keeps track of whether the options menu is open. This is important in
746 * determining whether to show or hide the title bar overlay.
747 */
748 private boolean mOptionsMenuOpen;
749
750 /**
751 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
752 * of whether the configuration has changed. The first onMenuOpened call
753 * after a configuration change is simply a reopening of the same menu
754 * (i.e. mIconView did not change).
755 */
756 private boolean mConfigChanged;
757
758 /**
759 * Whether or not the options menu is in its smaller, icon menu form. When
760 * true, we want the title bar overlay to be up. When false, we do not.
761 * Only meaningful if mOptionsMenuOpen is true.
762 */
763 private boolean mIconView;
764
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400765 @Override
766 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400767 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
768 if (mOptionsMenuOpen) {
769 if (mConfigChanged) {
770 // We do not need to make any changes to the state of the
771 // title bar, since the only thing that happened was a
772 // change in orientation
773 mConfigChanged = false;
774 } else {
775 if (mIconView) {
776 // Switching the menu to expanded view, so hide the
777 // title bar.
778 hideFakeTitleBar();
779 mIconView = false;
780 } else {
781 // Switching the menu back to icon view, so show the
782 // title bar once again.
783 showFakeTitleBar();
784 mIconView = true;
785 }
786 }
787 } else {
788 // The options menu is closed, so open it, and show the title
789 showFakeTitleBar();
790 mOptionsMenuOpen = true;
791 mConfigChanged = false;
792 mIconView = true;
793 }
794 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400795 return true;
796 }
797
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400798 /**
799 * Special class used exclusively for the shadow drawn underneath the fake
800 * title bar. The shadow does not need to be drawn if the WebView
801 * underneath is scrolled to the top, because it will draw directly on top
802 * of the embedded shadow.
803 */
804 private static class Shadow extends View {
805 private WebView mWebView;
806
807 public Shadow(Context context, AttributeSet attrs) {
808 super(context, attrs);
809 }
810
811 public void setWebView(WebView view) {
812 mWebView = view;
813 }
814
815 @Override
816 public void draw(Canvas canvas) {
817 // In general onDraw is the method to override, but we care about
818 // whether or not the background gets drawn, which happens in draw()
819 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
820 super.draw(canvas);
821 }
822 // Need to invalidate so that if the scroll position changes, we
823 // still draw as appropriate.
824 invalidate();
825 }
826 }
827
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400828 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400829 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400830 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400831 && !mActivityInPause && decor != null
832 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400833 Rect visRect = new Rect();
834 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
835 if (LOGD_ENABLED) {
836 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
837 }
838 return;
839 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400840
841 WindowManager manager
842 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
843
844 // Add the title bar to the window manager so it can receive touches
845 // while the menu is up
846 WindowManager.LayoutParams params
847 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800848 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400849 ViewGroup.LayoutParams.WRAP_CONTENT,
850 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
851 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400852 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400853 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400854 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400855 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400856 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400857 // XXX : Without providing an offset, the fake title bar will be
858 // placed underneath the status bar. Use the global visible rect
859 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400860 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400861 // Add a holder for the title bar. It also holds a shadow to show
862 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400863 if (mFakeTitleBarHolder == null) {
864 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
865 .inflate(R.layout.title_bar_bg, null);
866 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400867 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
868 R.id.shadow);
869 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400870 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400871 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400872 }
873 }
874
875 @Override
876 public void onOptionsMenuClosed(Menu menu) {
877 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400878 if (!mInLoad) {
879 hideFakeTitleBar();
880 } else if (!mIconView) {
881 // The page is currently loading, and we are in expanded mode, so
882 // we were not showing the menu. Show it once again. It will be
883 // removed when the page finishes.
884 showFakeTitleBar();
885 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400886 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700887
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400888 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400889 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400890 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
891 mFakeTitleBarHolder.getLayoutParams();
892 WebView mainView = mTabControl.getCurrentWebView();
893 // Although we decided whether or not to animate based on the current
894 // scroll position, the scroll position may have changed since the
895 // fake title bar was displayed. Make sure it has the appropriate
896 // animation/lack thereof before removing.
897 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400898 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400899 WindowManager manager
900 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400901 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400902 mFakeTitleBarHolder.removeView(mFakeTitleBar);
903 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 }
905
The Android Open Source Project0c908882009-03-03 19:32:16 -0800906 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400907 * Special method for the fake title bar to call when displaying its context
908 * menu, since it is in its own Window, and its parent does not show a
909 * context menu.
910 */
911 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400912 if (null == mTitleBar.getParent()) {
913 return;
914 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400915 openContextMenu(mTitleBar);
916 }
917
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400918 @Override
919 public void onContextMenuClosed(Menu menu) {
920 super.onContextMenuClosed(menu);
921 if (mInLoad) {
922 showFakeTitleBar();
923 }
924 }
925
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400926 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800927 * onSaveInstanceState(Bundle map)
928 * onSaveInstanceState is called right before onStop(). The map contains
929 * the saved state.
930 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700931 @Override
932 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700933 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800934 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
935 }
936 // the default implementation requires each view to have an id. As the
937 // browser handles the state itself and it doesn't use id for the views,
938 // don't call the default implementation. Otherwise it will trigger the
939 // warning like this, "couldn't save which view has focus because the
940 // focused view XXX has no id".
941
942 // Save all the tabs
943 mTabControl.saveState(outState);
944 }
945
Grace Kloba22ac16e2009-10-07 18:00:23 -0700946 @Override
947 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800948 super.onPause();
949
950 if (mActivityInPause) {
951 Log.e(LOGTAG, "BrowserActivity is already paused.");
952 return;
953 }
954
Mike Reed7bfa63b2009-05-28 11:08:32 -0400955 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800956 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400957 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 mWakeLock.acquire();
959 mHandler.sendMessageDelayed(mHandler
960 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
961 }
962
963 // Clear the credentials toast if it is up
964 if (mCredsDlg != null && mCredsDlg.isShowing()) {
965 mCredsDlg.dismiss();
966 }
967 mCredsDlg = null;
968
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400969 // FIXME: This removes the active tabs page and resets the menu to
970 // MAIN_MENU. A better solution might be to do this work in onNewIntent
971 // but then we would need to save it in onSaveInstanceState and restore
972 // it in onCreate/onRestoreInstanceState
973 if (mActiveTabsPage != null) {
974 removeActiveTabPage(true);
975 }
976
The Android Open Source Project0c908882009-03-03 19:32:16 -0800977 cancelStopToast();
978
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800982 }
983
Grace Kloba22ac16e2009-10-07 18:00:23 -0700984 @Override
985 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700986 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
988 }
989 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700990
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
994 }
995
Grace Kloba0923d692009-09-23 21:37:25 -0700996 if (mTabControl == null) return;
997
Grace Kloba1fc98a32009-10-21 13:23:08 -0700998 // Remove the fake title bar if it is there
999 hideFakeTitleBar();
1000
The Android Open Source Project0c908882009-03-03 19:32:16 -08001001 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001002 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001003 if (t != null) {
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1006 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010
Grace Klobab4da0ad2009-05-14 14:45:40 -07001011 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001012 }
1013
1014 @Override
1015 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001016 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 super.onConfigurationChanged(newConfig);
1018
1019 if (mPageInfoDialog != null) {
1020 mPageInfoDialog.dismiss();
1021 showPageInfo(
1022 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001023 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001024 }
1025 if (mSSLCertificateDialog != null) {
1026 mSSLCertificateDialog.dismiss();
1027 showSSLCertificate(
1028 mSSLCertificateView);
1029 }
1030 if (mSSLCertificateOnErrorDialog != null) {
1031 mSSLCertificateOnErrorDialog.dismiss();
1032 showSSLCertificateOnError(
1033 mSSLCertificateOnErrorView,
1034 mSSLCertificateOnErrorHandler,
1035 mSSLCertificateOnErrorError);
1036 }
1037 if (mHttpAuthenticationDialog != null) {
1038 String title = ((TextView) mHttpAuthenticationDialog
1039 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1040 .toString();
1041 String name = ((TextView) mHttpAuthenticationDialog
1042 .findViewById(R.id.username_edit)).getText().toString();
1043 String password = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(R.id.password_edit)).getText().toString();
1045 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1046 .getId();
1047 mHttpAuthenticationDialog.dismiss();
1048 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1049 name, password, focusId);
1050 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001051 }
1052
Grace Kloba22ac16e2009-10-07 18:00:23 -07001053 @Override
1054 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001055 super.onLowMemory();
1056 mTabControl.freeMemory();
1057 }
1058
Mike Reed7bfa63b2009-05-28 11:08:32 -04001059 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001060 Tab tab = mTabControl.getCurrentTab();
1061 boolean inLoad = tab.inLoad();
1062 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001063 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001064 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 if (w != null) {
1066 w.resumeTimers();
1067 }
1068 return true;
1069 } else {
1070 return false;
1071 }
1072 }
1073
Mike Reed7bfa63b2009-05-28 11:08:32 -04001074 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001075 Tab tab = mTabControl.getCurrentTab();
1076 boolean inLoad = tab.inLoad();
1077 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001078 CookieSyncManager.getInstance().stopSync();
1079 WebView w = mTabControl.getCurrentWebView();
1080 if (w != null) {
1081 w.pauseTimers();
1082 }
1083 return true;
1084 } else {
1085 return false;
1086 }
1087 }
1088
Leon Scroggins1f005d32009-08-10 17:36:42 -04001089 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001090 /*
1091 * This function is called when we are launching for the first time. We
1092 * are waiting for the login credentials before loading Google home
1093 * pages. This way the user will be logged in straight away.
1094 */
1095 private void waitForCredentials() {
1096 // Show a toast
1097 mCredsDlg = new ProgressDialog(this);
1098 mCredsDlg.setIndeterminate(true);
1099 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1100 // If the user cancels the operation, then cancel the Google
1101 // Credentials request.
1102 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1103 mCredsDlg.show();
1104
1105 // We set a timeout for the retrieval of credentials in onResume()
1106 // as that is when we have freed up some CPU time to get
1107 // the login credentials.
1108 }
1109
1110 /*
1111 * If we have received the credentials or we have timed out and we are
1112 * showing the credentials dialog, then it is time to move on.
1113 */
1114 private void resumeAfterCredentials() {
1115 if (mCredsDlg == null) {
1116 return;
1117 }
1118
1119 // Clear the toast
1120 if (mCredsDlg.isShowing()) {
1121 mCredsDlg.dismiss();
1122 }
1123 mCredsDlg = null;
1124
1125 // Clear any pending timeout
1126 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1127
1128 // Load the page
1129 WebView w = mTabControl.getCurrentWebView();
1130 if (w != null) {
1131 w.loadUrl(mSettings.getHomePage());
1132 }
1133
1134 // Update the settings, need to do this last as it can take a moment
1135 // to persist the settings. In the mean time we could be loading
1136 // content.
1137 mSettings.setLoginInitialized(this);
1138 }
1139
1140 // Open the icon database and retain all the icons for visited sites.
1141 private void retainIconsOnStartup() {
1142 final WebIconDatabase db = WebIconDatabase.getInstance();
1143 db.open(getDir("icons", 0).getPath());
1144 try {
1145 Cursor c = Browser.getAllBookmarks(mResolver);
1146 if (!c.moveToFirst()) {
1147 c.deactivate();
1148 return;
1149 }
1150 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1151 do {
1152 String url = c.getString(urlIndex);
1153 db.retainIconForPageUrl(url);
1154 } while (c.moveToNext());
1155 c.deactivate();
1156 } catch (IllegalStateException e) {
1157 Log.e(LOGTAG, "retainIconsOnStartup", e);
1158 }
1159 }
1160
1161 // Helper method for getting the top window.
1162 WebView getTopWindow() {
1163 return mTabControl.getCurrentTopWebView();
1164 }
1165
Grace Kloba22ac16e2009-10-07 18:00:23 -07001166 TabControl getTabControl() {
1167 return mTabControl;
1168 }
1169
The Android Open Source Project0c908882009-03-03 19:32:16 -08001170 @Override
1171 public boolean onCreateOptionsMenu(Menu menu) {
1172 super.onCreateOptionsMenu(menu);
1173
1174 MenuInflater inflater = getMenuInflater();
1175 inflater.inflate(R.menu.browser, menu);
1176 mMenu = menu;
1177 updateInLoadMenuItems();
1178 return true;
1179 }
1180
1181 /**
1182 * As the menu can be open when loading state changes
1183 * we must manually update the state of the stop/reload menu
1184 * item
1185 */
1186 private void updateInLoadMenuItems() {
1187 if (mMenu == null) {
1188 return;
1189 }
1190 MenuItem src = mInLoad ?
1191 mMenu.findItem(R.id.stop_menu_id):
1192 mMenu.findItem(R.id.reload_menu_id);
1193 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1194 dest.setIcon(src.getIcon());
1195 dest.setTitle(src.getTitle());
1196 }
1197
1198 @Override
1199 public boolean onContextItemSelected(MenuItem item) {
1200 // chording is not an issue with context menus, but we use the same
1201 // options selector, so set mCanChord to true so we can access them.
1202 mCanChord = true;
1203 int id = item.getItemId();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001204 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001205 // For the context menu from the title bar
1206 case R.id.title_bar_share_page_url:
1207 case R.id.title_bar_copy_page_url:
1208 WebView mainView = mTabControl.getCurrentWebView();
1209 if (null == mainView) {
1210 return false;
1211 }
1212 if (id == R.id.title_bar_share_page_url) {
1213 Browser.sendString(this, mainView.getUrl());
1214 } else {
1215 copy(mainView.getUrl());
1216 }
1217 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001218 // -- Browser context menu
1219 case R.id.open_context_menu_id:
1220 case R.id.open_newtab_context_menu_id:
1221 case R.id.bookmark_context_menu_id:
1222 case R.id.save_link_context_menu_id:
1223 case R.id.share_link_context_menu_id:
1224 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001225 final WebView webView = getTopWindow();
1226 if (null == webView) {
1227 return false;
1228 }
1229 final HashMap hrefMap = new HashMap();
1230 hrefMap.put("webview", webView);
1231 final Message msg = mHandler.obtainMessage(
1232 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001233 webView.requestFocusNodeHref(msg);
1234 break;
1235
1236 default:
1237 // For other context menus
1238 return onOptionsItemSelected(item);
1239 }
1240 mCanChord = false;
1241 return true;
1242 }
1243
1244 private Bundle createGoogleSearchSourceBundle(String source) {
1245 Bundle bundle = new Bundle();
1246 bundle.putString(SearchManager.SOURCE, source);
1247 return bundle;
1248 }
1249
1250 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001251 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001252 */
1253 @Override
1254 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001255 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001256 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001257 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001258 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001259 return true;
1260 }
1261
1262 @Override
1263 public void startSearch(String initialQuery, boolean selectInitialQuery,
1264 Bundle appSearchData, boolean globalSearch) {
1265 if (appSearchData == null) {
1266 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1267 }
1268 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1269 }
1270
Leon Scroggins1f005d32009-08-10 17:36:42 -04001271 /**
1272 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1273 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001274 * @param index Index of the tab to change to, as defined by
1275 * mTabControl.getTabIndex(Tab t).
1276 * @return boolean True if we successfully switched to a different tab. If
1277 * the indexth tab is null, or if that tab is the same as
1278 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001279 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001280 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001281 Tab tab = mTabControl.getTab(index);
1282 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001283 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001284 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001285 }
1286 if (currentTab != null) {
1287 // currentTab may be null if it was just removed. In that case,
1288 // we do not need to remove it
1289 removeTabFromContentView(currentTab);
1290 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001291 mTabControl.setCurrentTab(tab);
1292 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001293 resetTitleIconAndProgress();
1294 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001295 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 }
1297
Grace Kloba22ac16e2009-10-07 18:00:23 -07001298 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001299 return openTabAndShow(mSettings.getHomePage(), false, null);
1300 }
1301
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001303 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001304 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001305 // This is the last tab. Open a new one, with the home
1306 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001307 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001308 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001309 return;
1310 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001312 int indexToShow = -1;
1313 if (parent != null) {
1314 indexToShow = mTabControl.getTabIndex(parent);
1315 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001316 final int currentIndex = mTabControl.getCurrentIndex();
1317 // Try to move to the tab to the right
1318 indexToShow = currentIndex + 1;
1319 if (indexToShow > mTabControl.getTabCount() - 1) {
1320 // Try to move to the tab to the left
1321 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001322 }
1323 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001324 if (switchToTab(indexToShow)) {
1325 // Close window
1326 closeTab(current);
1327 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001328 }
1329
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001330 private ActiveTabsPage mActiveTabsPage;
1331
1332 /**
1333 * Remove the active tabs page.
1334 * @param needToAttach If true, the active tabs page did not attach a tab
1335 * to the content view, so we need to do that here.
1336 */
1337 /* package */ void removeActiveTabPage(boolean needToAttach) {
1338 mContentView.removeView(mActiveTabsPage);
1339 mActiveTabsPage = null;
1340 mMenuState = R.id.MAIN_MENU;
1341 if (needToAttach) {
1342 attachTabToContentView(mTabControl.getCurrentTab());
1343 }
1344 getTopWindow().requestFocus();
1345 }
1346
The Android Open Source Project0c908882009-03-03 19:32:16 -08001347 @Override
1348 public boolean onOptionsItemSelected(MenuItem item) {
1349 if (!mCanChord) {
1350 // The user has already fired a shortcut with this hold down of the
1351 // menu key.
1352 return false;
1353 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001354 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001355 return false;
1356 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001357 if (mMenuIsDown) {
1358 // The shortcut action consumes the MENU. Even if it is still down,
1359 // it won't trigger the next shortcut action. In the case of the
1360 // shortcut action triggering a new activity, like Bookmarks, we
1361 // won't get onKeyUp for MENU. So it is important to reset it here.
1362 mMenuIsDown = false;
1363 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001364 switch (item.getItemId()) {
1365 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001366 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001367 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001368 break;
1369
Leon Scroggins64b80f32009-08-07 12:03:34 -04001370 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001371 onSearchRequested();
1372 break;
1373
1374 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001375 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001376 break;
1377
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001378 case R.id.active_tabs_menu_id:
1379 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1380 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001381 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001382 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1383 mActiveTabsPage.requestFocus();
1384 mMenuState = EMPTY_MENU;
1385 break;
1386
Leon Scroggins1f005d32009-08-10 17:36:42 -04001387 case R.id.add_bookmark_menu_id:
1388 Intent i = new Intent(BrowserActivity.this,
1389 AddBookmarkPage.class);
1390 WebView w = getTopWindow();
1391 i.putExtra("url", w.getUrl());
1392 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001393 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001394 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001395 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001396 break;
1397
1398 case R.id.stop_reload_menu_id:
1399 if (mInLoad) {
1400 stopLoading();
1401 } else {
1402 getTopWindow().reload();
1403 }
1404 break;
1405
1406 case R.id.back_menu_id:
1407 getTopWindow().goBack();
1408 break;
1409
1410 case R.id.forward_menu_id:
1411 getTopWindow().goForward();
1412 break;
1413
1414 case R.id.close_menu_id:
1415 // Close the subwindow if it exists.
1416 if (mTabControl.getCurrentSubWindow() != null) {
1417 dismissSubWindow(mTabControl.getCurrentTab());
1418 break;
1419 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001420 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001421 break;
1422
1423 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001424 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001425 if (current != null) {
1426 dismissSubWindow(current);
1427 current.getWebView().loadUrl(mSettings.getHomePage());
1428 }
1429 break;
1430
1431 case R.id.preferences_menu_id:
1432 Intent intent = new Intent(this,
1433 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001434 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1435 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001436 startActivityForResult(intent, PREFERENCES_PAGE);
1437 break;
1438
1439 case R.id.find_menu_id:
1440 if (null == mFindDialog) {
1441 mFindDialog = new FindDialog(this);
1442 }
1443 mFindDialog.setWebView(getTopWindow());
1444 mFindDialog.show();
1445 mMenuState = EMPTY_MENU;
1446 break;
1447
1448 case R.id.select_text_id:
1449 getTopWindow().emulateShiftHeld();
1450 break;
1451 case R.id.page_info_menu_id:
1452 showPageInfo(mTabControl.getCurrentTab(), false);
1453 break;
1454
1455 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001456 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001457 break;
1458
1459 case R.id.share_page_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01001460 Browser.sendString(this, getTopWindow().getUrl(),
1461 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001462 break;
1463
1464 case R.id.dump_nav_menu_id:
1465 getTopWindow().debugDump();
1466 break;
1467
1468 case R.id.zoom_in_menu_id:
1469 getTopWindow().zoomIn();
1470 break;
1471
1472 case R.id.zoom_out_menu_id:
1473 getTopWindow().zoomOut();
1474 break;
1475
1476 case R.id.view_downloads_menu_id:
1477 viewDownloads(null);
1478 break;
1479
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 case R.id.window_one_menu_id:
1481 case R.id.window_two_menu_id:
1482 case R.id.window_three_menu_id:
1483 case R.id.window_four_menu_id:
1484 case R.id.window_five_menu_id:
1485 case R.id.window_six_menu_id:
1486 case R.id.window_seven_menu_id:
1487 case R.id.window_eight_menu_id:
1488 {
1489 int menuid = item.getItemId();
1490 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1491 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001492 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001493 if (desiredTab != null &&
1494 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001495 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001496 }
1497 break;
1498 }
1499 }
1500 }
1501 break;
1502
1503 default:
1504 if (!super.onOptionsItemSelected(item)) {
1505 return false;
1506 }
1507 // Otherwise fall through.
1508 }
1509 mCanChord = false;
1510 return true;
1511 }
1512
1513 public void closeFind() {
1514 mMenuState = R.id.MAIN_MENU;
1515 }
1516
Grace Kloba22ac16e2009-10-07 18:00:23 -07001517 @Override
1518 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001519 // This happens when the user begins to hold down the menu key, so
1520 // allow them to chord to get a shortcut.
1521 mCanChord = true;
1522 // Note: setVisible will decide whether an item is visible; while
1523 // setEnabled() will decide whether an item is enabled, which also means
1524 // whether the matching shortcut key will function.
1525 super.onPrepareOptionsMenu(menu);
1526 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001527 case EMPTY_MENU:
1528 if (mCurrentMenuState != mMenuState) {
1529 menu.setGroupVisible(R.id.MAIN_MENU, false);
1530 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1531 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001532 }
1533 break;
1534 default:
1535 if (mCurrentMenuState != mMenuState) {
1536 menu.setGroupVisible(R.id.MAIN_MENU, true);
1537 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1538 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001539 }
1540 final WebView w = getTopWindow();
1541 boolean canGoBack = false;
1542 boolean canGoForward = false;
1543 boolean isHome = false;
1544 if (w != null) {
1545 canGoBack = w.canGoBack();
1546 canGoForward = w.canGoForward();
1547 isHome = mSettings.getHomePage().equals(w.getUrl());
1548 }
1549 final MenuItem back = menu.findItem(R.id.back_menu_id);
1550 back.setEnabled(canGoBack);
1551
1552 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1553 home.setEnabled(!isHome);
1554
1555 menu.findItem(R.id.forward_menu_id)
1556 .setEnabled(canGoForward);
1557
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001558 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001559 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001560
The Android Open Source Project0c908882009-03-03 19:32:16 -08001561 // decide whether to show the share link option
1562 PackageManager pm = getPackageManager();
1563 Intent send = new Intent(Intent.ACTION_SEND);
1564 send.setType("text/plain");
1565 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1566 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1567
The Android Open Source Project0c908882009-03-03 19:32:16 -08001568 boolean isNavDump = mSettings.isNavDump();
1569 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1570 nav.setVisible(isNavDump);
1571 nav.setEnabled(isNavDump);
1572 break;
1573 }
1574 mCurrentMenuState = mMenuState;
1575 return true;
1576 }
1577
1578 @Override
1579 public void onCreateContextMenu(ContextMenu menu, View v,
1580 ContextMenuInfo menuInfo) {
1581 WebView webview = (WebView) v;
1582 WebView.HitTestResult result = webview.getHitTestResult();
1583 if (result == null) {
1584 return;
1585 }
1586
1587 int type = result.getType();
1588 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1589 Log.w(LOGTAG,
1590 "We should not show context menu when nothing is touched");
1591 return;
1592 }
1593 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1594 // let TextView handles context menu
1595 return;
1596 }
1597
1598 // Note, http://b/issue?id=1106666 is requesting that
1599 // an inflated menu can be used again. This is not available
1600 // yet, so inflate each time (yuk!)
1601 MenuInflater inflater = getMenuInflater();
1602 inflater.inflate(R.menu.browsercontext, menu);
1603
1604 // Show the correct menu group
1605 String extra = result.getExtra();
1606 menu.setGroupVisible(R.id.PHONE_MENU,
1607 type == WebView.HitTestResult.PHONE_TYPE);
1608 menu.setGroupVisible(R.id.EMAIL_MENU,
1609 type == WebView.HitTestResult.EMAIL_TYPE);
1610 menu.setGroupVisible(R.id.GEO_MENU,
1611 type == WebView.HitTestResult.GEO_TYPE);
1612 menu.setGroupVisible(R.id.IMAGE_MENU,
1613 type == WebView.HitTestResult.IMAGE_TYPE
1614 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1615 menu.setGroupVisible(R.id.ANCHOR_MENU,
1616 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1617 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1618
1619 // Setup custom handling depending on the type
1620 switch (type) {
1621 case WebView.HitTestResult.PHONE_TYPE:
1622 menu.setHeaderTitle(Uri.decode(extra));
1623 menu.findItem(R.id.dial_context_menu_id).setIntent(
1624 new Intent(Intent.ACTION_VIEW, Uri
1625 .parse(WebView.SCHEME_TEL + extra)));
1626 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1627 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001628 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001629 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1630 addIntent);
1631 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1632 new Copy(extra));
1633 break;
1634
1635 case WebView.HitTestResult.EMAIL_TYPE:
1636 menu.setHeaderTitle(extra);
1637 menu.findItem(R.id.email_context_menu_id).setIntent(
1638 new Intent(Intent.ACTION_VIEW, Uri
1639 .parse(WebView.SCHEME_MAILTO + extra)));
1640 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1641 new Copy(extra));
1642 break;
1643
1644 case WebView.HitTestResult.GEO_TYPE:
1645 menu.setHeaderTitle(extra);
1646 menu.findItem(R.id.map_context_menu_id).setIntent(
1647 new Intent(Intent.ACTION_VIEW, Uri
1648 .parse(WebView.SCHEME_GEO
1649 + URLEncoder.encode(extra))));
1650 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1651 new Copy(extra));
1652 break;
1653
1654 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1655 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1656 TextView titleView = (TextView) LayoutInflater.from(this)
1657 .inflate(android.R.layout.browser_link_context_header,
1658 null);
1659 titleView.setText(extra);
1660 menu.setHeaderView(titleView);
1661 // decide whether to show the open link in new tab option
1662 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001663 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001664 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1665 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001666 PackageManager pm = getPackageManager();
1667 Intent send = new Intent(Intent.ACTION_SEND);
1668 send.setType("text/plain");
1669 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1670 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1671 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1672 break;
1673 }
1674 // otherwise fall through to handle image part
1675 case WebView.HitTestResult.IMAGE_TYPE:
1676 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1677 menu.setHeaderTitle(extra);
1678 }
1679 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1680 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1681 menu.findItem(R.id.download_context_menu_id).
1682 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001683 menu.findItem(R.id.set_wallpaper_context_menu_id).
1684 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001685 break;
1686
1687 default:
1688 Log.w(LOGTAG, "We should not get here.");
1689 break;
1690 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001691 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001692 }
1693
The Android Open Source Project0c908882009-03-03 19:32:16 -08001694 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001695 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001696 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001697 // Attach the container that contains the main WebView and any other UI
1698 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001699 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001700
1701 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001702 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001703 if (errorConsole.numberOfErrors() == 0) {
1704 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1705 } else {
1706 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1707 }
1708
1709 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001710 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001711 ViewGroup.LayoutParams.WRAP_CONTENT));
1712 }
1713
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001714 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001715 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001716 // Request focus on the top window.
1717 t.getTopWindow().requestFocus();
1718 }
1719
1720 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001721 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001722 t.attachSubWindow(mContentView);
1723 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001724 }
1725
1726 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001727 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001728 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001729 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730
Grace Kloba22ac16e2009-10-07 18:00:23 -07001731 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1732 if (errorConsole != null) {
1733 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001734 }
1735
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001736 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001737 if (view != null) {
1738 view.setEmbeddedTitleBar(null);
1739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001740 }
1741
1742 // Remove the sub window if it exists. Also called by TabControl when the
1743 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001745 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 // dismiss the subwindow. This will destroy the WebView.
1747 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001748 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001749 }
1750
Leon Scroggins1f005d32009-08-10 17:36:42 -04001751 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001752 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001753 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001754 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001755 }
1756
1757 // This method does a ton of stuff. It will attempt to create a new tab
1758 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001759 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001760 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1761 String appId) {
1762 final Tab currentTab = mTabControl.getCurrentTab();
1763 if (mTabControl.canCreateNewTab()) {
1764 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1765 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001766 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001767 // If the last tab was removed from the active tabs page, currentTab
1768 // will be null.
1769 if (currentTab != null) {
1770 removeTabFromContentView(currentTab);
1771 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001772 // We must set the new tab as the current tab to reflect the old
1773 // animation behavior.
1774 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001775 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001776 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001777 urlData.loadIn(webview);
1778 }
1779 return tab;
1780 } else {
1781 // Get rid of the subwindow if it exists
1782 dismissSubWindow(currentTab);
1783 if (!urlData.isEmpty()) {
1784 // Load the given url.
1785 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001786 }
1787 }
Grace Klobac9181842009-04-14 08:53:22 -07001788 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001789 }
1790
Grace Kloba22ac16e2009-10-07 18:00:23 -07001791 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001792 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001793 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001794 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001795 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001796 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001797 }
Grace Klobac9181842009-04-14 08:53:22 -07001798 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001799 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001800 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001801 }
1802 }
1803
1804 private class Copy implements OnMenuItemClickListener {
1805 private CharSequence mText;
1806
1807 public boolean onMenuItemClick(MenuItem item) {
1808 copy(mText);
1809 return true;
1810 }
1811
1812 public Copy(CharSequence toCopy) {
1813 mText = toCopy;
1814 }
1815 }
1816
1817 private class Download implements OnMenuItemClickListener {
1818 private String mText;
1819
1820 public boolean onMenuItemClick(MenuItem item) {
1821 onDownloadStartNoStream(mText, null, null, null, -1);
1822 return true;
1823 }
1824
1825 public Download(String toDownload) {
1826 mText = toDownload;
1827 }
1828 }
1829
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001830 private class SetAsWallpaper extends Thread implements
1831 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1832 private URL mUrl;
1833 private ProgressDialog mWallpaperProgress;
1834 private boolean mCanceled = false;
1835
1836 public SetAsWallpaper(String url) {
1837 try {
1838 mUrl = new URL(url);
1839 } catch (MalformedURLException e) {
1840 mUrl = null;
1841 }
1842 }
1843
1844 public void onCancel(DialogInterface dialog) {
1845 mCanceled = true;
1846 }
1847
1848 public boolean onMenuItemClick(MenuItem item) {
1849 if (mUrl != null) {
1850 // The user may have tried to set a image with a large file size as their
1851 // background so it may take a few moments to perform the operation. Display
1852 // a progress spinner while it is working.
1853 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1854 mWallpaperProgress.setIndeterminate(true);
1855 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1856 mWallpaperProgress.setCancelable(true);
1857 mWallpaperProgress.setOnCancelListener(this);
1858 mWallpaperProgress.show();
1859 start();
1860 }
1861 return true;
1862 }
1863
1864 public void run() {
1865 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1866 try {
1867 // TODO: This will cause the resource to be downloaded again, when we
1868 // should in most cases be able to grab it from the cache. To fix this
1869 // we should query WebCore to see if we can access a cached version and
1870 // instead open an input stream on that. This pattern could also be used
1871 // in the download manager where the same problem exists.
1872 InputStream inputstream = mUrl.openStream();
1873 if (inputstream != null) {
1874 setWallpaper(inputstream);
1875 }
1876 } catch (IOException e) {
1877 Log.e(LOGTAG, "Unable to set new wallpaper");
1878 // Act as though the user canceled the operation so we try to
1879 // restore the old wallpaper.
1880 mCanceled = true;
1881 }
1882
1883 if (mCanceled) {
1884 // Restore the old wallpaper if the user cancelled whilst we were setting
1885 // the new wallpaper.
1886 int width = oldWallpaper.getIntrinsicWidth();
1887 int height = oldWallpaper.getIntrinsicHeight();
1888 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1889 Canvas canvas = new Canvas(bm);
1890 oldWallpaper.setBounds(0, 0, width, height);
1891 oldWallpaper.draw(canvas);
1892 try {
1893 setWallpaper(bm);
1894 } catch (IOException e) {
1895 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1896 }
1897 mCanceled = false;
1898 }
1899
1900 if (mWallpaperProgress.isShowing()) {
1901 mWallpaperProgress.dismiss();
1902 }
1903 }
1904 }
1905
The Android Open Source Project0c908882009-03-03 19:32:16 -08001906 private void copy(CharSequence text) {
1907 try {
1908 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1909 if (clip != null) {
1910 clip.setClipboardText(text);
1911 }
1912 } catch (android.os.RemoteException e) {
1913 Log.e(LOGTAG, "Copy failed", e);
1914 }
1915 }
1916
1917 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001918 * Resets the browser title-view to whatever it must be
1919 * (for example, if we had a loading error)
1920 * When we have a new page, we call resetTitle, when we
1921 * have to reset the titlebar to whatever it used to be
1922 * (for example, if the user chose to stop loading), we
1923 * call resetTitleAndRevertLockIcon.
1924 */
1925 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001926 mTabControl.getCurrentTab().revertLockIcon();
1927 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001928 resetTitleIconAndProgress();
1929 }
1930
1931 /**
1932 * Reset the title, favicon, and progress.
1933 */
1934 private void resetTitleIconAndProgress() {
1935 WebView current = mTabControl.getCurrentWebView();
1936 if (current == null) {
1937 return;
1938 }
1939 resetTitleAndIcon(current);
1940 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001941 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001942 }
1943
1944 // Reset the title and the icon based on the given item.
1945 private void resetTitleAndIcon(WebView view) {
1946 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1947 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001948 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 setFavicon(item.getFavicon());
1950 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001951 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001952 setFavicon(null);
1953 }
1954 }
1955
1956 /**
1957 * Sets a title composed of the URL and the title string.
1958 * @param url The URL of the site being loaded.
1959 * @param title The title of the site being loaded.
1960 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001961 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 mUrl = url;
1963 mTitle = title;
1964
Leon Scroggins68579392009-09-15 15:31:54 -04001965 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001966 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001967 }
1968
1969 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 * @param url The URL to build a title version of the URL from.
1971 * @return The title version of the URL or null if fails.
1972 * The title version of the URL can be either the URL hostname,
1973 * or the hostname with an "https://" prefix (for secure URLs),
1974 * or an empty string if, for example, the URL in question is a
1975 * file:// URL with no hostname.
1976 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001977 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001978 String titleUrl = null;
1979
1980 if (url != null) {
1981 try {
1982 // parse the url string
1983 URL urlObj = new URL(url);
1984 if (urlObj != null) {
1985 titleUrl = "";
1986
1987 String protocol = urlObj.getProtocol();
1988 String host = urlObj.getHost();
1989
1990 if (host != null && 0 < host.length()) {
1991 titleUrl = host;
1992 if (protocol != null) {
1993 // if a secure site, add an "https://" prefix!
1994 if (protocol.equalsIgnoreCase("https")) {
1995 titleUrl = protocol + "://" + host;
1996 }
1997 }
1998 }
1999 }
2000 } catch (MalformedURLException e) {}
2001 }
2002
2003 return titleUrl;
2004 }
2005
2006 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002007 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002008 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002009 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002010 }
2011
2012 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002013 * Close the tab, remove its associated title bar, and adjust mTabControl's
2014 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002015 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002016 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002017 int currentIndex = mTabControl.getCurrentIndex();
2018 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002019 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002020 if (currentIndex >= removeIndex && currentIndex != 0) {
2021 currentIndex--;
2022 }
2023 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002024 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 }
2026
2027 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002028 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 if (current == null) {
2030 /*
2031 * Instead of finishing the activity, simply push this to the back
2032 * of the stack and let ActivityManager to choose the foreground
2033 * activity. As BrowserActivity is singleTask, it will be always the
2034 * root of the task. So we can use either true or false for
2035 * moveTaskToBack().
2036 */
2037 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002038 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 }
2040 WebView w = current.getWebView();
2041 if (w.canGoBack()) {
2042 w.goBack();
2043 } else {
2044 // Check to see if we are closing a window that was created by
2045 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002046 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002047 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002048 switchToTab(mTabControl.getTabIndex(parent));
2049 // Now we close the other tab
2050 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 } else {
2052 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002053 // force the tab's inLoad() to be false as we are going to
2054 // either finish the activity or remove the tab. This will
2055 // ensure pauseWebViewTimers() taking action.
2056 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002057 if (mTabControl.getTabCount() == 1) {
2058 finish();
2059 return;
2060 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002061 // call pauseWebViewTimers() now, we won't be able to call
2062 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002063 // Temporarily change mActivityInPause to be true as
2064 // pauseWebViewTimers() will do nothing if mActivityInPause
2065 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002066 boolean savedState = mActivityInPause;
2067 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002068 Log.e(LOGTAG, "BrowserActivity is already paused "
2069 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002070 }
2071 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002072 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002073 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 removeTabFromContentView(current);
2075 mTabControl.removeTab(current);
2076 }
2077 /*
2078 * Instead of finishing the activity, simply push this to the back
2079 * of the stack and let ActivityManager to choose the foreground
2080 * activity. As BrowserActivity is singleTask, it will be always the
2081 * root of the task. So we can use either true or false for
2082 * moveTaskToBack().
2083 */
2084 moveTaskToBack(true);
2085 }
2086 }
2087 }
2088
Grace Kloba22ac16e2009-10-07 18:00:23 -07002089 boolean isMenuDown() {
2090 return mMenuIsDown;
2091 }
2092
Grace Kloba5942df02009-09-18 11:48:29 -07002093 @Override
2094 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002095 // Even if MENU is already held down, we need to call to super to open
2096 // the IME on long press.
2097 if (KeyEvent.KEYCODE_MENU == keyCode) {
2098 mMenuIsDown = true;
2099 return super.onKeyDown(keyCode, event);
2100 }
Grace Kloba5942df02009-09-18 11:48:29 -07002101 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2102 // still down, we don't want to trigger the search. Pretend to consume
2103 // the key and do nothing.
2104 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002105
Grace Kloba5942df02009-09-18 11:48:29 -07002106 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002107 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002108 // WebView/WebTextView handle the keys in the KeyDown. As
2109 // the Activity's shortcut keys are only handled when WebView
2110 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2111 if (event.isShiftPressed()) {
2112 getTopWindow().pageUp(false);
2113 } else {
2114 getTopWindow().pageDown(false);
2115 }
Grace Kloba5942df02009-09-18 11:48:29 -07002116 return true;
2117 case KeyEvent.KEYCODE_BACK:
2118 if (event.getRepeatCount() == 0) {
2119 event.startTracking();
2120 return true;
2121 } else if (mCustomView == null && mActiveTabsPage == null
2122 && event.isLongPress()) {
2123 bookmarksOrHistoryPicker(true);
2124 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002125 }
Grace Kloba5942df02009-09-18 11:48:29 -07002126 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002127 }
Grace Kloba5942df02009-09-18 11:48:29 -07002128 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002129 }
2130
Grace Kloba5942df02009-09-18 11:48:29 -07002131 @Override
2132 public boolean onKeyUp(int keyCode, KeyEvent event) {
2133 switch(keyCode) {
2134 case KeyEvent.KEYCODE_MENU:
2135 mMenuIsDown = false;
2136 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002137 case KeyEvent.KEYCODE_BACK:
2138 if (event.isTracking() && !event.isCanceled()) {
2139 if (mCustomView != null) {
2140 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002141 mTabControl.getCurrentWebView().getWebChromeClient()
2142 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002143 } else if (mActiveTabsPage != null) {
2144 // if tab page is showing, hide it
2145 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002147 WebView subwindow = mTabControl.getCurrentSubWindow();
2148 if (subwindow != null) {
2149 if (subwindow.canGoBack()) {
2150 subwindow.goBack();
2151 } else {
2152 dismissSubWindow(mTabControl.getCurrentTab());
2153 }
2154 } else {
2155 goBackOnePageOrQuit();
2156 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 }
Grace Kloba5942df02009-09-18 11:48:29 -07002158 return true;
2159 }
2160 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002161 }
Grace Kloba5942df02009-09-18 11:48:29 -07002162 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 }
2164
Leon Scroggins68579392009-09-15 15:31:54 -04002165 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002166 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 resetTitleAndRevertLockIcon();
2168 WebView w = getTopWindow();
2169 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002170 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2171 // same logic here. But for subwindow case, should we call into the main
2172 // WebView's onPageFinished as we never call its onPageStarted and if
2173 // the page finishes itself, we don't call onPageFinished.
2174 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2175 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176
2177 cancelStopToast();
2178 mStopToast = Toast
2179 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2180 mStopToast.show();
2181 }
2182
Grace Kloba22ac16e2009-10-07 18:00:23 -07002183 boolean didUserStopLoading() {
2184 return mDidStopLoad;
2185 }
2186
The Android Open Source Project0c908882009-03-03 19:32:16 -08002187 private void cancelStopToast() {
2188 if (mStopToast != null) {
2189 mStopToast.cancel();
2190 mStopToast = null;
2191 }
2192 }
2193
Grace Kloba22ac16e2009-10-07 18:00:23 -07002194 // called by a UI or non-UI thread to post the message
2195 public void postMessage(int what, int arg1, int arg2, Object obj,
2196 long delayMillis) {
2197 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2198 obj), delayMillis);
2199 }
2200
2201 // called by a UI or non-UI thread to remove the message
2202 void removeMessages(int what, Object object) {
2203 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002204 }
2205
2206 // public message ids
2207 public final static int LOAD_URL = 1001;
2208 public final static int STOP_LOAD = 1002;
2209
2210 // Message Ids
2211 private static final int FOCUS_NODE_HREF = 102;
2212 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002213 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214
Grace Kloba22ac16e2009-10-07 18:00:23 -07002215 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002216
The Android Open Source Project0c908882009-03-03 19:32:16 -08002217 // Private handler for handling javascript and saving passwords
2218 private Handler mHandler = new Handler() {
2219
2220 public void handleMessage(Message msg) {
2221 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002222 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002223 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002224 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002225 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002226 if (url == null || url.length() == 0) {
2227 break;
2228 }
2229 HashMap focusNodeMap = (HashMap) msg.obj;
2230 WebView view = (WebView) focusNodeMap.get("webview");
2231 // Only apply the action if the top window did not change.
2232 if (getTopWindow() != view) {
2233 break;
2234 }
2235 switch (msg.arg1) {
2236 case R.id.open_context_menu_id:
2237 case R.id.view_image_context_menu_id:
2238 loadURL(getTopWindow(), url);
2239 break;
2240 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002241 final Tab parent = mTabControl.getCurrentTab();
2242 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002243 if (newTab != parent) {
2244 parent.addChildTab(newTab);
2245 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002246 break;
2247 case R.id.bookmark_context_menu_id:
2248 Intent intent = new Intent(BrowserActivity.this,
2249 AddBookmarkPage.class);
2250 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002251 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002252 startActivity(intent);
2253 break;
2254 case R.id.share_link_context_menu_id:
Andrei Popescu10fdba82009-09-24 13:25:47 +01002255 Browser.sendString(BrowserActivity.this, url,
2256 getText(R.string.choosertitle_sharevia).toString());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002257 break;
2258 case R.id.copy_link_context_menu_id:
2259 copy(url);
2260 break;
2261 case R.id.save_link_context_menu_id:
2262 case R.id.download_context_menu_id:
2263 onDownloadStartNoStream(url, null, null, null, -1);
2264 break;
2265 }
2266 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002267 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002268
2269 case LOAD_URL:
2270 loadURL(getTopWindow(), (String) msg.obj);
2271 break;
2272
2273 case STOP_LOAD:
2274 stopLoading();
2275 break;
2276
2277 case CANCEL_CREDS_REQUEST:
2278 resumeAfterCredentials();
2279 break;
2280
The Android Open Source Project0c908882009-03-03 19:32:16 -08002281 case RELEASE_WAKELOCK:
2282 if (mWakeLock.isHeld()) {
2283 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002284 // if we reach here, Browser should be still in the
2285 // background loading after WAKELOCK_TIMEOUT (5-min).
2286 // To avoid burning the battery, stop loading.
2287 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002288 }
2289 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002290
2291 case UPDATE_BOOKMARK_THUMBNAIL:
2292 WebView view = (WebView) msg.obj;
2293 if (view != null) {
2294 updateScreenshot(view);
2295 }
2296 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002297 }
2298 }
2299 };
2300
Leon Scroggins89c6d362009-07-15 16:54:37 -04002301 private void updateScreenshot(WebView view) {
2302 // If this is a bookmarked site, add a screenshot to the database.
2303 // FIXME: When should we update? Every time?
2304 // FIXME: Would like to make sure there is actually something to
2305 // draw, but the API for that (WebViewCore.pictureReady()) is not
2306 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002307
Patrick Scott3918d442009-08-04 13:22:29 -04002308 ContentResolver cr = getContentResolver();
2309 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002310 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002311 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002312 boolean succeed = c.moveToFirst();
2313 ContentValues values = null;
2314 while (succeed) {
2315 if (values == null) {
2316 final ByteArrayOutputStream os
2317 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002318 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002319 if (bm == null) {
2320 c.close();
2321 return;
2322 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002323 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2324 values = new ContentValues();
2325 values.put(Browser.BookmarkColumns.THUMBNAIL,
2326 os.toByteArray());
2327 }
2328 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2329 c.getInt(0)), values, null, null);
2330 succeed = c.moveToNext();
2331 }
2332 c.close();
2333 }
2334 }
2335
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002336 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002337 * Values for the size of the thumbnail created when taking a screenshot.
2338 * Lazily initialized. Instead of using these directly, use
2339 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002340 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002341 private static int THUMBNAIL_WIDTH = 0;
2342 private static int THUMBNAIL_HEIGHT = 0;
2343
2344 /**
2345 * Return the desired width for thumbnail screenshots, which are stored in
2346 * the database, and used on the bookmarks screen.
2347 * @param context Context for finding out the density of the screen.
2348 * @return int desired width for thumbnail screenshot.
2349 */
2350 /* package */ static int getDesiredThumbnailWidth(Context context) {
2351 if (THUMBNAIL_WIDTH == 0) {
2352 float density = context.getResources().getDisplayMetrics().density;
2353 THUMBNAIL_WIDTH = (int) (90 * density);
2354 THUMBNAIL_HEIGHT = (int) (80 * density);
2355 }
2356 return THUMBNAIL_WIDTH;
2357 }
2358
2359 /**
2360 * Return the desired height for thumbnail screenshots, which are stored in
2361 * the database, and used on the bookmarks screen.
2362 * @param context Context for finding out the density of the screen.
2363 * @return int desired height for thumbnail screenshot.
2364 */
2365 /* package */ static int getDesiredThumbnailHeight(Context context) {
2366 // To ensure that they are both initialized.
2367 getDesiredThumbnailWidth(context);
2368 return THUMBNAIL_HEIGHT;
2369 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002370
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002371 private Bitmap createScreenshot(WebView view) {
2372 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002373 if (thumbnail == null) {
2374 return null;
2375 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002376 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2377 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002378 Canvas canvas = new Canvas(bm);
2379 // May need to tweak these values to determine what is the
2380 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002381 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002382 int thumbnailHeight = thumbnail.getHeight();
2383 float scaleFactorX = 1.0f;
2384 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002385 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002386 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002387 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002388 } else {
2389 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002390 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002391
2392 if (view.getWidth() > view.getHeight() &&
2393 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2394 // If the device is in landscape and the page is shorter
2395 // than the height of the view, stretch the thumbnail to fill the
2396 // space.
2397 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2398 (float)thumbnailHeight;
2399 } else {
2400 // In the portrait case, this looks nice.
2401 scaleFactorY = scaleFactorX;
2402 }
2403
2404 canvas.scale(scaleFactorX, scaleFactorY);
2405
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002406 thumbnail.draw(canvas);
2407 return bm;
2408 }
2409
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002411 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002412 //-------------------------------------------------------------------------
2413
2414 // Use in overrideUrlLoading
2415 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2416 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2417 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2418 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2419
Grace Kloba22ac16e2009-10-07 18:00:23 -07002420 void onPageStarted(WebView view, String url, Bitmap favicon) {
2421 // when BrowserActivity just starts, onPageStarted may be called before
2422 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2423 // to start the timer. As we won't switch tabs while an activity is in
2424 // pause state, we can ensure calling resume and pause in pair.
2425 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002426
Grace Kloba22ac16e2009-10-07 18:00:23 -07002427 resetLockIcon(url);
2428 setUrlTitle(url, null);
2429 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002430 // Keep this initial progress in sync with initialProgressValue (* 100)
2431 // in ProgressTracker.cpp
2432 // Show some progress so that the user knows the page is beginning to
2433 // load
2434 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002435 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002436 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002437
Grace Kloba22ac16e2009-10-07 18:00:23 -07002438 if (mSettings.isTracing()) {
2439 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002440 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002441 WebAddress uri = new WebAddress(url);
2442 host = uri.mHost;
2443 } catch (android.net.ParseException ex) {
2444 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002445 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002446 host = host.replace('.', '_');
2447 host += ".trace";
2448 mInTrace = true;
2449 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2450 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002451
Grace Kloba22ac16e2009-10-07 18:00:23 -07002452 // Performance probe
2453 if (false) {
2454 mStart = SystemClock.uptimeMillis();
2455 mProcessStart = Process.getElapsedCpuTime();
2456 long[] sysCpu = new long[7];
2457 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2458 sysCpu, null)) {
2459 mUserStart = sysCpu[0] + sysCpu[1];
2460 mSystemStart = sysCpu[2];
2461 mIdleStart = sysCpu[3];
2462 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2463 }
2464 mUiStart = SystemClock.currentThreadTimeMillis();
2465 }
2466 }
2467
2468 void onPageFinished(WebView view, String url) {
2469 // Reset the title and icon in case we stopped a provisional load.
2470 resetTitleAndIcon(view);
2471 // Update the lock icon image only once we are done loading
2472 updateLockIconToLatest();
2473 // pause the WebView timer and release the wake lock if it is finished
2474 // while BrowserActivity is in pause state.
2475 if (mActivityInPause && pauseWebViewTimers()) {
2476 if (mWakeLock.isHeld()) {
2477 mHandler.removeMessages(RELEASE_WAKELOCK);
2478 mWakeLock.release();
2479 }
2480 }
2481
2482 // Performance probe
2483 if (false) {
2484 long[] sysCpu = new long[7];
2485 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2486 sysCpu, null)) {
2487 String uiInfo = "UI thread used "
2488 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2489 + " ms";
2490 if (LOGD_ENABLED) {
2491 Log.d(LOGTAG, uiInfo);
2492 }
2493 //The string that gets written to the log
2494 String performanceString = "It took total "
2495 + (SystemClock.uptimeMillis() - mStart)
2496 + " ms clock time to load the page."
2497 + "\nbrowser process used "
2498 + (Process.getElapsedCpuTime() - mProcessStart)
2499 + " ms, user processes used "
2500 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2501 + " ms, kernel used "
2502 + (sysCpu[2] - mSystemStart) * 10
2503 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2504 + " ms and irq took "
2505 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2506 * 10 + " ms, " + uiInfo;
2507 if (LOGD_ENABLED) {
2508 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2509 }
2510 if (url != null) {
2511 // strip the url to maintain consistency
2512 String newUrl = new String(url);
2513 if (newUrl.startsWith("http://www.")) {
2514 newUrl = newUrl.substring(11);
2515 } else if (newUrl.startsWith("http://")) {
2516 newUrl = newUrl.substring(7);
2517 } else if (newUrl.startsWith("https://www.")) {
2518 newUrl = newUrl.substring(12);
2519 } else if (newUrl.startsWith("https://")) {
2520 newUrl = newUrl.substring(8);
2521 }
2522 if (LOGD_ENABLED) {
2523 Log.d(LOGTAG, newUrl + " loaded");
2524 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002525 }
2526 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002527 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002528
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 if (mInTrace) {
2530 mInTrace = false;
2531 Debug.stopMethodTracing();
2532 }
2533 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 boolean shouldOverrideUrlLoading(WebView view, String url) {
2536 if (url.startsWith(SCHEME_WTAI)) {
2537 // wtai://wp/mc;number
2538 // number=string(phone-number)
2539 if (url.startsWith(SCHEME_WTAI_MC)) {
2540 Intent intent = new Intent(Intent.ACTION_VIEW,
2541 Uri.parse(WebView.SCHEME_TEL +
2542 url.substring(SCHEME_WTAI_MC.length())));
2543 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002544 return true;
2545 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002546 // wtai://wp/sd;dtmf
2547 // dtmf=string(dialstring)
2548 if (url.startsWith(SCHEME_WTAI_SD)) {
2549 // TODO: only send when there is active voice connection
2550 return false;
2551 }
2552 // wtai://wp/ap;number;name
2553 // number=string(phone-number)
2554 // name=string
2555 if (url.startsWith(SCHEME_WTAI_AP)) {
2556 // TODO
2557 return false;
2558 }
2559 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002560
Grace Kloba22ac16e2009-10-07 18:00:23 -07002561 // The "about:" schemes are internal to the browser; don't want these to
2562 // be dispatched to other apps.
2563 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002564 return false;
2565 }
2566
Grace Kloba22ac16e2009-10-07 18:00:23 -07002567 Intent intent;
2568 // perform generic parsing of the URI to turn it into an Intent.
2569 try {
2570 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2571 } catch (URISyntaxException ex) {
2572 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2573 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002574 }
2575
Grace Kloba22ac16e2009-10-07 18:00:23 -07002576 // check whether the intent can be resolved. If not, we will see
2577 // whether we can download it from the Market.
2578 if (getPackageManager().resolveActivity(intent, 0) == null) {
2579 String packagename = intent.getPackage();
2580 if (packagename != null) {
2581 intent = new Intent(Intent.ACTION_VIEW, Uri
2582 .parse("market://search?q=pname:" + packagename));
2583 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2584 startActivity(intent);
2585 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002586 } else {
2587 return false;
2588 }
2589 }
2590
Grace Kloba22ac16e2009-10-07 18:00:23 -07002591 // sanitize the Intent, ensuring web pages can not bypass browser
2592 // security (only access to BROWSABLE activities).
2593 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2594 intent.setComponent(null);
2595 try {
2596 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002597 return true;
2598 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002599 } catch (ActivityNotFoundException ex) {
2600 // ignore the error. If no application can handle the URL,
2601 // eg about:blank, assume the browser can handle it.
2602 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603
Grace Kloba22ac16e2009-10-07 18:00:23 -07002604 if (mMenuIsDown) {
2605 openTab(url);
2606 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002607 return true;
2608 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002609 return false;
2610 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 // -------------------------------------------------------------------------
2613 // Helper function for WebChromeClient
2614 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002615
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 void onProgressChanged(WebView view, int newProgress) {
2617 mTitleBar.setProgress(newProgress);
2618 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002619
Grace Kloba22ac16e2009-10-07 18:00:23 -07002620 if (newProgress == 100) {
2621 // onProgressChanged() may continue to be called after the main
2622 // frame has finished loading, as any remaining sub frames continue
2623 // to load. We'll only get called once though with newProgress as
2624 // 100 when everything is loaded. (onPageFinished is called once
2625 // when the main frame completes loading regardless of the state of
2626 // any sub frames so calls to onProgressChanges may continue after
2627 // onPageFinished has executed)
2628 if (mInLoad) {
2629 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002630 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 // If the options menu is open, leave the title bar
2632 if (!mOptionsMenuOpen || !mIconView) {
2633 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002634 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002635 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 } else if (!mInLoad) {
2637 // onPageFinished may have already been called but a subframe is
2638 // still loading and updating the progress. Reset mInLoad and update
2639 // the menu items.
2640 mInLoad = true;
2641 updateInLoadMenuItems();
2642 if (!mOptionsMenuOpen || mIconView) {
2643 // This page has begun to load, so show the title bar
2644 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645 }
2646 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002647 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002648
Grace Kloba22ac16e2009-10-07 18:00:23 -07002649 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002650 // if a view already exists then immediately terminate the new one
2651 if (mCustomView != null) {
2652 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002653 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002654 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002655
2656 // Add the custom view to its container.
2657 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2658 mCustomView = view;
2659 mCustomViewCallback = callback;
2660 // Save the menu state and set it to empty while the custom
2661 // view is showing.
2662 mOldMenuState = mMenuState;
2663 mMenuState = EMPTY_MENU;
2664 // Hide the content view.
2665 mContentView.setVisibility(View.GONE);
2666 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002667 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002668 mCustomViewContainer.setVisibility(View.VISIBLE);
2669 mCustomViewContainer.bringToFront();
2670 }
2671
2672 void onHideCustomView() {
2673 if (mCustomView == null)
2674 return;
2675
2676 // Hide the custom view.
2677 mCustomView.setVisibility(View.GONE);
2678 // Remove the custom view from its container.
2679 mCustomViewContainer.removeView(mCustomView);
2680 mCustomView = null;
2681 // Reset the old menu state.
2682 mMenuState = mOldMenuState;
2683 mOldMenuState = EMPTY_MENU;
2684 mCustomViewContainer.setVisibility(View.GONE);
2685 mCustomViewCallback.onCustomViewHidden();
2686 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002687 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 mContentView.setVisibility(View.VISIBLE);
2689 }
2690
2691 Bitmap getDefaultVideoPoster() {
2692 if (mDefaultVideoPoster == null) {
2693 mDefaultVideoPoster = BitmapFactory.decodeResource(
2694 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002695 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002696 return mDefaultVideoPoster;
2697 }
Patrick Scott3918d442009-08-04 13:22:29 -04002698
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 View getVideoLoadingProgressView() {
2700 if (mVideoProgressView == null) {
2701 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2702 mVideoProgressView = inflater.inflate(
2703 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002704 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 return mVideoProgressView;
2706 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002707
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002708 /*
2709 * The Object used to inform the WebView of the file to upload.
2710 */
2711 private ValueCallback<Uri> mUploadMessage;
2712
Grace Kloba22ac16e2009-10-07 18:00:23 -07002713 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2714 if (mUploadMessage != null) return;
2715 mUploadMessage = uploadMsg;
2716 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2717 i.addCategory(Intent.CATEGORY_OPENABLE);
2718 i.setType("*/*");
2719 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2720 getString(R.string.choose_upload)), FILE_SELECTED);
2721 }
2722
2723 // -------------------------------------------------------------------------
2724 // Implement functions for DownloadListener
2725 // -------------------------------------------------------------------------
2726
The Android Open Source Project0c908882009-03-03 19:32:16 -08002727 /**
2728 * Notify the host application a download should be done, or that
2729 * the data should be streamed if a streaming viewer is available.
2730 * @param url The full url to the content that should be downloaded
2731 * @param contentDisposition Content-disposition http header, if
2732 * present.
2733 * @param mimetype The mimetype of the content reported by the server
2734 * @param contentLength The file size reported by the server
2735 */
2736 public void onDownloadStart(String url, String userAgent,
2737 String contentDisposition, String mimetype, long contentLength) {
2738 // if we're dealing wih A/V content that's not explicitly marked
2739 // for download, check if it's streamable.
2740 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002741 || !contentDisposition.regionMatches(
2742 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002743 // query the package manager to see if there's a registered handler
2744 // that matches.
2745 Intent intent = new Intent(Intent.ACTION_VIEW);
2746 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002747 ResolveInfo info = getPackageManager().resolveActivity(intent,
2748 PackageManager.MATCH_DEFAULT_ONLY);
2749 if (info != null) {
2750 ComponentName myName = getComponentName();
2751 // If we resolved to ourselves, we don't want to attempt to
2752 // load the url only to try and download it again.
2753 if (!myName.getPackageName().equals(
2754 info.activityInfo.packageName)
2755 || !myName.getClassName().equals(
2756 info.activityInfo.name)) {
2757 // someone (other than us) knows how to handle this mime
2758 // type with this scheme, don't download.
2759 try {
2760 startActivity(intent);
2761 return;
2762 } catch (ActivityNotFoundException ex) {
2763 if (LOGD_ENABLED) {
2764 Log.d(LOGTAG, "activity not found for " + mimetype
2765 + " over " + Uri.parse(url).getScheme(),
2766 ex);
2767 }
2768 // Best behavior is to fall back to a download in this
2769 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002770 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002771 }
2772 }
2773 }
2774 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2775 }
2776
2777 /**
2778 * Notify the host application a download should be done, even if there
2779 * is a streaming viewer available for thise type.
2780 * @param url The full url to the content that should be downloaded
2781 * @param contentDisposition Content-disposition http header, if
2782 * present.
2783 * @param mimetype The mimetype of the content reported by the server
2784 * @param contentLength The file size reported by the server
2785 */
2786 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2787 String contentDisposition, String mimetype, long contentLength) {
2788
2789 String filename = URLUtil.guessFileName(url,
2790 contentDisposition, mimetype);
2791
2792 // Check to see if we have an SDCard
2793 String status = Environment.getExternalStorageState();
2794 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2795 int title;
2796 String msg;
2797
2798 // Check to see if the SDCard is busy, same as the music app
2799 if (status.equals(Environment.MEDIA_SHARED)) {
2800 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2801 title = R.string.download_sdcard_busy_dlg_title;
2802 } else {
2803 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2804 title = R.string.download_no_sdcard_dlg_title;
2805 }
2806
2807 new AlertDialog.Builder(this)
2808 .setTitle(title)
2809 .setIcon(android.R.drawable.ic_dialog_alert)
2810 .setMessage(msg)
2811 .setPositiveButton(R.string.ok, null)
2812 .show();
2813 return;
2814 }
2815
2816 // java.net.URI is a lot stricter than KURL so we have to undo
2817 // KURL's percent-encoding and redo the encoding using java.net.URI.
2818 URI uri = null;
2819 try {
2820 // Undo the percent-encoding that KURL may have done.
2821 String newUrl = new String(URLUtil.decode(url.getBytes()));
2822 // Parse the url into pieces
2823 WebAddress w = new WebAddress(newUrl);
2824 String frag = null;
2825 String query = null;
2826 String path = w.mPath;
2827 // Break the path into path, query, and fragment
2828 if (path.length() > 0) {
2829 // Strip the fragment
2830 int idx = path.lastIndexOf('#');
2831 if (idx != -1) {
2832 frag = path.substring(idx + 1);
2833 path = path.substring(0, idx);
2834 }
2835 idx = path.lastIndexOf('?');
2836 if (idx != -1) {
2837 query = path.substring(idx + 1);
2838 path = path.substring(0, idx);
2839 }
2840 }
2841 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2842 query, frag);
2843 } catch (Exception e) {
2844 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2845 return;
2846 }
2847
2848 // XXX: Have to use the old url since the cookies were stored using the
2849 // old percent-encoded url.
2850 String cookies = CookieManager.getInstance().getCookie(url);
2851
2852 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002853 values.put(Downloads.COLUMN_URI, uri.toString());
2854 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2855 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2856 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002857 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002858 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002860 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2861 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2862 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2863 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002864 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07002865 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002866 }
2867 if (mimetype == null) {
2868 // We must have long pressed on a link or image to download it. We
2869 // are not sure of the mimetype in this case, so do a head request
2870 new FetchUrlMimeType(this).execute(values);
2871 } else {
2872 final Uri contentUri =
2873 getContentResolver().insert(Downloads.CONTENT_URI, values);
2874 viewDownloads(contentUri);
2875 }
2876
2877 }
2878
Grace Kloba22ac16e2009-10-07 18:00:23 -07002879 // -------------------------------------------------------------------------
2880
The Android Open Source Project0c908882009-03-03 19:32:16 -08002881 /**
2882 * Resets the lock icon. This method is called when we start a new load and
2883 * know the url to be loaded.
2884 */
2885 private void resetLockIcon(String url) {
2886 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002887 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002888 updateLockIconImage(LOCK_ICON_UNSECURE);
2889 }
2890
The Android Open Source Project0c908882009-03-03 19:32:16 -08002891 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002892 * Update the lock icon to correspond to our latest state.
2893 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002894 private void updateLockIconToLatest() {
2895 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002896 }
2897
2898 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002899 * Updates the lock-icon image in the title-bar.
2900 */
2901 private void updateLockIconImage(int lockIconType) {
2902 Drawable d = null;
2903 if (lockIconType == LOCK_ICON_SECURE) {
2904 d = mSecLockIcon;
2905 } else if (lockIconType == LOCK_ICON_MIXED) {
2906 d = mMixLockIcon;
2907 }
Leon Scroggins68579392009-09-15 15:31:54 -04002908 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002909 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002910 }
2911
2912 /**
2913 * Displays a page-info dialog.
2914 * @param tab The tab to show info about
2915 * @param fromShowSSLCertificateOnError The flag that indicates whether
2916 * this dialog was opened from the SSL-certificate-on-error dialog or
2917 * not. This is important, since we need to know whether to return to
2918 * the parent dialog or simply dismiss.
2919 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002920 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002921 final boolean fromShowSSLCertificateOnError) {
2922 final LayoutInflater factory = LayoutInflater
2923 .from(this);
2924
2925 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2926
2927 final WebView view = tab.getWebView();
2928
2929 String url = null;
2930 String title = null;
2931
2932 if (view == null) {
2933 url = tab.getUrl();
2934 title = tab.getTitle();
2935 } else if (view == mTabControl.getCurrentWebView()) {
2936 // Use the cached title and url if this is the current WebView
2937 url = mUrl;
2938 title = mTitle;
2939 } else {
2940 url = view.getUrl();
2941 title = view.getTitle();
2942 }
2943
2944 if (url == null) {
2945 url = "";
2946 }
2947 if (title == null) {
2948 title = "";
2949 }
2950
2951 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2952 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2953
2954 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05002955 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956
2957 AlertDialog.Builder alertDialogBuilder =
2958 new AlertDialog.Builder(this)
2959 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2960 .setView(pageInfoView)
2961 .setPositiveButton(
2962 R.string.ok,
2963 new DialogInterface.OnClickListener() {
2964 public void onClick(DialogInterface dialog,
2965 int whichButton) {
2966 mPageInfoDialog = null;
2967 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002968
2969 // if we came here from the SSL error dialog
2970 if (fromShowSSLCertificateOnError) {
2971 // go back to the SSL error dialog
2972 showSSLCertificateOnError(
2973 mSSLCertificateOnErrorView,
2974 mSSLCertificateOnErrorHandler,
2975 mSSLCertificateOnErrorError);
2976 }
2977 }
2978 })
2979 .setOnCancelListener(
2980 new DialogInterface.OnCancelListener() {
2981 public void onCancel(DialogInterface dialog) {
2982 mPageInfoDialog = null;
2983 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002984
2985 // if we came here from the SSL error dialog
2986 if (fromShowSSLCertificateOnError) {
2987 // go back to the SSL error dialog
2988 showSSLCertificateOnError(
2989 mSSLCertificateOnErrorView,
2990 mSSLCertificateOnErrorHandler,
2991 mSSLCertificateOnErrorError);
2992 }
2993 }
2994 });
2995
2996 // if we have a main top-level page SSL certificate set or a certificate
2997 // error
2998 if (fromShowSSLCertificateOnError ||
2999 (view != null && view.getCertificate() != null)) {
3000 // add a 'View Certificate' button
3001 alertDialogBuilder.setNeutralButton(
3002 R.string.view_certificate,
3003 new DialogInterface.OnClickListener() {
3004 public void onClick(DialogInterface dialog,
3005 int whichButton) {
3006 mPageInfoDialog = null;
3007 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003008
3009 // if we came here from the SSL error dialog
3010 if (fromShowSSLCertificateOnError) {
3011 // go back to the SSL error dialog
3012 showSSLCertificateOnError(
3013 mSSLCertificateOnErrorView,
3014 mSSLCertificateOnErrorHandler,
3015 mSSLCertificateOnErrorError);
3016 } else {
3017 // otherwise, display the top-most certificate from
3018 // the chain
3019 if (view.getCertificate() != null) {
3020 showSSLCertificate(tab);
3021 }
3022 }
3023 }
3024 });
3025 }
3026
3027 mPageInfoDialog = alertDialogBuilder.show();
3028 }
3029
3030 /**
3031 * Displays the main top-level page SSL certificate dialog
3032 * (accessible from the Page-Info dialog).
3033 * @param tab The tab to show certificate for.
3034 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003035 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003036 final View certificateView =
3037 inflateCertificateView(tab.getWebView().getCertificate());
3038 if (certificateView == null) {
3039 return;
3040 }
3041
3042 LayoutInflater factory = LayoutInflater.from(this);
3043
3044 final LinearLayout placeholder =
3045 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3046
3047 LinearLayout ll = (LinearLayout) factory.inflate(
3048 R.layout.ssl_success, placeholder);
3049 ((TextView)ll.findViewById(R.id.success))
3050 .setText(R.string.ssl_certificate_is_valid);
3051
3052 mSSLCertificateView = tab;
3053 mSSLCertificateDialog =
3054 new AlertDialog.Builder(this)
3055 .setTitle(R.string.ssl_certificate).setIcon(
3056 R.drawable.ic_dialog_browser_certificate_secure)
3057 .setView(certificateView)
3058 .setPositiveButton(R.string.ok,
3059 new DialogInterface.OnClickListener() {
3060 public void onClick(DialogInterface dialog,
3061 int whichButton) {
3062 mSSLCertificateDialog = null;
3063 mSSLCertificateView = null;
3064
3065 showPageInfo(tab, false);
3066 }
3067 })
3068 .setOnCancelListener(
3069 new DialogInterface.OnCancelListener() {
3070 public void onCancel(DialogInterface dialog) {
3071 mSSLCertificateDialog = null;
3072 mSSLCertificateView = null;
3073
3074 showPageInfo(tab, false);
3075 }
3076 })
3077 .show();
3078 }
3079
3080 /**
3081 * Displays the SSL error certificate dialog.
3082 * @param view The target web-view.
3083 * @param handler The SSL error handler responsible for cancelling the
3084 * connection that resulted in an SSL error or proceeding per user request.
3085 * @param error The SSL error object.
3086 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003087 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088 final WebView view, final SslErrorHandler handler, final SslError error) {
3089
3090 final View certificateView =
3091 inflateCertificateView(error.getCertificate());
3092 if (certificateView == null) {
3093 return;
3094 }
3095
3096 LayoutInflater factory = LayoutInflater.from(this);
3097
3098 final LinearLayout placeholder =
3099 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3100
3101 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3102 LinearLayout ll = (LinearLayout)factory
3103 .inflate(R.layout.ssl_warning, placeholder);
3104 ((TextView)ll.findViewById(R.id.warning))
3105 .setText(R.string.ssl_untrusted);
3106 }
3107
3108 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3109 LinearLayout ll = (LinearLayout)factory
3110 .inflate(R.layout.ssl_warning, placeholder);
3111 ((TextView)ll.findViewById(R.id.warning))
3112 .setText(R.string.ssl_mismatch);
3113 }
3114
3115 if (error.hasError(SslError.SSL_EXPIRED)) {
3116 LinearLayout ll = (LinearLayout)factory
3117 .inflate(R.layout.ssl_warning, placeholder);
3118 ((TextView)ll.findViewById(R.id.warning))
3119 .setText(R.string.ssl_expired);
3120 }
3121
3122 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3123 LinearLayout ll = (LinearLayout)factory
3124 .inflate(R.layout.ssl_warning, placeholder);
3125 ((TextView)ll.findViewById(R.id.warning))
3126 .setText(R.string.ssl_not_yet_valid);
3127 }
3128
3129 mSSLCertificateOnErrorHandler = handler;
3130 mSSLCertificateOnErrorView = view;
3131 mSSLCertificateOnErrorError = error;
3132 mSSLCertificateOnErrorDialog =
3133 new AlertDialog.Builder(this)
3134 .setTitle(R.string.ssl_certificate).setIcon(
3135 R.drawable.ic_dialog_browser_certificate_partially_secure)
3136 .setView(certificateView)
3137 .setPositiveButton(R.string.ok,
3138 new DialogInterface.OnClickListener() {
3139 public void onClick(DialogInterface dialog,
3140 int whichButton) {
3141 mSSLCertificateOnErrorDialog = null;
3142 mSSLCertificateOnErrorView = null;
3143 mSSLCertificateOnErrorHandler = null;
3144 mSSLCertificateOnErrorError = null;
3145
Grace Kloba22ac16e2009-10-07 18:00:23 -07003146 view.getWebViewClient().onReceivedSslError(
3147 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003148 }
3149 })
3150 .setNeutralButton(R.string.page_info_view,
3151 new DialogInterface.OnClickListener() {
3152 public void onClick(DialogInterface dialog,
3153 int whichButton) {
3154 mSSLCertificateOnErrorDialog = null;
3155
3156 // do not clear the dialog state: we will
3157 // need to show the dialog again once the
3158 // user is done exploring the page-info details
3159
3160 showPageInfo(mTabControl.getTabFromView(view),
3161 true);
3162 }
3163 })
3164 .setOnCancelListener(
3165 new DialogInterface.OnCancelListener() {
3166 public void onCancel(DialogInterface dialog) {
3167 mSSLCertificateOnErrorDialog = null;
3168 mSSLCertificateOnErrorView = null;
3169 mSSLCertificateOnErrorHandler = null;
3170 mSSLCertificateOnErrorError = null;
3171
Grace Kloba22ac16e2009-10-07 18:00:23 -07003172 view.getWebViewClient().onReceivedSslError(
3173 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003174 }
3175 })
3176 .show();
3177 }
3178
3179 /**
3180 * Inflates the SSL certificate view (helper method).
3181 * @param certificate The SSL certificate.
3182 * @return The resultant certificate view with issued-to, issued-by,
3183 * issued-on, expires-on, and possibly other fields set.
3184 * If the input certificate is null, returns null.
3185 */
3186 private View inflateCertificateView(SslCertificate certificate) {
3187 if (certificate == null) {
3188 return null;
3189 }
3190
3191 LayoutInflater factory = LayoutInflater.from(this);
3192
3193 View certificateView = factory.inflate(
3194 R.layout.ssl_certificate, null);
3195
3196 // issued to:
3197 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3198 if (issuedTo != null) {
3199 ((TextView) certificateView.findViewById(R.id.to_common))
3200 .setText(issuedTo.getCName());
3201 ((TextView) certificateView.findViewById(R.id.to_org))
3202 .setText(issuedTo.getOName());
3203 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3204 .setText(issuedTo.getUName());
3205 }
3206
3207 // issued by:
3208 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3209 if (issuedBy != null) {
3210 ((TextView) certificateView.findViewById(R.id.by_common))
3211 .setText(issuedBy.getCName());
3212 ((TextView) certificateView.findViewById(R.id.by_org))
3213 .setText(issuedBy.getOName());
3214 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3215 .setText(issuedBy.getUName());
3216 }
3217
3218 // issued on:
3219 String issuedOn = reformatCertificateDate(
3220 certificate.getValidNotBefore());
3221 ((TextView) certificateView.findViewById(R.id.issued_on))
3222 .setText(issuedOn);
3223
3224 // expires on:
3225 String expiresOn = reformatCertificateDate(
3226 certificate.getValidNotAfter());
3227 ((TextView) certificateView.findViewById(R.id.expires_on))
3228 .setText(expiresOn);
3229
3230 return certificateView;
3231 }
3232
3233 /**
3234 * Re-formats the certificate date (Date.toString()) string to
3235 * a properly localized date string.
3236 * @return Properly localized version of the certificate date string and
3237 * the original certificate date string if fails to localize.
3238 * If the original string is null, returns an empty string "".
3239 */
3240 private String reformatCertificateDate(String certificateDate) {
3241 String reformattedDate = null;
3242
3243 if (certificateDate != null) {
3244 Date date = null;
3245 try {
3246 date = java.text.DateFormat.getInstance().parse(certificateDate);
3247 } catch (ParseException e) {
3248 date = null;
3249 }
3250
3251 if (date != null) {
3252 reformattedDate =
3253 DateFormat.getDateFormat(this).format(date);
3254 }
3255 }
3256
3257 return reformattedDate != null ? reformattedDate :
3258 (certificateDate != null ? certificateDate : "");
3259 }
3260
3261 /**
3262 * Displays an http-authentication dialog.
3263 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003264 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003265 final String host, final String realm, final String title,
3266 final String name, final String password, int focusId) {
3267 LayoutInflater factory = LayoutInflater.from(this);
3268 final View v = factory
3269 .inflate(R.layout.http_authentication, null);
3270 if (name != null) {
3271 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3272 }
3273 if (password != null) {
3274 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3275 }
3276
3277 String titleText = title;
3278 if (titleText == null) {
3279 titleText = getText(R.string.sign_in_to).toString().replace(
3280 "%s1", host).replace("%s2", realm);
3281 }
3282
3283 mHttpAuthHandler = handler;
3284 AlertDialog dialog = new AlertDialog.Builder(this)
3285 .setTitle(titleText)
3286 .setIcon(android.R.drawable.ic_dialog_alert)
3287 .setView(v)
3288 .setPositiveButton(R.string.action,
3289 new DialogInterface.OnClickListener() {
3290 public void onClick(DialogInterface dialog,
3291 int whichButton) {
3292 String nm = ((EditText) v
3293 .findViewById(R.id.username_edit))
3294 .getText().toString();
3295 String pw = ((EditText) v
3296 .findViewById(R.id.password_edit))
3297 .getText().toString();
3298 BrowserActivity.this.setHttpAuthUsernamePassword
3299 (host, realm, nm, pw);
3300 handler.proceed(nm, pw);
3301 mHttpAuthenticationDialog = null;
3302 mHttpAuthHandler = null;
3303 }})
3304 .setNegativeButton(R.string.cancel,
3305 new DialogInterface.OnClickListener() {
3306 public void onClick(DialogInterface dialog,
3307 int whichButton) {
3308 handler.cancel();
3309 BrowserActivity.this.resetTitleAndRevertLockIcon();
3310 mHttpAuthenticationDialog = null;
3311 mHttpAuthHandler = null;
3312 }})
3313 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3314 public void onCancel(DialogInterface dialog) {
3315 handler.cancel();
3316 BrowserActivity.this.resetTitleAndRevertLockIcon();
3317 mHttpAuthenticationDialog = null;
3318 mHttpAuthHandler = null;
3319 }})
3320 .create();
3321 // Make the IME appear when the dialog is displayed if applicable.
3322 dialog.getWindow().setSoftInputMode(
3323 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3324 dialog.show();
3325 if (focusId != 0) {
3326 dialog.findViewById(focusId).requestFocus();
3327 } else {
3328 v.findViewById(R.id.username_edit).requestFocus();
3329 }
3330 mHttpAuthenticationDialog = dialog;
3331 }
3332
3333 public int getProgress() {
3334 WebView w = mTabControl.getCurrentWebView();
3335 if (w != null) {
3336 return w.getProgress();
3337 } else {
3338 return 100;
3339 }
3340 }
3341
3342 /**
3343 * Set HTTP authentication password.
3344 *
3345 * @param host The host for the password
3346 * @param realm The realm for the password
3347 * @param username The username for the password. If it is null, it means
3348 * password can't be saved.
3349 * @param password The password
3350 */
3351 public void setHttpAuthUsernamePassword(String host, String realm,
3352 String username,
3353 String password) {
3354 WebView w = mTabControl.getCurrentWebView();
3355 if (w != null) {
3356 w.setHttpAuthUsernamePassword(host, realm, username, password);
3357 }
3358 }
3359
3360 /**
3361 * connectivity manager says net has come or gone... inform the user
3362 * @param up true if net has come up, false if net has gone down
3363 */
3364 public void onNetworkToggle(boolean up) {
3365 if (up == mIsNetworkUp) {
3366 return;
3367 } else if (up) {
3368 mIsNetworkUp = true;
3369 if (mAlertDialog != null) {
3370 mAlertDialog.cancel();
3371 mAlertDialog = null;
3372 }
3373 } else {
3374 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003375 if (mInLoad) {
3376 createAndShowNetworkDialog();
3377 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003378 }
3379 WebView w = mTabControl.getCurrentWebView();
3380 if (w != null) {
3381 w.setNetworkAvailable(up);
3382 }
3383 }
3384
Grace Kloba22ac16e2009-10-07 18:00:23 -07003385 boolean isNetworkUp() {
3386 return mIsNetworkUp;
3387 }
3388
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003389 // This method shows the network dialog alerting the user that the net is
3390 // down. It will only show the dialog if mAlertDialog is null.
3391 private void createAndShowNetworkDialog() {
3392 if (mAlertDialog == null) {
3393 mAlertDialog = new AlertDialog.Builder(this)
3394 .setTitle(R.string.loadSuspendedTitle)
3395 .setMessage(R.string.loadSuspended)
3396 .setPositiveButton(R.string.ok, null)
3397 .show();
3398 }
3399 }
3400
The Android Open Source Project0c908882009-03-03 19:32:16 -08003401 @Override
3402 protected void onActivityResult(int requestCode, int resultCode,
3403 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003404 if (getTopWindow() == null) return;
3405
The Android Open Source Project0c908882009-03-03 19:32:16 -08003406 switch (requestCode) {
3407 case COMBO_PAGE:
3408 if (resultCode == RESULT_OK && intent != null) {
3409 String data = intent.getAction();
3410 Bundle extras = intent.getExtras();
3411 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003412 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003413 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003414 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003415 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003416 dismissSubWindow(currentTab);
3417 if (data != null && data.length() != 0) {
3418 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003419 }
3420 }
3421 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003422 // Deliberately fall through to PREFERENCES_PAGE, since the
3423 // same extra may be attached to the COMBO_PAGE
3424 case PREFERENCES_PAGE:
3425 if (resultCode == RESULT_OK && intent != null) {
3426 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3427 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3428 mTabControl.removeParentChildRelationShips();
3429 }
3430 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003431 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003432 // Choose a file from the file picker.
3433 case FILE_SELECTED:
3434 if (null == mUploadMessage) break;
3435 Uri result = intent == null || resultCode != RESULT_OK ? null
3436 : intent.getData();
3437 mUploadMessage.onReceiveValue(result);
3438 mUploadMessage = null;
3439 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003440 default:
3441 break;
3442 }
Leon Scroggins30444232009-09-04 18:36:20 -04003443 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003444 }
3445
3446 /*
3447 * This method is called as a result of the user selecting the options
3448 * menu to see the download window, or when a download changes state. It
3449 * shows the download window ontop of the current window.
3450 */
3451 /* package */ void viewDownloads(Uri downloadRecord) {
3452 Intent intent = new Intent(this,
3453 BrowserDownloadPage.class);
3454 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003455 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003456
3457 }
3458
Leon Scroggins160a7e72009-08-14 18:28:01 -04003459 /**
3460 * Open the Go page.
3461 * @param startWithHistory If true, open starting on the history tab.
3462 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003463 */
Leon Scroggins30444232009-09-04 18:36:20 -04003464 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003465 WebView current = mTabControl.getCurrentWebView();
3466 if (current == null) {
3467 return;
3468 }
3469 Intent intent = new Intent(this,
3470 CombinedBookmarkHistoryActivity.class);
3471 String title = current.getTitle();
3472 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003473 Bitmap thumbnail = createScreenshot(current);
3474
The Android Open Source Project0c908882009-03-03 19:32:16 -08003475 // Just in case the user opens bookmarks before a page finishes loading
3476 // so the current history item, and therefore the page, is null.
3477 if (null == url) {
3478 url = mLastEnteredUrl;
3479 // This can happen.
3480 if (null == url) {
3481 url = mSettings.getHomePage();
3482 }
3483 }
3484 // In case the web page has not yet received its associated title.
3485 if (title == null) {
3486 title = url;
3487 }
3488 intent.putExtra("title", title);
3489 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003490 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003491 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003492 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003493 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003494 if (startWithHistory) {
3495 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3496 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3497 }
3498 startActivityForResult(intent, COMBO_PAGE);
3499 }
3500
3501 // Called when loading from context menu or LOAD_URL message
3502 private void loadURL(WebView view, String url) {
3503 // In case the user enters nothing.
3504 if (url != null && url.length() != 0 && view != null) {
3505 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003506 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003507 view.loadUrl(url);
3508 }
3509 }
3510 }
3511
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512 private String smartUrlFilter(Uri inUri) {
3513 if (inUri != null) {
3514 return smartUrlFilter(inUri.toString());
3515 }
3516 return null;
3517 }
3518
Feng Qianb34f87a2009-03-24 21:27:26 -07003519 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 "(?i)" + // switch on case insensitive matching
3521 "(" + // begin group for schema
3522 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003523 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003524 ")" +
3525 "(.*)" );
3526
3527 /**
3528 * Attempts to determine whether user input is a URL or search
3529 * terms. Anything with a space is passed to search.
3530 *
3531 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3532 * "Http://" converts to "http://"
3533 *
3534 * @return Original or modified URL
3535 *
3536 */
3537 String smartUrlFilter(String url) {
3538
3539 String inUrl = url.trim();
3540 boolean hasSpace = inUrl.indexOf(' ') != -1;
3541
3542 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3543 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003544 // force scheme to lowercase
3545 String scheme = matcher.group(1);
3546 String lcScheme = scheme.toLowerCase();
3547 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003548 inUrl = lcScheme + matcher.group(2);
3549 }
3550 if (hasSpace) {
3551 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003552 }
3553 return inUrl;
3554 }
3555 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003556 // FIXME: Is this the correct place to add to searches?
3557 // what if someone else calls this function?
3558 int shortcut = parseUrlShortcut(inUrl);
3559 if (shortcut != SHORTCUT_INVALID) {
3560 Browser.addSearchUrl(mResolver, inUrl);
3561 String query = inUrl.substring(2);
3562 switch (shortcut) {
3563 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003564 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003565 case SHORTCUT_WIKIPEDIA_SEARCH:
3566 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3567 case SHORTCUT_DICTIONARY_SEARCH:
3568 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3569 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003570 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003571 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003572 }
3573 }
3574 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003575 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003576 return URLUtil.guessUrl(inUrl);
3577 }
3578 }
3579
3580 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003581 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003582 }
3583
Ben Murdochbff2d602009-07-01 20:19:05 +01003584 /* package */ void setShouldShowErrorConsole(boolean flag) {
3585 if (flag == mShouldShowErrorConsole) {
3586 // Nothing to do.
3587 return;
3588 }
3589
3590 mShouldShowErrorConsole = flag;
3591
Grace Kloba22ac16e2009-10-07 18:00:23 -07003592 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3593 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003594
3595 if (flag) {
3596 // Setting the show state of the console will cause it's the layout to be inflated.
3597 if (errorConsole.numberOfErrors() > 0) {
3598 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3599 } else {
3600 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3601 }
3602
3603 // Now we can add it to the main view.
3604 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003605 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003606 ViewGroup.LayoutParams.WRAP_CONTENT));
3607 } else {
3608 mErrorConsoleContainer.removeView(errorConsole);
3609 }
3610
3611 }
3612
Grace Kloba22ac16e2009-10-07 18:00:23 -07003613 boolean shouldShowErrorConsole() {
3614 return mShouldShowErrorConsole;
3615 }
3616
Andrei Popescu163ab742009-10-20 17:58:23 +01003617 private void setStatusBarVisibility(boolean visible) {
3618 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3619 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3620 }
3621
Grace Klobaeb6eef42009-09-15 17:56:32 -07003622 final static int LOCK_ICON_UNSECURE = 0;
3623 final static int LOCK_ICON_SECURE = 1;
3624 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625
The Android Open Source Project0c908882009-03-03 19:32:16 -08003626 private BrowserSettings mSettings;
3627 private TabControl mTabControl;
3628 private ContentResolver mResolver;
3629 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003630 private View mCustomView;
3631 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003632 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633
3634 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3635 // view, we should rewrite this.
3636 private int mCurrentMenuState = 0;
3637 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003638 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003639 private static final int EMPTY_MENU = -1;
3640 private Menu mMenu;
3641
3642 private FindDialog mFindDialog;
3643 // Used to prevent chording to result in firing two shortcuts immediately
3644 // one after another. Fixes bug 1211714.
3645 boolean mCanChord;
3646
3647 private boolean mInLoad;
3648 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003649 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003650
The Android Open Source Project0c908882009-03-03 19:32:16 -08003651 private boolean mActivityInPause = true;
3652
3653 private boolean mMenuIsDown;
3654
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 private static boolean mInTrace;
3656
3657 // Performance probe
3658 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3659 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3660 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3661 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3662 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3663 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3664 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3665 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3666 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3667 };
3668
3669 private long mStart;
3670 private long mProcessStart;
3671 private long mUserStart;
3672 private long mSystemStart;
3673 private long mIdleStart;
3674 private long mIrqStart;
3675
3676 private long mUiStart;
3677
3678 private Drawable mMixLockIcon;
3679 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680
3681 /* hold a ref so we can auto-cancel if necessary */
3682 private AlertDialog mAlertDialog;
3683
3684 // Wait for credentials before loading google.com
3685 private ProgressDialog mCredsDlg;
3686
3687 // The up-to-date URL and title (these can be different from those stored
3688 // in WebView, since it takes some time for the information in WebView to
3689 // get updated)
3690 private String mUrl;
3691 private String mTitle;
3692
3693 // As PageInfo has different style for landscape / portrait, we have
3694 // to re-open it when configuration changed
3695 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003696 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003697 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3698 // dialog, we should not just dismiss it, but should get back to the
3699 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003700 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003701
3702 // as SSLCertificateOnError has different style for landscape / portrait,
3703 // we have to re-open it when configuration changed
3704 private AlertDialog mSSLCertificateOnErrorDialog;
3705 private WebView mSSLCertificateOnErrorView;
3706 private SslErrorHandler mSSLCertificateOnErrorHandler;
3707 private SslError mSSLCertificateOnErrorError;
3708
3709 // as SSLCertificate has different style for landscape / portrait, we
3710 // have to re-open it when configuration changed
3711 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003712 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003713
3714 // as HttpAuthentication has different style for landscape / portrait, we
3715 // have to re-open it when configuration changed
3716 private AlertDialog mHttpAuthenticationDialog;
3717 private HttpAuthHandler mHttpAuthHandler;
3718
3719 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3720 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003721 ViewGroup.LayoutParams.MATCH_PARENT,
3722 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003723 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3724 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003725 ViewGroup.LayoutParams.MATCH_PARENT,
3726 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003727 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003728 // Google search
3729 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730 // Wikipedia search
3731 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3732 // Dictionary search
3733 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3734 // Google Mobile Local search
3735 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3736
3737 final static String QUERY_PLACE_HOLDER = "%s";
3738
3739 // "source" parameter for Google search through search key
3740 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3741 // "source" parameter for Google search through goto menu
3742 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3743 // "source" parameter for Google search through simplily type
3744 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3745 // "source" parameter for Google search suggested by the browser
3746 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3747 // "source" parameter for Google search from unknown source
3748 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3749
3750 private final static String LOGTAG = "browser";
3751
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 private String mLastEnteredUrl;
3753
3754 private PowerManager.WakeLock mWakeLock;
3755 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3756
3757 private Toast mStopToast;
3758
Leon Scroggins68579392009-09-15 15:31:54 -04003759 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003760
Ben Murdochbff2d602009-07-01 20:19:05 +01003761 private LinearLayout mErrorConsoleContainer = null;
3762 private boolean mShouldShowErrorConsole = false;
3763
The Android Open Source Project0c908882009-03-03 19:32:16 -08003764 // As the ids are dynamically created, we can't guarantee that they will
3765 // be in sequence, so this static array maps ids to a window number.
3766 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3767 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3768 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3769 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3770
3771 // monitor platform changes
3772 private IntentFilter mNetworkStateChangedFilter;
3773 private BroadcastReceiver mNetworkStateIntentReceiver;
3774
Grace Klobab4da0ad2009-05-14 14:45:40 -07003775 private BroadcastReceiver mPackageInstallationReceiver;
3776
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003778 final static int COMBO_PAGE = 1;
3779 final static int DOWNLOAD_PAGE = 2;
3780 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003781 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003782
Andrei Popescu540035d2009-09-18 18:59:20 +01003783 // the default <video> poster
3784 private Bitmap mDefaultVideoPoster;
3785 // the video progress view
3786 private View mVideoProgressView;
3787
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003788 /**
3789 * A UrlData class to abstract how the content will be set to WebView.
3790 * This base class uses loadUrl to show the content.
3791 */
3792 private static class UrlData {
3793 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003794 byte[] mPostData;
3795
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003796 UrlData(String url) {
3797 this.mUrl = url;
3798 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003799
3800 void setPostData(byte[] postData) {
3801 mPostData = postData;
3802 }
3803
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003804 boolean isEmpty() {
3805 return mUrl == null || mUrl.length() == 0;
3806 }
3807
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003808 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003809 if (mPostData != null) {
3810 webView.postUrl(mUrl, mPostData);
3811 } else {
3812 webView.loadUrl(mUrl);
3813 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003814 }
3815 };
3816
3817 /**
3818 * A subclass of UrlData class that can display inlined content using
3819 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3820 */
3821 private static class InlinedUrlData extends UrlData {
3822 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3823 super(failUrl);
3824 mInlined = inlined;
3825 mMimeType = mimeType;
3826 mEncoding = encoding;
3827 }
3828 String mMimeType;
3829 String mInlined;
3830 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003831 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003832 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003833 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003834 }
3835
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003836 @Override
3837 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003838 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3839 }
3840 }
3841
Leon Scroggins1f005d32009-08-10 17:36:42 -04003842 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843}