blob: 92e1968194aa1fe7276af512be09b20754298d9a [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;
Leon Scroggins96afcb12009-12-10 12:35:56 -050039import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080040import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010041import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080043import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040044import android.graphics.PixelFormat;
45import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080046import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080047import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000048import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.Uri;
50import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.http.SslCertificate;
52import android.net.http.SslError;
53import android.os.AsyncTask;
54import android.os.Bundle;
55import android.os.Debug;
56import android.os.Environment;
57import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080058import android.os.Message;
59import android.os.PowerManager;
60import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080061import android.os.ServiceManager;
62import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040064import android.provider.ContactsContract;
65import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080066import android.provider.Downloads;
67import android.provider.MediaStore;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.text.IClipboard;
69import android.text.TextUtils;
70import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040071import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080072import android.util.Log;
73import android.view.ContextMenu;
74import android.view.Gravity;
75import android.view.KeyEvent;
76import android.view.LayoutInflater;
77import android.view.Menu;
78import android.view.MenuInflater;
79import android.view.MenuItem;
80import android.view.View;
81import android.view.ViewGroup;
82import android.view.Window;
83import android.view.WindowManager;
84import android.view.ContextMenu.ContextMenuInfo;
85import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080086import android.webkit.CookieManager;
87import android.webkit.CookieSyncManager;
88import android.webkit.DownloadListener;
89import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070090import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080091import android.webkit.SslErrorHandler;
92import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010093import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080094import android.webkit.WebChromeClient;
95import android.webkit.WebHistoryItem;
96import android.webkit.WebIconDatabase;
97import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.widget.EditText;
99import android.widget.FrameLayout;
100import android.widget.LinearLayout;
101import android.widget.TextView;
102import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800103import android.accounts.Account;
104import android.accounts.AccountManager;
105import android.accounts.AccountManagerFuture;
106import android.accounts.AuthenticatorException;
107import android.accounts.OperationCanceledException;
108import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800109
Dan Egnor5ee906c2009-11-18 12:11:49 -0800110import com.android.common.Patterns;
111
Dan Egnor5ee906c2009-11-18 12:11:49 -0800112import com.google.android.googlelogin.GoogleLoginServiceConstants;
113
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400114import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800115import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000116import java.io.IOException;
117import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800118import java.net.MalformedURLException;
119import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700120import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800121import java.net.URL;
122import java.net.URLEncoder;
123import java.text.ParseException;
124import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.util.HashMap;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800126import java.util.regex.Matcher;
127import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800128
129public class BrowserActivity extends Activity
Fred Quintana752b6562009-12-18 10:18:26 -0800130 implements View.OnCreateContextMenuListener, DownloadListener,
131 AccountManagerCallback<Account[]> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800132
Dave Bort31a6d1c2009-04-13 15:56:49 -0700133 /* Define some aliases to make these debugging flags easier to refer to.
134 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
135 */
136 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
137 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
138 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
139
Satish Sampath565505b2009-05-29 15:37:27 +0100140 // These are single-character shortcuts for searching popular sources.
141 private static final int SHORTCUT_INVALID = 0;
142 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
143 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
144 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
145 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
146
Fred Quintana752b6562009-12-18 10:18:26 -0800147 private Account[] mAccountsGoogle;
148 private Account[] mAccountsPreferHosted;
149
150 private void startReadOfGoogleAccounts() {
151 mAccountsGoogle = null;
152 mAccountsPreferHosted = null;
153
154 AccountManager.get(this).getAccountsByTypeAndFeatures(
155 GoogleLoginServiceConstants.ACCOUNT_TYPE,
156 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
157 this, null);
158 }
159
160 /** This implements AccountManagerCallback<Account[]> */
161 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
162 try {
163 if (mAccountsGoogle == null) {
164 mAccountsGoogle = accountManagerFuture.getResult();
165
166 AccountManager.get(this).getAccountsByTypeAndFeatures(
167 GoogleLoginServiceConstants.ACCOUNT_TYPE,
168 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
169 this, null);
170 } else {
171 mAccountsPreferHosted = accountManagerFuture.getResult();
172 setupHomePage();
173 }
174 } catch (OperationCanceledException e) {
175 setupHomePage();
176 } catch (IOException e) {
177 setupHomePage();
178 } catch (AuthenticatorException e) {
179 setupHomePage();
180 }
181 }
182
The Android Open Source Project0c908882009-03-03 19:32:16 -0800183 private void setupHomePage() {
Fred Quintana752b6562009-12-18 10:18:26 -0800184 // get the default home page
185 String homepage = mSettings.getHomePage();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800186
Fred Quintana752b6562009-12-18 10:18:26 -0800187 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
188 // three cases:
189 //
190 // hostedUser == googleUser
191 // The device has only a google account
192 //
193 // hostedUser != googleUser
194 // The device has a hosted account and a google account
195 //
196 // hostedUser != null, googleUser == null
197 // The device has only a hosted account (so far)
198 String hostedUser = mAccountsPreferHosted.length == 0
199 ? null
200 : mAccountsPreferHosted[0].name;
201 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800202
Fred Quintana752b6562009-12-18 10:18:26 -0800203 // developers might have no accounts at all
204 if (hostedUser == null) return;
Grace Klobaf2c5c1b2009-05-26 10:48:31 -0700205
Fred Quintana752b6562009-12-18 10:18:26 -0800206 if (googleUser == null || !hostedUser.equals(googleUser)) {
207 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
208 homepage = homepage.replace("?", "/a/" + domain + "?");
The Android Open Source Project0c908882009-03-03 19:32:16 -0800209 }
Fred Quintana752b6562009-12-18 10:18:26 -0800210 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800211
Fred Quintana752b6562009-12-18 10:18:26 -0800212 mSettings.setHomePage(BrowserActivity.this, homepage);
213 resumeAfterCredentials();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800214 }
215
Cary Clarka9771242009-08-11 16:42:26 -0400216 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800217 @Override
218 public Void doInBackground(File... files) {
219 if (files != null) {
220 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400221 if (!f.delete()) {
222 Log.e(LOGTAG, f.getPath() + " was not deleted");
223 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800224 }
225 }
226 return null;
227 }
228 }
229
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400230 /**
231 * This layout holds everything you see below the status bar, including the
232 * error console, the custom view container, and the webviews.
233 */
234 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400235
Grace Kloba22ac16e2009-10-07 18:00:23 -0700236 @Override
237 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700238 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800239 Log.v(LOGTAG, this + " onStart");
240 }
241 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800242 // test the browser in OpenGL
243 // requestWindowFeature(Window.FEATURE_OPENGL);
244
245 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
246
247 mResolver = getContentResolver();
248
Grace Kloba0923d692009-09-23 21:37:25 -0700249 // If this was a web search request, pass it on to the default web
250 // search provider and finish this activity.
251 if (handleWebSearchIntent(getIntent())) {
252 finish();
253 return;
254 }
255
The Android Open Source Project0c908882009-03-03 19:32:16 -0800256 mSecLockIcon = Resources.getSystem().getDrawable(
257 android.R.drawable.ic_secure);
258 mMixLockIcon = Resources.getSystem().getDrawable(
259 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800260
Leon Scroggins81db3662009-06-04 17:45:11 -0400261 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
262 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400263 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
264 .inflate(R.layout.custom_screen, null);
265 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
266 R.id.main_content);
267 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
268 .findViewById(R.id.error_console);
269 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
270 .findViewById(R.id.fullscreen_custom_content);
271 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400272 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400273 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800274
275 // Create the tab control and our initial tab
276 mTabControl = new TabControl(this);
277
278 // Open the icon database and retain all the bookmark urls for favicons
279 retainIconsOnStartup();
280
281 // Keep a settings instance handy.
282 mSettings = BrowserSettings.getInstance();
283 mSettings.setTabControl(mTabControl);
284 mSettings.loadFromDb(this);
285
286 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
287 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
288
Grace Klobaa34f6862009-07-31 16:28:17 -0700289 /* enables registration for changes in network status from
290 http stack */
291 mNetworkStateChangedFilter = new IntentFilter();
292 mNetworkStateChangedFilter.addAction(
293 ConnectivityManager.CONNECTIVITY_ACTION);
294 mNetworkStateIntentReceiver = new BroadcastReceiver() {
295 @Override
296 public void onReceive(Context context, Intent intent) {
297 if (intent.getAction().equals(
298 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700299 boolean noConnectivity = intent.getBooleanExtra(
300 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000301 if (!noConnectivity) {
302 NetworkInfo info = intent.getParcelableExtra(
303 ConnectivityManager.EXTRA_NETWORK_INFO);
304 String typeName = info.getTypeName();
305 String subtypeName = info.getSubtypeName();
306 sendNetworkType(typeName.toLowerCase(),
307 (subtypeName != null ? subtypeName.toLowerCase() : ""));
308 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700309 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700310 }
311 }
312 };
313
Grace Kloba615c6c92009-08-03 10:22:44 -0700314 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
315 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
316 filter.addDataScheme("package");
317 mPackageInstallationReceiver = new BroadcastReceiver() {
318 @Override
319 public void onReceive(Context context, Intent intent) {
320 final String action = intent.getAction();
321 final String packageName = intent.getData()
322 .getSchemeSpecificPart();
323 final boolean replacing = intent.getBooleanExtra(
324 Intent.EXTRA_REPLACING, false);
325 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
326 // if it is replacing, refreshPlugins() when adding
327 return;
328 }
329 PackageManager pm = BrowserActivity.this.getPackageManager();
330 PackageInfo pkgInfo = null;
331 try {
332 pkgInfo = pm.getPackageInfo(packageName,
333 PackageManager.GET_PERMISSIONS);
334 } catch (PackageManager.NameNotFoundException e) {
335 return;
336 }
337 if (pkgInfo != null) {
338 String permissions[] = pkgInfo.requestedPermissions;
339 if (permissions == null) {
340 return;
341 }
342 boolean permissionOk = false;
343 for (String permit : permissions) {
344 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
345 permissionOk = true;
346 break;
347 }
348 }
349 if (permissionOk) {
350 PluginManager.getInstance(BrowserActivity.this)
351 .refreshPlugins(
352 Intent.ACTION_PACKAGE_ADDED
353 .equals(action));
354 }
355 }
356 }
357 };
358 registerReceiver(mPackageInstallationReceiver, filter);
359
The Android Open Source Project0c908882009-03-03 19:32:16 -0800360 if (!mTabControl.restoreState(icicle)) {
361 // clear up the thumbnail directory if we can't restore the state as
362 // none of the files in the directory are referenced any more.
363 new ClearThumbnails().execute(
364 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700365 // there is no quit on Android. But if we can't restore the state,
366 // we can treat it as a new Browser, remove the old session cookies.
367 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800368 final Intent intent = getIntent();
369 final Bundle extra = intent.getExtras();
370 // Create an initial tab.
371 // If the intent is ACTION_VIEW and data is not null, the Browser is
372 // invoked to view the content by another application. In this case,
373 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700374 UrlData urlData = getUrlDataFromIntent(intent);
375
Grace Kloba22ac16e2009-10-07 18:00:23 -0700376 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800377 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700378 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700379 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800380 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800381 attachTabToContentView(t);
382 WebView webView = t.getWebView();
383 if (extra != null) {
384 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
385 if (scale > 0 && scale <= 1000) {
386 webView.setInitialScale(scale);
387 }
388 }
389 // If we are not restoring from an icicle, then there is a high
390 // likely hood this is the first run. So, check to see if the
391 // homepage needs to be configured and copy any plugins from our
392 // asset directory to the data partition.
393 if ((extra == null || !extra.getBoolean("testing"))
394 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800395 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800396 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800397
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700398 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400399 if (mSettings.isLoginInitialized()) {
400 webView.loadUrl(mSettings.getHomePage());
401 } else {
402 waitForCredentials();
403 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800404 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700405 if (extra != null) {
406 urlData.setPostData(extra
407 .getByteArray(Browser.EXTRA_POST_DATA));
408 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700409 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 }
411 } else {
412 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400413 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800414 attachTabToContentView(mTabControl.getCurrentTab());
415 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700416
Feng Qianb3c02da2009-06-29 15:58:08 -0700417 // Read JavaScript flags if it exists.
418 String jsFlags = mSettings.getJsFlags();
419 if (jsFlags.trim().length() != 0) {
420 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
421 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800422 }
423
424 @Override
425 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700426 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800427 // When a tab is closed on exit, the current tab index is set to -1.
428 // Reset before proceed as Browser requires the current tab to be set.
429 if (current == null) {
430 // Try to reset the tab in case the index was incorrect.
431 current = mTabControl.getTab(0);
432 if (current == null) {
433 // No tabs at all so just ignore this intent.
434 return;
435 }
436 mTabControl.setCurrentTab(current);
437 attachTabToContentView(current);
438 resetTitleAndIcon(current.getWebView());
439 }
440 final String action = intent.getAction();
441 final int flags = intent.getFlags();
442 if (Intent.ACTION_MAIN.equals(action) ||
443 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
444 // just resume the browser
445 return;
446 }
447 if (Intent.ACTION_VIEW.equals(action)
448 || Intent.ACTION_SEARCH.equals(action)
449 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
450 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100451 // If this was a search request (e.g. search query directly typed into the address bar),
452 // pass it on to the default web search provider.
453 if (handleWebSearchIntent(intent)) {
454 return;
455 }
456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 UrlData urlData = getUrlDataFromIntent(intent);
458 if (urlData.isEmpty()) {
459 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800460 }
Grace Kloba81678d92009-06-30 07:09:56 -0700461 urlData.setPostData(intent
462 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463
Grace Klobacc634032009-07-28 15:58:19 -0700464 final String appId = intent
465 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
466 if (Intent.ACTION_VIEW.equals(action)
467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700469 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
480 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700481 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100482
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700483 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400484 switchToTab(mTabControl.getTabIndex(appTab));
485 if (needsLoad) {
486 urlData.loadIn(appTab.getWebView());
487 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700488 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
492 if (needsLoad) {
493 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 }
495 }
496 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400497 } else {
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
504 }
505 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400506 } else {
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
511 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400512 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400513 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700514 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800515 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
532 } else {
533 current.getWebView().setDragTracker(new MeshTracker(index));
534 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800535 } else {
536 mSettings.toggleDebugSettings();
537 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800538 return;
539 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
542 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800543 }
544 }
545 }
546
Satish Sampath565505b2009-05-29 15:37:27 +0100547 private int parseUrlShortcut(String url) {
548 if (url == null) return SHORTCUT_INVALID;
549
550 // FIXME: quick search, need to be customized by setting
551 if (url.length() > 2 && url.charAt(1) == ' ') {
552 switch (url.charAt(0)) {
553 case 'g': return SHORTCUT_GOOGLE_SEARCH;
554 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
555 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
556 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
557 }
558 }
559 return SHORTCUT_INVALID;
560 }
561
562 /**
563 * Launches the default web search activity with the query parameters if the given intent's data
564 * are identified as plain search terms and not URLs/shortcuts.
565 * @return true if the intent was handled and web search activity was launched, false if not.
566 */
567 private boolean handleWebSearchIntent(Intent intent) {
568 if (intent == null) return false;
569
570 String url = null;
571 final String action = intent.getAction();
572 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700573 Uri data = intent.getData();
574 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100575 } else if (Intent.ACTION_SEARCH.equals(action)
576 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
577 || Intent.ACTION_WEB_SEARCH.equals(action)) {
578 url = intent.getStringExtra(SearchManager.QUERY);
579 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100580 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
581 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100582 }
583
584 /**
585 * Launches the default web search activity with the query parameters if the given url string
586 * was identified as plain search terms and not URL/shortcut.
587 * @return true if the request was handled and web search activity was launched, false if not.
588 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100589 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100590 if (inUrl == null) return false;
591
592 // In general, we shouldn't modify URL from Intent.
593 // But currently, we get the user-typed URL from search box as well.
594 String url = fixUrl(inUrl).trim();
595
596 // URLs and site specific search shortcuts are handled by the regular flow of control, so
597 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800598 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100599 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100600 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
601 return false;
602 }
603
604 Browser.updateVisitedHistory(mResolver, url, false);
605 Browser.addSearchUrl(mResolver, url);
606
607 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
608 intent.addCategory(Intent.CATEGORY_DEFAULT);
609 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100610 if (appData != null) {
611 intent.putExtra(SearchManager.APP_DATA, appData);
612 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100613 if (extraData != null) {
614 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
615 }
Grace Klobacc634032009-07-28 15:58:19 -0700616 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100617 startActivity(intent);
618
619 return true;
620 }
621
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700622 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800623 String url = null;
624 if (intent != null) {
625 final String action = intent.getAction();
626 if (Intent.ACTION_VIEW.equals(action)) {
627 url = smartUrlFilter(intent.getData());
628 if (url != null && url.startsWith("content:")) {
629 /* Append mimetype so webview knows how to display */
630 String mimeType = intent.resolveType(getContentResolver());
631 if (mimeType != null) {
632 url += "?" + mimeType;
633 }
634 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700635 if ("inline:".equals(url)) {
636 return new InlinedUrlData(
637 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
638 intent.getType(),
639 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
640 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
641 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800642 } else if (Intent.ACTION_SEARCH.equals(action)
643 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
644 || Intent.ACTION_WEB_SEARCH.equals(action)) {
645 url = intent.getStringExtra(SearchManager.QUERY);
646 if (url != null) {
647 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500648 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800649 // In general, we shouldn't modify URL from Intent.
650 // But currently, we get the user-typed URL from search box as well.
651 url = fixUrl(url);
652 url = smartUrlFilter(url);
653 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
654 if (url.contains(searchSource)) {
655 String source = null;
656 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
657 if (appData != null) {
658 source = appData.getString(SearchManager.SOURCE);
659 }
660 if (TextUtils.isEmpty(source)) {
661 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
662 }
663 url = url.replace(searchSource, "&source=android-"+source+"&");
664 }
665 }
666 }
667 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700668 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800669 }
670
671 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400672 // FIXME: Converting the url to lower case
673 // duplicates functionality in smartUrlFilter().
674 // However, changing all current callers of fixUrl to
675 // call smartUrlFilter in addition may have unwanted
676 // consequences, and is deferred for now.
677 int colon = inUrl.indexOf(':');
678 boolean allLower = true;
679 for (int index = 0; index < colon; index++) {
680 char ch = inUrl.charAt(index);
681 if (!Character.isLetter(ch)) {
682 break;
683 }
684 allLower &= Character.isLowerCase(ch);
685 if (index == colon - 1 && !allLower) {
686 inUrl = inUrl.substring(0, colon).toLowerCase()
687 + inUrl.substring(colon);
688 }
689 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
691 return inUrl;
692 if (inUrl.startsWith("http:") ||
693 inUrl.startsWith("https:")) {
694 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
695 inUrl = inUrl.replaceFirst("/", "//");
696 } else inUrl = inUrl.replaceFirst(":", "://");
697 }
698 return inUrl;
699 }
700
Grace Kloba22ac16e2009-10-07 18:00:23 -0700701 @Override
702 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800703 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700704 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
706 }
707
708 if (!mActivityInPause) {
709 Log.e(LOGTAG, "BrowserActivity is already resumed.");
710 return;
711 }
712
Mike Reed7bfa63b2009-05-28 11:08:32 -0400713 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800714 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400715 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800716
717 if (mWakeLock.isHeld()) {
718 mHandler.removeMessages(RELEASE_WAKELOCK);
719 mWakeLock.release();
720 }
721
722 if (mCredsDlg != null) {
723 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
724 // In case credential request never comes back
725 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
726 }
727 }
728
729 registerReceiver(mNetworkStateIntentReceiver,
730 mNetworkStateChangedFilter);
731 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800732 }
733
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400734 /**
735 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400736 * would change its appearance, use a different TitleBar to show overlayed
737 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400738 */
739 private TitleBar mFakeTitleBar;
740
741 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400742 * Holder for the fake title bar. It will have a foreground shadow, as well
743 * as a white background, so the fake title bar looks like the real one.
744 */
745 private ViewGroup mFakeTitleBarHolder;
746
747 /**
748 * Layout parameters for the fake title bar within mFakeTitleBarHolder
749 */
750 private FrameLayout.LayoutParams mFakeTitleBarParams
751 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800752 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400753 ViewGroup.LayoutParams.WRAP_CONTENT);
754 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400755 * Keeps track of whether the options menu is open. This is important in
756 * determining whether to show or hide the title bar overlay.
757 */
758 private boolean mOptionsMenuOpen;
759
760 /**
761 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
762 * of whether the configuration has changed. The first onMenuOpened call
763 * after a configuration change is simply a reopening of the same menu
764 * (i.e. mIconView did not change).
765 */
766 private boolean mConfigChanged;
767
768 /**
769 * Whether or not the options menu is in its smaller, icon menu form. When
770 * true, we want the title bar overlay to be up. When false, we do not.
771 * Only meaningful if mOptionsMenuOpen is true.
772 */
773 private boolean mIconView;
774
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400775 @Override
776 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400777 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
778 if (mOptionsMenuOpen) {
779 if (mConfigChanged) {
780 // We do not need to make any changes to the state of the
781 // title bar, since the only thing that happened was a
782 // change in orientation
783 mConfigChanged = false;
784 } else {
785 if (mIconView) {
786 // Switching the menu to expanded view, so hide the
787 // title bar.
788 hideFakeTitleBar();
789 mIconView = false;
790 } else {
791 // Switching the menu back to icon view, so show the
792 // title bar once again.
793 showFakeTitleBar();
794 mIconView = true;
795 }
796 }
797 } else {
798 // The options menu is closed, so open it, and show the title
799 showFakeTitleBar();
800 mOptionsMenuOpen = true;
801 mConfigChanged = false;
802 mIconView = true;
803 }
804 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400805 return true;
806 }
807
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400808 /**
809 * Special class used exclusively for the shadow drawn underneath the fake
810 * title bar. The shadow does not need to be drawn if the WebView
811 * underneath is scrolled to the top, because it will draw directly on top
812 * of the embedded shadow.
813 */
814 private static class Shadow extends View {
815 private WebView mWebView;
816
817 public Shadow(Context context, AttributeSet attrs) {
818 super(context, attrs);
819 }
820
821 public void setWebView(WebView view) {
822 mWebView = view;
823 }
824
825 @Override
826 public void draw(Canvas canvas) {
827 // In general onDraw is the method to override, but we care about
828 // whether or not the background gets drawn, which happens in draw()
829 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
830 super.draw(canvas);
831 }
832 // Need to invalidate so that if the scroll position changes, we
833 // still draw as appropriate.
834 invalidate();
835 }
836 }
837
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400838 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400839 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400840 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400841 && !mActivityInPause && decor != null
842 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400843 Rect visRect = new Rect();
844 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
845 if (LOGD_ENABLED) {
846 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
847 }
848 return;
849 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400850
851 WindowManager manager
852 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
853
854 // Add the title bar to the window manager so it can receive touches
855 // while the menu is up
856 WindowManager.LayoutParams params
857 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800858 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400859 ViewGroup.LayoutParams.WRAP_CONTENT,
860 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
861 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400862 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400864 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400865 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400866 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400867 // XXX : Without providing an offset, the fake title bar will be
868 // placed underneath the status bar. Use the global visible rect
869 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400870 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400871 // Add a holder for the title bar. It also holds a shadow to show
872 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400873 if (mFakeTitleBarHolder == null) {
874 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
875 .inflate(R.layout.title_bar_bg, null);
876 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400877 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
878 R.id.shadow);
879 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400880 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400881 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400882 }
883 }
884
885 @Override
886 public void onOptionsMenuClosed(Menu menu) {
887 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400888 if (!mInLoad) {
889 hideFakeTitleBar();
890 } else if (!mIconView) {
891 // The page is currently loading, and we are in expanded mode, so
892 // we were not showing the menu. Show it once again. It will be
893 // removed when the page finishes.
894 showFakeTitleBar();
895 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400896 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700897
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400898 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400899 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400900 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
901 mFakeTitleBarHolder.getLayoutParams();
902 WebView mainView = mTabControl.getCurrentWebView();
903 // Although we decided whether or not to animate based on the current
904 // scroll position, the scroll position may have changed since the
905 // fake title bar was displayed. Make sure it has the appropriate
906 // animation/lack thereof before removing.
907 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400908 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400909 WindowManager manager
910 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400911 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400912 mFakeTitleBarHolder.removeView(mFakeTitleBar);
913 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400914 }
915
The Android Open Source Project0c908882009-03-03 19:32:16 -0800916 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400917 * Special method for the fake title bar to call when displaying its context
918 * menu, since it is in its own Window, and its parent does not show a
919 * context menu.
920 */
921 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400922 if (null == mTitleBar.getParent()) {
923 return;
924 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400925 openContextMenu(mTitleBar);
926 }
927
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400928 @Override
929 public void onContextMenuClosed(Menu menu) {
930 super.onContextMenuClosed(menu);
931 if (mInLoad) {
932 showFakeTitleBar();
933 }
934 }
935
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400936 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800937 * onSaveInstanceState(Bundle map)
938 * onSaveInstanceState is called right before onStop(). The map contains
939 * the saved state.
940 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700941 @Override
942 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700943 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800944 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
945 }
946 // the default implementation requires each view to have an id. As the
947 // browser handles the state itself and it doesn't use id for the views,
948 // don't call the default implementation. Otherwise it will trigger the
949 // warning like this, "couldn't save which view has focus because the
950 // focused view XXX has no id".
951
952 // Save all the tabs
953 mTabControl.saveState(outState);
954 }
955
Grace Kloba22ac16e2009-10-07 18:00:23 -0700956 @Override
957 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800958 super.onPause();
959
960 if (mActivityInPause) {
961 Log.e(LOGTAG, "BrowserActivity is already paused.");
962 return;
963 }
964
Mike Reed7bfa63b2009-05-28 11:08:32 -0400965 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800966 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400967 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800968 mWakeLock.acquire();
969 mHandler.sendMessageDelayed(mHandler
970 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
971 }
972
973 // Clear the credentials toast if it is up
974 if (mCredsDlg != null && mCredsDlg.isShowing()) {
975 mCredsDlg.dismiss();
976 }
977 mCredsDlg = null;
978
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400979 // FIXME: This removes the active tabs page and resets the menu to
980 // MAIN_MENU. A better solution might be to do this work in onNewIntent
981 // but then we would need to save it in onSaveInstanceState and restore
982 // it in onCreate/onRestoreInstanceState
983 if (mActiveTabsPage != null) {
984 removeActiveTabPage(true);
985 }
986
The Android Open Source Project0c908882009-03-03 19:32:16 -0800987 cancelStopToast();
988
989 // unregister network state listener
990 unregisterReceiver(mNetworkStateIntentReceiver);
991 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800992 }
993
Grace Kloba22ac16e2009-10-07 18:00:23 -0700994 @Override
995 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700996 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800997 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
998 }
999 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001000
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001001 if (mUploadMessage != null) {
1002 mUploadMessage.onReceiveValue(null);
1003 mUploadMessage = null;
1004 }
1005
Grace Kloba0923d692009-09-23 21:37:25 -07001006 if (mTabControl == null) return;
1007
Grace Kloba1fc98a32009-10-21 13:23:08 -07001008 // Remove the fake title bar if it is there
1009 hideFakeTitleBar();
1010
The Android Open Source Project0c908882009-03-03 19:32:16 -08001011 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001012 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001013 if (t != null) {
1014 dismissSubWindow(t);
1015 removeTabFromContentView(t);
1016 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 // Destroy all the tabs
1018 mTabControl.destroy();
1019 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001020
Grace Klobab4da0ad2009-05-14 14:45:40 -07001021 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001022 }
1023
1024 @Override
1025 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001026 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 super.onConfigurationChanged(newConfig);
1028
1029 if (mPageInfoDialog != null) {
1030 mPageInfoDialog.dismiss();
1031 showPageInfo(
1032 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001033 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001034 }
1035 if (mSSLCertificateDialog != null) {
1036 mSSLCertificateDialog.dismiss();
1037 showSSLCertificate(
1038 mSSLCertificateView);
1039 }
1040 if (mSSLCertificateOnErrorDialog != null) {
1041 mSSLCertificateOnErrorDialog.dismiss();
1042 showSSLCertificateOnError(
1043 mSSLCertificateOnErrorView,
1044 mSSLCertificateOnErrorHandler,
1045 mSSLCertificateOnErrorError);
1046 }
1047 if (mHttpAuthenticationDialog != null) {
1048 String title = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1050 .toString();
1051 String name = ((TextView) mHttpAuthenticationDialog
1052 .findViewById(R.id.username_edit)).getText().toString();
1053 String password = ((TextView) mHttpAuthenticationDialog
1054 .findViewById(R.id.password_edit)).getText().toString();
1055 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1056 .getId();
1057 mHttpAuthenticationDialog.dismiss();
1058 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1059 name, password, focusId);
1060 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001061 }
1062
Grace Kloba22ac16e2009-10-07 18:00:23 -07001063 @Override
1064 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001065 super.onLowMemory();
1066 mTabControl.freeMemory();
1067 }
1068
Mike Reed7bfa63b2009-05-28 11:08:32 -04001069 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001070 Tab tab = mTabControl.getCurrentTab();
1071 boolean inLoad = tab.inLoad();
1072 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001074 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 if (w != null) {
1076 w.resumeTimers();
1077 }
1078 return true;
1079 } else {
1080 return false;
1081 }
1082 }
1083
Mike Reed7bfa63b2009-05-28 11:08:32 -04001084 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001085 Tab tab = mTabControl.getCurrentTab();
1086 boolean inLoad = tab.inLoad();
1087 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001088 CookieSyncManager.getInstance().stopSync();
1089 WebView w = mTabControl.getCurrentWebView();
1090 if (w != null) {
1091 w.pauseTimers();
1092 }
1093 return true;
1094 } else {
1095 return false;
1096 }
1097 }
1098
Leon Scroggins1f005d32009-08-10 17:36:42 -04001099 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001100 /*
1101 * This function is called when we are launching for the first time. We
1102 * are waiting for the login credentials before loading Google home
1103 * pages. This way the user will be logged in straight away.
1104 */
1105 private void waitForCredentials() {
1106 // Show a toast
1107 mCredsDlg = new ProgressDialog(this);
1108 mCredsDlg.setIndeterminate(true);
1109 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1110 // If the user cancels the operation, then cancel the Google
1111 // Credentials request.
1112 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1113 mCredsDlg.show();
1114
1115 // We set a timeout for the retrieval of credentials in onResume()
1116 // as that is when we have freed up some CPU time to get
1117 // the login credentials.
1118 }
1119
1120 /*
1121 * If we have received the credentials or we have timed out and we are
1122 * showing the credentials dialog, then it is time to move on.
1123 */
1124 private void resumeAfterCredentials() {
1125 if (mCredsDlg == null) {
1126 return;
1127 }
1128
1129 // Clear the toast
1130 if (mCredsDlg.isShowing()) {
1131 mCredsDlg.dismiss();
1132 }
1133 mCredsDlg = null;
1134
1135 // Clear any pending timeout
1136 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1137
1138 // Load the page
1139 WebView w = mTabControl.getCurrentWebView();
1140 if (w != null) {
1141 w.loadUrl(mSettings.getHomePage());
1142 }
1143
1144 // Update the settings, need to do this last as it can take a moment
1145 // to persist the settings. In the mean time we could be loading
1146 // content.
1147 mSettings.setLoginInitialized(this);
1148 }
1149
1150 // Open the icon database and retain all the icons for visited sites.
1151 private void retainIconsOnStartup() {
1152 final WebIconDatabase db = WebIconDatabase.getInstance();
1153 db.open(getDir("icons", 0).getPath());
1154 try {
1155 Cursor c = Browser.getAllBookmarks(mResolver);
1156 if (!c.moveToFirst()) {
1157 c.deactivate();
1158 return;
1159 }
1160 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1161 do {
1162 String url = c.getString(urlIndex);
1163 db.retainIconForPageUrl(url);
1164 } while (c.moveToNext());
1165 c.deactivate();
1166 } catch (IllegalStateException e) {
1167 Log.e(LOGTAG, "retainIconsOnStartup", e);
1168 }
1169 }
1170
1171 // Helper method for getting the top window.
1172 WebView getTopWindow() {
1173 return mTabControl.getCurrentTopWebView();
1174 }
1175
Grace Kloba22ac16e2009-10-07 18:00:23 -07001176 TabControl getTabControl() {
1177 return mTabControl;
1178 }
1179
The Android Open Source Project0c908882009-03-03 19:32:16 -08001180 @Override
1181 public boolean onCreateOptionsMenu(Menu menu) {
1182 super.onCreateOptionsMenu(menu);
1183
1184 MenuInflater inflater = getMenuInflater();
1185 inflater.inflate(R.menu.browser, menu);
1186 mMenu = menu;
1187 updateInLoadMenuItems();
1188 return true;
1189 }
1190
1191 /**
1192 * As the menu can be open when loading state changes
1193 * we must manually update the state of the stop/reload menu
1194 * item
1195 */
1196 private void updateInLoadMenuItems() {
1197 if (mMenu == null) {
1198 return;
1199 }
1200 MenuItem src = mInLoad ?
1201 mMenu.findItem(R.id.stop_menu_id):
1202 mMenu.findItem(R.id.reload_menu_id);
1203 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1204 dest.setIcon(src.getIcon());
1205 dest.setTitle(src.getTitle());
1206 }
1207
1208 @Override
1209 public boolean onContextItemSelected(MenuItem item) {
1210 // chording is not an issue with context menus, but we use the same
1211 // options selector, so set mCanChord to true so we can access them.
1212 mCanChord = true;
1213 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001214 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001215 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001216 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001217 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001218 Tab currentTab = mTabControl.getCurrentTab();
1219 if (null == currentTab) {
1220 result = false;
1221 break;
1222 }
1223 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001224 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001225 result = false;
1226 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001227 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001228 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001229 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001230 // -- Browser context menu
1231 case R.id.open_context_menu_id:
1232 case R.id.open_newtab_context_menu_id:
1233 case R.id.bookmark_context_menu_id:
1234 case R.id.save_link_context_menu_id:
1235 case R.id.share_link_context_menu_id:
1236 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001237 final WebView webView = getTopWindow();
1238 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001239 result = false;
1240 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001241 }
1242 final HashMap hrefMap = new HashMap();
1243 hrefMap.put("webview", webView);
1244 final Message msg = mHandler.obtainMessage(
1245 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001246 webView.requestFocusNodeHref(msg);
1247 break;
1248
1249 default:
1250 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001251 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001252 }
1253 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001254 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001255 }
1256
1257 private Bundle createGoogleSearchSourceBundle(String source) {
1258 Bundle bundle = new Bundle();
1259 bundle.putString(SearchManager.SOURCE, source);
1260 return bundle;
1261 }
1262
1263 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001264 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001265 */
1266 @Override
1267 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001268 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001269 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001270 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001271 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001272 return true;
1273 }
1274
1275 @Override
1276 public void startSearch(String initialQuery, boolean selectInitialQuery,
1277 Bundle appSearchData, boolean globalSearch) {
1278 if (appSearchData == null) {
1279 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1280 }
1281 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1282 }
1283
Leon Scroggins1f005d32009-08-10 17:36:42 -04001284 /**
1285 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1286 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001287 * @param index Index of the tab to change to, as defined by
1288 * mTabControl.getTabIndex(Tab t).
1289 * @return boolean True if we successfully switched to a different tab. If
1290 * the indexth tab is null, or if that tab is the same as
1291 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001292 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001293 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001294 Tab tab = mTabControl.getTab(index);
1295 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001296 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001297 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 }
1299 if (currentTab != null) {
1300 // currentTab may be null if it was just removed. In that case,
1301 // we do not need to remove it
1302 removeTabFromContentView(currentTab);
1303 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 mTabControl.setCurrentTab(tab);
1305 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001306 resetTitleIconAndProgress();
1307 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001308 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001309 }
1310
Grace Kloba22ac16e2009-10-07 18:00:23 -07001311 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001312 return openTabAndShow(mSettings.getHomePage(), false, null);
1313 }
1314
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001316 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001317 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001318 // This is the last tab. Open a new one, with the home
1319 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001320 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001321 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001322 return;
1323 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001324 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001325 int indexToShow = -1;
1326 if (parent != null) {
1327 indexToShow = mTabControl.getTabIndex(parent);
1328 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001329 final int currentIndex = mTabControl.getCurrentIndex();
1330 // Try to move to the tab to the right
1331 indexToShow = currentIndex + 1;
1332 if (indexToShow > mTabControl.getTabCount() - 1) {
1333 // Try to move to the tab to the left
1334 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001335 }
1336 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001337 if (switchToTab(indexToShow)) {
1338 // Close window
1339 closeTab(current);
1340 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 }
1342
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001343 private ActiveTabsPage mActiveTabsPage;
1344
1345 /**
1346 * Remove the active tabs page.
1347 * @param needToAttach If true, the active tabs page did not attach a tab
1348 * to the content view, so we need to do that here.
1349 */
1350 /* package */ void removeActiveTabPage(boolean needToAttach) {
1351 mContentView.removeView(mActiveTabsPage);
1352 mActiveTabsPage = null;
1353 mMenuState = R.id.MAIN_MENU;
1354 if (needToAttach) {
1355 attachTabToContentView(mTabControl.getCurrentTab());
1356 }
1357 getTopWindow().requestFocus();
1358 }
1359
The Android Open Source Project0c908882009-03-03 19:32:16 -08001360 @Override
1361 public boolean onOptionsItemSelected(MenuItem item) {
1362 if (!mCanChord) {
1363 // The user has already fired a shortcut with this hold down of the
1364 // menu key.
1365 return false;
1366 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001367 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001368 return false;
1369 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001370 if (mMenuIsDown) {
1371 // The shortcut action consumes the MENU. Even if it is still down,
1372 // it won't trigger the next shortcut action. In the case of the
1373 // shortcut action triggering a new activity, like Bookmarks, we
1374 // won't get onKeyUp for MENU. So it is important to reset it here.
1375 mMenuIsDown = false;
1376 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001377 switch (item.getItemId()) {
1378 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001379 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001380 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001381 break;
1382
Leon Scroggins64b80f32009-08-07 12:03:34 -04001383 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001384 onSearchRequested();
1385 break;
1386
1387 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001388 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001389 break;
1390
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001391 case R.id.active_tabs_menu_id:
1392 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1393 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001394 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001395 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1396 mActiveTabsPage.requestFocus();
1397 mMenuState = EMPTY_MENU;
1398 break;
1399
Leon Scroggins1f005d32009-08-10 17:36:42 -04001400 case R.id.add_bookmark_menu_id:
1401 Intent i = new Intent(BrowserActivity.this,
1402 AddBookmarkPage.class);
1403 WebView w = getTopWindow();
1404 i.putExtra("url", w.getUrl());
1405 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001406 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001407 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001408 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001409 break;
1410
1411 case R.id.stop_reload_menu_id:
1412 if (mInLoad) {
1413 stopLoading();
1414 } else {
1415 getTopWindow().reload();
1416 }
1417 break;
1418
1419 case R.id.back_menu_id:
1420 getTopWindow().goBack();
1421 break;
1422
1423 case R.id.forward_menu_id:
1424 getTopWindow().goForward();
1425 break;
1426
1427 case R.id.close_menu_id:
1428 // Close the subwindow if it exists.
1429 if (mTabControl.getCurrentSubWindow() != null) {
1430 dismissSubWindow(mTabControl.getCurrentTab());
1431 break;
1432 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001433 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001434 break;
1435
1436 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001437 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001438 if (current != null) {
1439 dismissSubWindow(current);
1440 current.getWebView().loadUrl(mSettings.getHomePage());
1441 }
1442 break;
1443
1444 case R.id.preferences_menu_id:
1445 Intent intent = new Intent(this,
1446 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001447 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1448 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001449 startActivityForResult(intent, PREFERENCES_PAGE);
1450 break;
1451
1452 case R.id.find_menu_id:
1453 if (null == mFindDialog) {
1454 mFindDialog = new FindDialog(this);
1455 }
1456 mFindDialog.setWebView(getTopWindow());
1457 mFindDialog.show();
1458 mMenuState = EMPTY_MENU;
1459 break;
1460
1461 case R.id.select_text_id:
1462 getTopWindow().emulateShiftHeld();
1463 break;
1464 case R.id.page_info_menu_id:
1465 showPageInfo(mTabControl.getCurrentTab(), false);
1466 break;
1467
1468 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001469 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001470 break;
1471
Leon Scroggins96afcb12009-12-10 12:35:56 -05001472 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001473 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001474 Tab currentTab = mTabControl.getCurrentTab();
1475 if (null == currentTab) {
1476 mCanChord = false;
1477 return false;
1478 }
1479 currentTab.populatePickerData();
1480 sharePage(this, currentTab.getTitle(),
1481 currentTab.getUrl(), currentTab.getFavicon(),
1482 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001483 break;
1484
1485 case R.id.dump_nav_menu_id:
1486 getTopWindow().debugDump();
1487 break;
1488
1489 case R.id.zoom_in_menu_id:
1490 getTopWindow().zoomIn();
1491 break;
1492
1493 case R.id.zoom_out_menu_id:
1494 getTopWindow().zoomOut();
1495 break;
1496
1497 case R.id.view_downloads_menu_id:
1498 viewDownloads(null);
1499 break;
1500
The Android Open Source Project0c908882009-03-03 19:32:16 -08001501 case R.id.window_one_menu_id:
1502 case R.id.window_two_menu_id:
1503 case R.id.window_three_menu_id:
1504 case R.id.window_four_menu_id:
1505 case R.id.window_five_menu_id:
1506 case R.id.window_six_menu_id:
1507 case R.id.window_seven_menu_id:
1508 case R.id.window_eight_menu_id:
1509 {
1510 int menuid = item.getItemId();
1511 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1512 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001513 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001514 if (desiredTab != null &&
1515 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001516 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001517 }
1518 break;
1519 }
1520 }
1521 }
1522 break;
1523
1524 default:
1525 if (!super.onOptionsItemSelected(item)) {
1526 return false;
1527 }
1528 // Otherwise fall through.
1529 }
1530 mCanChord = false;
1531 return true;
1532 }
1533
1534 public void closeFind() {
1535 mMenuState = R.id.MAIN_MENU;
1536 }
1537
Grace Kloba22ac16e2009-10-07 18:00:23 -07001538 @Override
1539 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001540 // This happens when the user begins to hold down the menu key, so
1541 // allow them to chord to get a shortcut.
1542 mCanChord = true;
1543 // Note: setVisible will decide whether an item is visible; while
1544 // setEnabled() will decide whether an item is enabled, which also means
1545 // whether the matching shortcut key will function.
1546 super.onPrepareOptionsMenu(menu);
1547 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001548 case EMPTY_MENU:
1549 if (mCurrentMenuState != mMenuState) {
1550 menu.setGroupVisible(R.id.MAIN_MENU, false);
1551 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1552 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001553 }
1554 break;
1555 default:
1556 if (mCurrentMenuState != mMenuState) {
1557 menu.setGroupVisible(R.id.MAIN_MENU, true);
1558 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1559 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001560 }
1561 final WebView w = getTopWindow();
1562 boolean canGoBack = false;
1563 boolean canGoForward = false;
1564 boolean isHome = false;
1565 if (w != null) {
1566 canGoBack = w.canGoBack();
1567 canGoForward = w.canGoForward();
1568 isHome = mSettings.getHomePage().equals(w.getUrl());
1569 }
1570 final MenuItem back = menu.findItem(R.id.back_menu_id);
1571 back.setEnabled(canGoBack);
1572
1573 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1574 home.setEnabled(!isHome);
1575
1576 menu.findItem(R.id.forward_menu_id)
1577 .setEnabled(canGoForward);
1578
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001579 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001580 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001581
The Android Open Source Project0c908882009-03-03 19:32:16 -08001582 // decide whether to show the share link option
1583 PackageManager pm = getPackageManager();
1584 Intent send = new Intent(Intent.ACTION_SEND);
1585 send.setType("text/plain");
1586 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1587 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1588
The Android Open Source Project0c908882009-03-03 19:32:16 -08001589 boolean isNavDump = mSettings.isNavDump();
1590 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1591 nav.setVisible(isNavDump);
1592 nav.setEnabled(isNavDump);
1593 break;
1594 }
1595 mCurrentMenuState = mMenuState;
1596 return true;
1597 }
1598
1599 @Override
1600 public void onCreateContextMenu(ContextMenu menu, View v,
1601 ContextMenuInfo menuInfo) {
1602 WebView webview = (WebView) v;
1603 WebView.HitTestResult result = webview.getHitTestResult();
1604 if (result == null) {
1605 return;
1606 }
1607
1608 int type = result.getType();
1609 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1610 Log.w(LOGTAG,
1611 "We should not show context menu when nothing is touched");
1612 return;
1613 }
1614 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1615 // let TextView handles context menu
1616 return;
1617 }
1618
1619 // Note, http://b/issue?id=1106666 is requesting that
1620 // an inflated menu can be used again. This is not available
1621 // yet, so inflate each time (yuk!)
1622 MenuInflater inflater = getMenuInflater();
1623 inflater.inflate(R.menu.browsercontext, menu);
1624
1625 // Show the correct menu group
1626 String extra = result.getExtra();
1627 menu.setGroupVisible(R.id.PHONE_MENU,
1628 type == WebView.HitTestResult.PHONE_TYPE);
1629 menu.setGroupVisible(R.id.EMAIL_MENU,
1630 type == WebView.HitTestResult.EMAIL_TYPE);
1631 menu.setGroupVisible(R.id.GEO_MENU,
1632 type == WebView.HitTestResult.GEO_TYPE);
1633 menu.setGroupVisible(R.id.IMAGE_MENU,
1634 type == WebView.HitTestResult.IMAGE_TYPE
1635 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1636 menu.setGroupVisible(R.id.ANCHOR_MENU,
1637 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1638 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1639
1640 // Setup custom handling depending on the type
1641 switch (type) {
1642 case WebView.HitTestResult.PHONE_TYPE:
1643 menu.setHeaderTitle(Uri.decode(extra));
1644 menu.findItem(R.id.dial_context_menu_id).setIntent(
1645 new Intent(Intent.ACTION_VIEW, Uri
1646 .parse(WebView.SCHEME_TEL + extra)));
1647 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1648 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001649 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001650 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1651 addIntent);
1652 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1653 new Copy(extra));
1654 break;
1655
1656 case WebView.HitTestResult.EMAIL_TYPE:
1657 menu.setHeaderTitle(extra);
1658 menu.findItem(R.id.email_context_menu_id).setIntent(
1659 new Intent(Intent.ACTION_VIEW, Uri
1660 .parse(WebView.SCHEME_MAILTO + extra)));
1661 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1662 new Copy(extra));
1663 break;
1664
1665 case WebView.HitTestResult.GEO_TYPE:
1666 menu.setHeaderTitle(extra);
1667 menu.findItem(R.id.map_context_menu_id).setIntent(
1668 new Intent(Intent.ACTION_VIEW, Uri
1669 .parse(WebView.SCHEME_GEO
1670 + URLEncoder.encode(extra))));
1671 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1672 new Copy(extra));
1673 break;
1674
1675 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1676 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1677 TextView titleView = (TextView) LayoutInflater.from(this)
1678 .inflate(android.R.layout.browser_link_context_header,
1679 null);
1680 titleView.setText(extra);
1681 menu.setHeaderView(titleView);
1682 // decide whether to show the open link in new tab option
1683 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001684 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001685 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1686 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001687 PackageManager pm = getPackageManager();
1688 Intent send = new Intent(Intent.ACTION_SEND);
1689 send.setType("text/plain");
1690 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1691 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1692 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1693 break;
1694 }
1695 // otherwise fall through to handle image part
1696 case WebView.HitTestResult.IMAGE_TYPE:
1697 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1698 menu.setHeaderTitle(extra);
1699 }
1700 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1701 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1702 menu.findItem(R.id.download_context_menu_id).
1703 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001704 menu.findItem(R.id.set_wallpaper_context_menu_id).
1705 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001706 break;
1707
1708 default:
1709 Log.w(LOGTAG, "We should not get here.");
1710 break;
1711 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001712 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001713 }
1714
The Android Open Source Project0c908882009-03-03 19:32:16 -08001715 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001716 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001717 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001718 // Attach the container that contains the main WebView and any other UI
1719 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001720 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001721
1722 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001724 if (errorConsole.numberOfErrors() == 0) {
1725 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1726 } else {
1727 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1728 }
1729
1730 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001731 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001732 ViewGroup.LayoutParams.WRAP_CONTENT));
1733 }
1734
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001735 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001736 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001737 // Request focus on the top window.
1738 t.getTopWindow().requestFocus();
1739 }
1740
1741 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001742 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001743 t.attachSubWindow(mContentView);
1744 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001745 }
1746
1747 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001749 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001750 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001751
Grace Kloba22ac16e2009-10-07 18:00:23 -07001752 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1753 if (errorConsole != null) {
1754 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001755 }
1756
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001757 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001758 if (view != null) {
1759 view.setEmbeddedTitleBar(null);
1760 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001761 }
1762
1763 // Remove the sub window if it exists. Also called by TabControl when the
1764 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001765 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001766 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001767 // dismiss the subwindow. This will destroy the WebView.
1768 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001769 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001770 }
1771
Leon Scroggins1f005d32009-08-10 17:36:42 -04001772 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001773 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001774 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001775 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 }
1777
1778 // This method does a ton of stuff. It will attempt to create a new tab
1779 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001780 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001781 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1782 String appId) {
1783 final Tab currentTab = mTabControl.getCurrentTab();
1784 if (mTabControl.canCreateNewTab()) {
1785 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1786 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001787 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001788 // If the last tab was removed from the active tabs page, currentTab
1789 // will be null.
1790 if (currentTab != null) {
1791 removeTabFromContentView(currentTab);
1792 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001793 // We must set the new tab as the current tab to reflect the old
1794 // animation behavior.
1795 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001796 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001797 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001798 urlData.loadIn(webview);
1799 }
1800 return tab;
1801 } else {
1802 // Get rid of the subwindow if it exists
1803 dismissSubWindow(currentTab);
1804 if (!urlData.isEmpty()) {
1805 // Load the given url.
1806 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001807 }
1808 }
Grace Klobac9181842009-04-14 08:53:22 -07001809 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001810 }
1811
Grace Kloba22ac16e2009-10-07 18:00:23 -07001812 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001813 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001814 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001815 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001816 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001817 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001818 }
Grace Klobac9181842009-04-14 08:53:22 -07001819 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001820 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001821 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001822 }
1823 }
1824
1825 private class Copy implements OnMenuItemClickListener {
1826 private CharSequence mText;
1827
1828 public boolean onMenuItemClick(MenuItem item) {
1829 copy(mText);
1830 return true;
1831 }
1832
1833 public Copy(CharSequence toCopy) {
1834 mText = toCopy;
1835 }
1836 }
1837
1838 private class Download implements OnMenuItemClickListener {
1839 private String mText;
1840
1841 public boolean onMenuItemClick(MenuItem item) {
1842 onDownloadStartNoStream(mText, null, null, null, -1);
1843 return true;
1844 }
1845
1846 public Download(String toDownload) {
1847 mText = toDownload;
1848 }
1849 }
1850
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001851 private class SetAsWallpaper extends Thread implements
1852 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1853 private URL mUrl;
1854 private ProgressDialog mWallpaperProgress;
1855 private boolean mCanceled = false;
1856
1857 public SetAsWallpaper(String url) {
1858 try {
1859 mUrl = new URL(url);
1860 } catch (MalformedURLException e) {
1861 mUrl = null;
1862 }
1863 }
1864
1865 public void onCancel(DialogInterface dialog) {
1866 mCanceled = true;
1867 }
1868
1869 public boolean onMenuItemClick(MenuItem item) {
1870 if (mUrl != null) {
1871 // The user may have tried to set a image with a large file size as their
1872 // background so it may take a few moments to perform the operation. Display
1873 // a progress spinner while it is working.
1874 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1875 mWallpaperProgress.setIndeterminate(true);
1876 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1877 mWallpaperProgress.setCancelable(true);
1878 mWallpaperProgress.setOnCancelListener(this);
1879 mWallpaperProgress.show();
1880 start();
1881 }
1882 return true;
1883 }
1884
1885 public void run() {
1886 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1887 try {
1888 // TODO: This will cause the resource to be downloaded again, when we
1889 // should in most cases be able to grab it from the cache. To fix this
1890 // we should query WebCore to see if we can access a cached version and
1891 // instead open an input stream on that. This pattern could also be used
1892 // in the download manager where the same problem exists.
1893 InputStream inputstream = mUrl.openStream();
1894 if (inputstream != null) {
1895 setWallpaper(inputstream);
1896 }
1897 } catch (IOException e) {
1898 Log.e(LOGTAG, "Unable to set new wallpaper");
1899 // Act as though the user canceled the operation so we try to
1900 // restore the old wallpaper.
1901 mCanceled = true;
1902 }
1903
1904 if (mCanceled) {
1905 // Restore the old wallpaper if the user cancelled whilst we were setting
1906 // the new wallpaper.
1907 int width = oldWallpaper.getIntrinsicWidth();
1908 int height = oldWallpaper.getIntrinsicHeight();
1909 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1910 Canvas canvas = new Canvas(bm);
1911 oldWallpaper.setBounds(0, 0, width, height);
1912 oldWallpaper.draw(canvas);
1913 try {
1914 setWallpaper(bm);
1915 } catch (IOException e) {
1916 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1917 }
1918 mCanceled = false;
1919 }
1920
1921 if (mWallpaperProgress.isShowing()) {
1922 mWallpaperProgress.dismiss();
1923 }
1924 }
1925 }
1926
The Android Open Source Project0c908882009-03-03 19:32:16 -08001927 private void copy(CharSequence text) {
1928 try {
1929 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1930 if (clip != null) {
1931 clip.setClipboardText(text);
1932 }
1933 } catch (android.os.RemoteException e) {
1934 Log.e(LOGTAG, "Copy failed", e);
1935 }
1936 }
1937
1938 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001939 * Resets the browser title-view to whatever it must be
1940 * (for example, if we had a loading error)
1941 * When we have a new page, we call resetTitle, when we
1942 * have to reset the titlebar to whatever it used to be
1943 * (for example, if the user chose to stop loading), we
1944 * call resetTitleAndRevertLockIcon.
1945 */
1946 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001947 mTabControl.getCurrentTab().revertLockIcon();
1948 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001949 resetTitleIconAndProgress();
1950 }
1951
1952 /**
1953 * Reset the title, favicon, and progress.
1954 */
1955 private void resetTitleIconAndProgress() {
1956 WebView current = mTabControl.getCurrentWebView();
1957 if (current == null) {
1958 return;
1959 }
1960 resetTitleAndIcon(current);
1961 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001962 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001963 }
1964
1965 // Reset the title and the icon based on the given item.
1966 private void resetTitleAndIcon(WebView view) {
1967 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1968 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001969 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 setFavicon(item.getFavicon());
1971 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001972 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001973 setFavicon(null);
1974 }
1975 }
1976
1977 /**
1978 * Sets a title composed of the URL and the title string.
1979 * @param url The URL of the site being loaded.
1980 * @param title The title of the site being loaded.
1981 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001982 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 mUrl = url;
1984 mTitle = title;
1985
Leon Scroggins68579392009-09-15 15:31:54 -04001986 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001987 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001988 }
1989
1990 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001991 * @param url The URL to build a title version of the URL from.
1992 * @return The title version of the URL or null if fails.
1993 * The title version of the URL can be either the URL hostname,
1994 * or the hostname with an "https://" prefix (for secure URLs),
1995 * or an empty string if, for example, the URL in question is a
1996 * file:// URL with no hostname.
1997 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001998 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001999 String titleUrl = null;
2000
2001 if (url != null) {
2002 try {
2003 // parse the url string
2004 URL urlObj = new URL(url);
2005 if (urlObj != null) {
2006 titleUrl = "";
2007
2008 String protocol = urlObj.getProtocol();
2009 String host = urlObj.getHost();
2010
2011 if (host != null && 0 < host.length()) {
2012 titleUrl = host;
2013 if (protocol != null) {
2014 // if a secure site, add an "https://" prefix!
2015 if (protocol.equalsIgnoreCase("https")) {
2016 titleUrl = protocol + "://" + host;
2017 }
2018 }
2019 }
2020 }
2021 } catch (MalformedURLException e) {}
2022 }
2023
2024 return titleUrl;
2025 }
2026
2027 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002028 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002029 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002030 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002031 }
2032
2033 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002034 * Close the tab, remove its associated title bar, and adjust mTabControl's
2035 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002036 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002037 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002038 int currentIndex = mTabControl.getCurrentIndex();
2039 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002040 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002041 if (currentIndex >= removeIndex && currentIndex != 0) {
2042 currentIndex--;
2043 }
2044 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002045 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002046 }
2047
2048 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002049 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002050 if (current == null) {
2051 /*
2052 * Instead of finishing the activity, simply push this to the back
2053 * of the stack and let ActivityManager to choose the foreground
2054 * activity. As BrowserActivity is singleTask, it will be always the
2055 * root of the task. So we can use either true or false for
2056 * moveTaskToBack().
2057 */
2058 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002059 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060 }
2061 WebView w = current.getWebView();
2062 if (w.canGoBack()) {
2063 w.goBack();
2064 } else {
2065 // Check to see if we are closing a window that was created by
2066 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002067 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002068 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002069 switchToTab(mTabControl.getTabIndex(parent));
2070 // Now we close the other tab
2071 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002072 } else {
2073 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002074 // force the tab's inLoad() to be false as we are going to
2075 // either finish the activity or remove the tab. This will
2076 // ensure pauseWebViewTimers() taking action.
2077 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 if (mTabControl.getTabCount() == 1) {
2079 finish();
2080 return;
2081 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002082 // call pauseWebViewTimers() now, we won't be able to call
2083 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002084 // Temporarily change mActivityInPause to be true as
2085 // pauseWebViewTimers() will do nothing if mActivityInPause
2086 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002087 boolean savedState = mActivityInPause;
2088 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002089 Log.e(LOGTAG, "BrowserActivity is already paused "
2090 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002091 }
2092 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002093 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002094 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002095 removeTabFromContentView(current);
2096 mTabControl.removeTab(current);
2097 }
2098 /*
2099 * Instead of finishing the activity, simply push this to the back
2100 * of the stack and let ActivityManager to choose the foreground
2101 * activity. As BrowserActivity is singleTask, it will be always the
2102 * root of the task. So we can use either true or false for
2103 * moveTaskToBack().
2104 */
2105 moveTaskToBack(true);
2106 }
2107 }
2108 }
2109
Grace Kloba22ac16e2009-10-07 18:00:23 -07002110 boolean isMenuDown() {
2111 return mMenuIsDown;
2112 }
2113
Grace Kloba5942df02009-09-18 11:48:29 -07002114 @Override
2115 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002116 // Even if MENU is already held down, we need to call to super to open
2117 // the IME on long press.
2118 if (KeyEvent.KEYCODE_MENU == keyCode) {
2119 mMenuIsDown = true;
2120 return super.onKeyDown(keyCode, event);
2121 }
Grace Kloba5942df02009-09-18 11:48:29 -07002122 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2123 // still down, we don't want to trigger the search. Pretend to consume
2124 // the key and do nothing.
2125 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002126
Grace Kloba5942df02009-09-18 11:48:29 -07002127 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002128 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002129 // WebView/WebTextView handle the keys in the KeyDown. As
2130 // the Activity's shortcut keys are only handled when WebView
2131 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2132 if (event.isShiftPressed()) {
2133 getTopWindow().pageUp(false);
2134 } else {
2135 getTopWindow().pageDown(false);
2136 }
Grace Kloba5942df02009-09-18 11:48:29 -07002137 return true;
2138 case KeyEvent.KEYCODE_BACK:
2139 if (event.getRepeatCount() == 0) {
2140 event.startTracking();
2141 return true;
2142 } else if (mCustomView == null && mActiveTabsPage == null
2143 && event.isLongPress()) {
2144 bookmarksOrHistoryPicker(true);
2145 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
Grace Kloba5942df02009-09-18 11:48:29 -07002147 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002148 }
Grace Kloba5942df02009-09-18 11:48:29 -07002149 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002150 }
2151
Grace Kloba5942df02009-09-18 11:48:29 -07002152 @Override
2153 public boolean onKeyUp(int keyCode, KeyEvent event) {
2154 switch(keyCode) {
2155 case KeyEvent.KEYCODE_MENU:
2156 mMenuIsDown = false;
2157 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002158 case KeyEvent.KEYCODE_BACK:
2159 if (event.isTracking() && !event.isCanceled()) {
2160 if (mCustomView != null) {
2161 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002162 mTabControl.getCurrentWebView().getWebChromeClient()
2163 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002164 } else if (mActiveTabsPage != null) {
2165 // if tab page is showing, hide it
2166 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002168 WebView subwindow = mTabControl.getCurrentSubWindow();
2169 if (subwindow != null) {
2170 if (subwindow.canGoBack()) {
2171 subwindow.goBack();
2172 } else {
2173 dismissSubWindow(mTabControl.getCurrentTab());
2174 }
2175 } else {
2176 goBackOnePageOrQuit();
2177 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 }
Grace Kloba5942df02009-09-18 11:48:29 -07002179 return true;
2180 }
2181 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002182 }
Grace Kloba5942df02009-09-18 11:48:29 -07002183 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002184 }
2185
Leon Scroggins68579392009-09-15 15:31:54 -04002186 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002187 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 resetTitleAndRevertLockIcon();
2189 WebView w = getTopWindow();
2190 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002191 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2192 // same logic here. But for subwindow case, should we call into the main
2193 // WebView's onPageFinished as we never call its onPageStarted and if
2194 // the page finishes itself, we don't call onPageFinished.
2195 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2196 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002197
2198 cancelStopToast();
2199 mStopToast = Toast
2200 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2201 mStopToast.show();
2202 }
2203
Grace Kloba22ac16e2009-10-07 18:00:23 -07002204 boolean didUserStopLoading() {
2205 return mDidStopLoad;
2206 }
2207
The Android Open Source Project0c908882009-03-03 19:32:16 -08002208 private void cancelStopToast() {
2209 if (mStopToast != null) {
2210 mStopToast.cancel();
2211 mStopToast = null;
2212 }
2213 }
2214
Grace Kloba22ac16e2009-10-07 18:00:23 -07002215 // called by a UI or non-UI thread to post the message
2216 public void postMessage(int what, int arg1, int arg2, Object obj,
2217 long delayMillis) {
2218 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2219 obj), delayMillis);
2220 }
2221
2222 // called by a UI or non-UI thread to remove the message
2223 void removeMessages(int what, Object object) {
2224 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002225 }
2226
2227 // public message ids
2228 public final static int LOAD_URL = 1001;
2229 public final static int STOP_LOAD = 1002;
2230
2231 // Message Ids
2232 private static final int FOCUS_NODE_HREF = 102;
2233 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002234 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002235
Grace Kloba22ac16e2009-10-07 18:00:23 -07002236 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002237
The Android Open Source Project0c908882009-03-03 19:32:16 -08002238 // Private handler for handling javascript and saving passwords
2239 private Handler mHandler = new Handler() {
2240
2241 public void handleMessage(Message msg) {
2242 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002243 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002244 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002245 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002246 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002247 if (url == null || url.length() == 0) {
2248 break;
2249 }
2250 HashMap focusNodeMap = (HashMap) msg.obj;
2251 WebView view = (WebView) focusNodeMap.get("webview");
2252 // Only apply the action if the top window did not change.
2253 if (getTopWindow() != view) {
2254 break;
2255 }
2256 switch (msg.arg1) {
2257 case R.id.open_context_menu_id:
2258 case R.id.view_image_context_menu_id:
2259 loadURL(getTopWindow(), url);
2260 break;
2261 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002262 final Tab parent = mTabControl.getCurrentTab();
2263 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002264 if (newTab != parent) {
2265 parent.addChildTab(newTab);
2266 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002267 break;
2268 case R.id.bookmark_context_menu_id:
2269 Intent intent = new Intent(BrowserActivity.this,
2270 AddBookmarkPage.class);
2271 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002272 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 startActivity(intent);
2274 break;
2275 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002276 // See if this site has been visited before
2277 StringBuilder sb = new StringBuilder(
2278 Browser.BookmarkColumns.URL + " = ");
2279 DatabaseUtils.appendEscapedSQLString(sb, url);
2280 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2281 Browser.HISTORY_PROJECTION,
2282 sb.toString(),
2283 null,
2284 null);
2285 if (c.moveToFirst()) {
2286 // The site has been visited before, so grab the
2287 // info from the database.
2288 Bitmap favicon = null;
2289 Bitmap thumbnail = null;
2290 String linkTitle = c.getString(Browser.
2291 HISTORY_PROJECTION_TITLE_INDEX);
2292 byte[] data = c.getBlob(Browser.
2293 HISTORY_PROJECTION_FAVICON_INDEX);
2294 if (data != null) {
2295 favicon = BitmapFactory.decodeByteArray(
2296 data, 0, data.length);
2297 }
2298 data = c.getBlob(Browser.
2299 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2300 if (data != null) {
2301 thumbnail = BitmapFactory.decodeByteArray(
2302 data, 0, data.length);
2303 }
2304 sharePage(BrowserActivity.this,
2305 linkTitle, url, favicon, thumbnail);
2306 } else {
2307 Browser.sendString(BrowserActivity.this, url,
2308 getString(
2309 R.string.choosertitle_sharevia));
2310 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002311 break;
2312 case R.id.copy_link_context_menu_id:
2313 copy(url);
2314 break;
2315 case R.id.save_link_context_menu_id:
2316 case R.id.download_context_menu_id:
2317 onDownloadStartNoStream(url, null, null, null, -1);
2318 break;
2319 }
2320 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002321 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002322
2323 case LOAD_URL:
2324 loadURL(getTopWindow(), (String) msg.obj);
2325 break;
2326
2327 case STOP_LOAD:
2328 stopLoading();
2329 break;
2330
2331 case CANCEL_CREDS_REQUEST:
2332 resumeAfterCredentials();
2333 break;
2334
The Android Open Source Project0c908882009-03-03 19:32:16 -08002335 case RELEASE_WAKELOCK:
2336 if (mWakeLock.isHeld()) {
2337 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002338 // if we reach here, Browser should be still in the
2339 // background loading after WAKELOCK_TIMEOUT (5-min).
2340 // To avoid burning the battery, stop loading.
2341 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002342 }
2343 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002344
2345 case UPDATE_BOOKMARK_THUMBNAIL:
2346 WebView view = (WebView) msg.obj;
2347 if (view != null) {
2348 updateScreenshot(view);
2349 }
2350 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002351 }
2352 }
2353 };
2354
Leon Scroggins96afcb12009-12-10 12:35:56 -05002355 /**
2356 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2357 * an {@link Intent} to launch the Activity chooser.
2358 * @param c Context used to launch a new Activity.
2359 * @param title Title of the page. Stored in the Intent with
2360 * {@link Browser#EXTRA_SHARE_TITLE}
2361 * @param url URL of the page. Stored in the Intent with
2362 * {@link Intent#EXTRA_TEXT}
2363 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2364 * with {@link Browser#EXTRA_SHARE_FAVICON}
2365 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2366 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2367 */
2368 public static final void sharePage(Context c, String title, String url,
2369 Bitmap favicon, Bitmap screenshot) {
2370 Intent send = new Intent(Intent.ACTION_SEND);
2371 send.setType("text/plain");
2372 send.putExtra(Intent.EXTRA_TEXT, url);
2373 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2374 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2375 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2376 try {
2377 c.startActivity(Intent.createChooser(send, c.getString(
2378 R.string.choosertitle_sharevia)));
2379 } catch(android.content.ActivityNotFoundException ex) {
2380 // if no app handles it, do nothing
2381 }
2382 }
2383
Leon Scroggins89c6d362009-07-15 16:54:37 -04002384 private void updateScreenshot(WebView view) {
2385 // If this is a bookmarked site, add a screenshot to the database.
2386 // FIXME: When should we update? Every time?
2387 // FIXME: Would like to make sure there is actually something to
2388 // draw, but the API for that (WebViewCore.pictureReady()) is not
2389 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002390
Patrick Scott3918d442009-08-04 13:22:29 -04002391 ContentResolver cr = getContentResolver();
2392 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002393 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002394 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002395 boolean succeed = c.moveToFirst();
2396 ContentValues values = null;
2397 while (succeed) {
2398 if (values == null) {
2399 final ByteArrayOutputStream os
2400 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002401 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002402 if (bm == null) {
2403 c.close();
2404 return;
2405 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002406 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2407 values = new ContentValues();
2408 values.put(Browser.BookmarkColumns.THUMBNAIL,
2409 os.toByteArray());
2410 }
2411 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2412 c.getInt(0)), values, null, null);
2413 succeed = c.moveToNext();
2414 }
2415 c.close();
2416 }
2417 }
2418
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002419 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002420 * Values for the size of the thumbnail created when taking a screenshot.
2421 * Lazily initialized. Instead of using these directly, use
2422 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002423 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002424 private static int THUMBNAIL_WIDTH = 0;
2425 private static int THUMBNAIL_HEIGHT = 0;
2426
2427 /**
2428 * Return the desired width for thumbnail screenshots, which are stored in
2429 * the database, and used on the bookmarks screen.
2430 * @param context Context for finding out the density of the screen.
2431 * @return int desired width for thumbnail screenshot.
2432 */
2433 /* package */ static int getDesiredThumbnailWidth(Context context) {
2434 if (THUMBNAIL_WIDTH == 0) {
2435 float density = context.getResources().getDisplayMetrics().density;
2436 THUMBNAIL_WIDTH = (int) (90 * density);
2437 THUMBNAIL_HEIGHT = (int) (80 * density);
2438 }
2439 return THUMBNAIL_WIDTH;
2440 }
2441
2442 /**
2443 * Return the desired height for thumbnail screenshots, which are stored in
2444 * the database, and used on the bookmarks screen.
2445 * @param context Context for finding out the density of the screen.
2446 * @return int desired height for thumbnail screenshot.
2447 */
2448 /* package */ static int getDesiredThumbnailHeight(Context context) {
2449 // To ensure that they are both initialized.
2450 getDesiredThumbnailWidth(context);
2451 return THUMBNAIL_HEIGHT;
2452 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002453
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002454 private Bitmap createScreenshot(WebView view) {
2455 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002456 if (thumbnail == null) {
2457 return null;
2458 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002459 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2460 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002461 Canvas canvas = new Canvas(bm);
2462 // May need to tweak these values to determine what is the
2463 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002464 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002465 int thumbnailHeight = thumbnail.getHeight();
2466 float scaleFactorX = 1.0f;
2467 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002468 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002469 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002470 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002471 } else {
2472 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002473 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002474
2475 if (view.getWidth() > view.getHeight() &&
2476 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2477 // If the device is in landscape and the page is shorter
2478 // than the height of the view, stretch the thumbnail to fill the
2479 // space.
2480 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2481 (float)thumbnailHeight;
2482 } else {
2483 // In the portrait case, this looks nice.
2484 scaleFactorY = scaleFactorX;
2485 }
2486
2487 canvas.scale(scaleFactorX, scaleFactorY);
2488
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002489 thumbnail.draw(canvas);
2490 return bm;
2491 }
2492
The Android Open Source Project0c908882009-03-03 19:32:16 -08002493 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002494 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002495 //-------------------------------------------------------------------------
2496
2497 // Use in overrideUrlLoading
2498 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2499 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2500 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2501 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2502
Grace Kloba22ac16e2009-10-07 18:00:23 -07002503 void onPageStarted(WebView view, String url, Bitmap favicon) {
2504 // when BrowserActivity just starts, onPageStarted may be called before
2505 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2506 // to start the timer. As we won't switch tabs while an activity is in
2507 // pause state, we can ensure calling resume and pause in pair.
2508 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002509
Grace Kloba22ac16e2009-10-07 18:00:23 -07002510 resetLockIcon(url);
2511 setUrlTitle(url, null);
2512 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002513 // Keep this initial progress in sync with initialProgressValue (* 100)
2514 // in ProgressTracker.cpp
2515 // Show some progress so that the user knows the page is beginning to
2516 // load
2517 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002518 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002519 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002520
Grace Kloba22ac16e2009-10-07 18:00:23 -07002521 if (mSettings.isTracing()) {
2522 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002523 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002524 WebAddress uri = new WebAddress(url);
2525 host = uri.mHost;
2526 } catch (android.net.ParseException ex) {
2527 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002528 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002529 host = host.replace('.', '_');
2530 host += ".trace";
2531 mInTrace = true;
2532 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2533 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 // Performance probe
2536 if (false) {
2537 mStart = SystemClock.uptimeMillis();
2538 mProcessStart = Process.getElapsedCpuTime();
2539 long[] sysCpu = new long[7];
2540 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2541 sysCpu, null)) {
2542 mUserStart = sysCpu[0] + sysCpu[1];
2543 mSystemStart = sysCpu[2];
2544 mIdleStart = sysCpu[3];
2545 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2546 }
2547 mUiStart = SystemClock.currentThreadTimeMillis();
2548 }
2549 }
2550
2551 void onPageFinished(WebView view, String url) {
2552 // Reset the title and icon in case we stopped a provisional load.
2553 resetTitleAndIcon(view);
2554 // Update the lock icon image only once we are done loading
2555 updateLockIconToLatest();
2556 // pause the WebView timer and release the wake lock if it is finished
2557 // while BrowserActivity is in pause state.
2558 if (mActivityInPause && pauseWebViewTimers()) {
2559 if (mWakeLock.isHeld()) {
2560 mHandler.removeMessages(RELEASE_WAKELOCK);
2561 mWakeLock.release();
2562 }
2563 }
2564
2565 // Performance probe
2566 if (false) {
2567 long[] sysCpu = new long[7];
2568 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2569 sysCpu, null)) {
2570 String uiInfo = "UI thread used "
2571 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2572 + " ms";
2573 if (LOGD_ENABLED) {
2574 Log.d(LOGTAG, uiInfo);
2575 }
2576 //The string that gets written to the log
2577 String performanceString = "It took total "
2578 + (SystemClock.uptimeMillis() - mStart)
2579 + " ms clock time to load the page."
2580 + "\nbrowser process used "
2581 + (Process.getElapsedCpuTime() - mProcessStart)
2582 + " ms, user processes used "
2583 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2584 + " ms, kernel used "
2585 + (sysCpu[2] - mSystemStart) * 10
2586 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2587 + " ms and irq took "
2588 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2589 * 10 + " ms, " + uiInfo;
2590 if (LOGD_ENABLED) {
2591 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2592 }
2593 if (url != null) {
2594 // strip the url to maintain consistency
2595 String newUrl = new String(url);
2596 if (newUrl.startsWith("http://www.")) {
2597 newUrl = newUrl.substring(11);
2598 } else if (newUrl.startsWith("http://")) {
2599 newUrl = newUrl.substring(7);
2600 } else if (newUrl.startsWith("https://www.")) {
2601 newUrl = newUrl.substring(12);
2602 } else if (newUrl.startsWith("https://")) {
2603 newUrl = newUrl.substring(8);
2604 }
2605 if (LOGD_ENABLED) {
2606 Log.d(LOGTAG, newUrl + " loaded");
2607 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002608 }
2609 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002610 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002611
Grace Kloba22ac16e2009-10-07 18:00:23 -07002612 if (mInTrace) {
2613 mInTrace = false;
2614 Debug.stopMethodTracing();
2615 }
2616 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002617
Grace Kloba22ac16e2009-10-07 18:00:23 -07002618 boolean shouldOverrideUrlLoading(WebView view, String url) {
2619 if (url.startsWith(SCHEME_WTAI)) {
2620 // wtai://wp/mc;number
2621 // number=string(phone-number)
2622 if (url.startsWith(SCHEME_WTAI_MC)) {
2623 Intent intent = new Intent(Intent.ACTION_VIEW,
2624 Uri.parse(WebView.SCHEME_TEL +
2625 url.substring(SCHEME_WTAI_MC.length())));
2626 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002627 return true;
2628 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002629 // wtai://wp/sd;dtmf
2630 // dtmf=string(dialstring)
2631 if (url.startsWith(SCHEME_WTAI_SD)) {
2632 // TODO: only send when there is active voice connection
2633 return false;
2634 }
2635 // wtai://wp/ap;number;name
2636 // number=string(phone-number)
2637 // name=string
2638 if (url.startsWith(SCHEME_WTAI_AP)) {
2639 // TODO
2640 return false;
2641 }
2642 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002643
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 // The "about:" schemes are internal to the browser; don't want these to
2645 // be dispatched to other apps.
2646 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002647 return false;
2648 }
2649
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 Intent intent;
2651 // perform generic parsing of the URI to turn it into an Intent.
2652 try {
2653 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2654 } catch (URISyntaxException ex) {
2655 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2656 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002657 }
2658
Grace Kloba22ac16e2009-10-07 18:00:23 -07002659 // check whether the intent can be resolved. If not, we will see
2660 // whether we can download it from the Market.
2661 if (getPackageManager().resolveActivity(intent, 0) == null) {
2662 String packagename = intent.getPackage();
2663 if (packagename != null) {
2664 intent = new Intent(Intent.ACTION_VIEW, Uri
2665 .parse("market://search?q=pname:" + packagename));
2666 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2667 startActivity(intent);
2668 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002669 } else {
2670 return false;
2671 }
2672 }
2673
Grace Kloba22ac16e2009-10-07 18:00:23 -07002674 // sanitize the Intent, ensuring web pages can not bypass browser
2675 // security (only access to BROWSABLE activities).
2676 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2677 intent.setComponent(null);
2678 try {
2679 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680 return true;
2681 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002682 } catch (ActivityNotFoundException ex) {
2683 // ignore the error. If no application can handle the URL,
2684 // eg about:blank, assume the browser can handle it.
2685 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686
Grace Kloba22ac16e2009-10-07 18:00:23 -07002687 if (mMenuIsDown) {
2688 openTab(url);
2689 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002690 return true;
2691 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002692 return false;
2693 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002694
Grace Kloba22ac16e2009-10-07 18:00:23 -07002695 // -------------------------------------------------------------------------
2696 // Helper function for WebChromeClient
2697 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002698
Grace Kloba22ac16e2009-10-07 18:00:23 -07002699 void onProgressChanged(WebView view, int newProgress) {
2700 mTitleBar.setProgress(newProgress);
2701 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002702
Grace Kloba22ac16e2009-10-07 18:00:23 -07002703 if (newProgress == 100) {
2704 // onProgressChanged() may continue to be called after the main
2705 // frame has finished loading, as any remaining sub frames continue
2706 // to load. We'll only get called once though with newProgress as
2707 // 100 when everything is loaded. (onPageFinished is called once
2708 // when the main frame completes loading regardless of the state of
2709 // any sub frames so calls to onProgressChanges may continue after
2710 // onPageFinished has executed)
2711 if (mInLoad) {
2712 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002713 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002714 // If the options menu is open, leave the title bar
2715 if (!mOptionsMenuOpen || !mIconView) {
2716 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002717 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002718 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002719 } else if (!mInLoad) {
2720 // onPageFinished may have already been called but a subframe is
2721 // still loading and updating the progress. Reset mInLoad and update
2722 // the menu items.
2723 mInLoad = true;
2724 updateInLoadMenuItems();
2725 if (!mOptionsMenuOpen || mIconView) {
2726 // This page has begun to load, so show the title bar
2727 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 }
2729 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002730 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002733 // if a view already exists then immediately terminate the new one
2734 if (mCustomView != null) {
2735 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002736 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002737 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738
2739 // Add the custom view to its container.
2740 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2741 mCustomView = view;
2742 mCustomViewCallback = callback;
2743 // Save the menu state and set it to empty while the custom
2744 // view is showing.
2745 mOldMenuState = mMenuState;
2746 mMenuState = EMPTY_MENU;
2747 // Hide the content view.
2748 mContentView.setVisibility(View.GONE);
2749 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002750 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002751 mCustomViewContainer.setVisibility(View.VISIBLE);
2752 mCustomViewContainer.bringToFront();
2753 }
2754
2755 void onHideCustomView() {
2756 if (mCustomView == null)
2757 return;
2758
2759 // Hide the custom view.
2760 mCustomView.setVisibility(View.GONE);
2761 // Remove the custom view from its container.
2762 mCustomViewContainer.removeView(mCustomView);
2763 mCustomView = null;
2764 // Reset the old menu state.
2765 mMenuState = mOldMenuState;
2766 mOldMenuState = EMPTY_MENU;
2767 mCustomViewContainer.setVisibility(View.GONE);
2768 mCustomViewCallback.onCustomViewHidden();
2769 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002770 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002771 mContentView.setVisibility(View.VISIBLE);
2772 }
2773
2774 Bitmap getDefaultVideoPoster() {
2775 if (mDefaultVideoPoster == null) {
2776 mDefaultVideoPoster = BitmapFactory.decodeResource(
2777 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002778 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002779 return mDefaultVideoPoster;
2780 }
Patrick Scott3918d442009-08-04 13:22:29 -04002781
Grace Kloba22ac16e2009-10-07 18:00:23 -07002782 View getVideoLoadingProgressView() {
2783 if (mVideoProgressView == null) {
2784 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2785 mVideoProgressView = inflater.inflate(
2786 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002787 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 return mVideoProgressView;
2789 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002790
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002791 /*
2792 * The Object used to inform the WebView of the file to upload.
2793 */
2794 private ValueCallback<Uri> mUploadMessage;
2795
Grace Kloba22ac16e2009-10-07 18:00:23 -07002796 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2797 if (mUploadMessage != null) return;
2798 mUploadMessage = uploadMsg;
2799 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2800 i.addCategory(Intent.CATEGORY_OPENABLE);
2801 i.setType("*/*");
2802 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2803 getString(R.string.choose_upload)), FILE_SELECTED);
2804 }
2805
2806 // -------------------------------------------------------------------------
2807 // Implement functions for DownloadListener
2808 // -------------------------------------------------------------------------
2809
The Android Open Source Project0c908882009-03-03 19:32:16 -08002810 /**
2811 * Notify the host application a download should be done, or that
2812 * the data should be streamed if a streaming viewer is available.
2813 * @param url The full url to the content that should be downloaded
2814 * @param contentDisposition Content-disposition http header, if
2815 * present.
2816 * @param mimetype The mimetype of the content reported by the server
2817 * @param contentLength The file size reported by the server
2818 */
2819 public void onDownloadStart(String url, String userAgent,
2820 String contentDisposition, String mimetype, long contentLength) {
2821 // if we're dealing wih A/V content that's not explicitly marked
2822 // for download, check if it's streamable.
2823 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002824 || !contentDisposition.regionMatches(
2825 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002826 // query the package manager to see if there's a registered handler
2827 // that matches.
2828 Intent intent = new Intent(Intent.ACTION_VIEW);
2829 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002830 ResolveInfo info = getPackageManager().resolveActivity(intent,
2831 PackageManager.MATCH_DEFAULT_ONLY);
2832 if (info != null) {
2833 ComponentName myName = getComponentName();
2834 // If we resolved to ourselves, we don't want to attempt to
2835 // load the url only to try and download it again.
2836 if (!myName.getPackageName().equals(
2837 info.activityInfo.packageName)
2838 || !myName.getClassName().equals(
2839 info.activityInfo.name)) {
2840 // someone (other than us) knows how to handle this mime
2841 // type with this scheme, don't download.
2842 try {
2843 startActivity(intent);
2844 return;
2845 } catch (ActivityNotFoundException ex) {
2846 if (LOGD_ENABLED) {
2847 Log.d(LOGTAG, "activity not found for " + mimetype
2848 + " over " + Uri.parse(url).getScheme(),
2849 ex);
2850 }
2851 // Best behavior is to fall back to a download in this
2852 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002853 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002854 }
2855 }
2856 }
2857 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2858 }
2859
2860 /**
2861 * Notify the host application a download should be done, even if there
2862 * is a streaming viewer available for thise type.
2863 * @param url The full url to the content that should be downloaded
2864 * @param contentDisposition Content-disposition http header, if
2865 * present.
2866 * @param mimetype The mimetype of the content reported by the server
2867 * @param contentLength The file size reported by the server
2868 */
2869 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2870 String contentDisposition, String mimetype, long contentLength) {
2871
2872 String filename = URLUtil.guessFileName(url,
2873 contentDisposition, mimetype);
2874
2875 // Check to see if we have an SDCard
2876 String status = Environment.getExternalStorageState();
2877 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2878 int title;
2879 String msg;
2880
2881 // Check to see if the SDCard is busy, same as the music app
2882 if (status.equals(Environment.MEDIA_SHARED)) {
2883 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2884 title = R.string.download_sdcard_busy_dlg_title;
2885 } else {
2886 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2887 title = R.string.download_no_sdcard_dlg_title;
2888 }
2889
2890 new AlertDialog.Builder(this)
2891 .setTitle(title)
2892 .setIcon(android.R.drawable.ic_dialog_alert)
2893 .setMessage(msg)
2894 .setPositiveButton(R.string.ok, null)
2895 .show();
2896 return;
2897 }
2898
2899 // java.net.URI is a lot stricter than KURL so we have to undo
2900 // KURL's percent-encoding and redo the encoding using java.net.URI.
2901 URI uri = null;
2902 try {
2903 // Undo the percent-encoding that KURL may have done.
2904 String newUrl = new String(URLUtil.decode(url.getBytes()));
2905 // Parse the url into pieces
2906 WebAddress w = new WebAddress(newUrl);
2907 String frag = null;
2908 String query = null;
2909 String path = w.mPath;
2910 // Break the path into path, query, and fragment
2911 if (path.length() > 0) {
2912 // Strip the fragment
2913 int idx = path.lastIndexOf('#');
2914 if (idx != -1) {
2915 frag = path.substring(idx + 1);
2916 path = path.substring(0, idx);
2917 }
2918 idx = path.lastIndexOf('?');
2919 if (idx != -1) {
2920 query = path.substring(idx + 1);
2921 path = path.substring(0, idx);
2922 }
2923 }
2924 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2925 query, frag);
2926 } catch (Exception e) {
2927 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2928 return;
2929 }
2930
2931 // XXX: Have to use the old url since the cookies were stored using the
2932 // old percent-encoded url.
2933 String cookies = CookieManager.getInstance().getCookie(url);
2934
2935 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002936 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2937 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2938 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2939 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002940 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002941 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002942 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002943 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2944 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2945 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2946 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2947 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002949 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002950 }
2951 if (mimetype == null) {
2952 // We must have long pressed on a link or image to download it. We
2953 // are not sure of the mimetype in this case, so do a head request
2954 new FetchUrlMimeType(this).execute(values);
2955 } else {
2956 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002957 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002958 }
2959
2960 }
2961
Grace Kloba22ac16e2009-10-07 18:00:23 -07002962 // -------------------------------------------------------------------------
2963
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 /**
2965 * Resets the lock icon. This method is called when we start a new load and
2966 * know the url to be loaded.
2967 */
2968 private void resetLockIcon(String url) {
2969 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002970 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 updateLockIconImage(LOCK_ICON_UNSECURE);
2972 }
2973
The Android Open Source Project0c908882009-03-03 19:32:16 -08002974 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002975 * Update the lock icon to correspond to our latest state.
2976 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002977 private void updateLockIconToLatest() {
2978 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002979 }
2980
2981 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002982 * Updates the lock-icon image in the title-bar.
2983 */
2984 private void updateLockIconImage(int lockIconType) {
2985 Drawable d = null;
2986 if (lockIconType == LOCK_ICON_SECURE) {
2987 d = mSecLockIcon;
2988 } else if (lockIconType == LOCK_ICON_MIXED) {
2989 d = mMixLockIcon;
2990 }
Leon Scroggins68579392009-09-15 15:31:54 -04002991 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002992 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002993 }
2994
2995 /**
2996 * Displays a page-info dialog.
2997 * @param tab The tab to show info about
2998 * @param fromShowSSLCertificateOnError The flag that indicates whether
2999 * this dialog was opened from the SSL-certificate-on-error dialog or
3000 * not. This is important, since we need to know whether to return to
3001 * the parent dialog or simply dismiss.
3002 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003003 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003004 final boolean fromShowSSLCertificateOnError) {
3005 final LayoutInflater factory = LayoutInflater
3006 .from(this);
3007
3008 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3009
3010 final WebView view = tab.getWebView();
3011
3012 String url = null;
3013 String title = null;
3014
3015 if (view == null) {
3016 url = tab.getUrl();
3017 title = tab.getTitle();
3018 } else if (view == mTabControl.getCurrentWebView()) {
3019 // Use the cached title and url if this is the current WebView
3020 url = mUrl;
3021 title = mTitle;
3022 } else {
3023 url = view.getUrl();
3024 title = view.getTitle();
3025 }
3026
3027 if (url == null) {
3028 url = "";
3029 }
3030 if (title == null) {
3031 title = "";
3032 }
3033
3034 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3035 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3036
3037 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003038 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039
3040 AlertDialog.Builder alertDialogBuilder =
3041 new AlertDialog.Builder(this)
3042 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3043 .setView(pageInfoView)
3044 .setPositiveButton(
3045 R.string.ok,
3046 new DialogInterface.OnClickListener() {
3047 public void onClick(DialogInterface dialog,
3048 int whichButton) {
3049 mPageInfoDialog = null;
3050 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051
3052 // if we came here from the SSL error dialog
3053 if (fromShowSSLCertificateOnError) {
3054 // go back to the SSL error dialog
3055 showSSLCertificateOnError(
3056 mSSLCertificateOnErrorView,
3057 mSSLCertificateOnErrorHandler,
3058 mSSLCertificateOnErrorError);
3059 }
3060 }
3061 })
3062 .setOnCancelListener(
3063 new DialogInterface.OnCancelListener() {
3064 public void onCancel(DialogInterface dialog) {
3065 mPageInfoDialog = null;
3066 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003067
3068 // if we came here from the SSL error dialog
3069 if (fromShowSSLCertificateOnError) {
3070 // go back to the SSL error dialog
3071 showSSLCertificateOnError(
3072 mSSLCertificateOnErrorView,
3073 mSSLCertificateOnErrorHandler,
3074 mSSLCertificateOnErrorError);
3075 }
3076 }
3077 });
3078
3079 // if we have a main top-level page SSL certificate set or a certificate
3080 // error
3081 if (fromShowSSLCertificateOnError ||
3082 (view != null && view.getCertificate() != null)) {
3083 // add a 'View Certificate' button
3084 alertDialogBuilder.setNeutralButton(
3085 R.string.view_certificate,
3086 new DialogInterface.OnClickListener() {
3087 public void onClick(DialogInterface dialog,
3088 int whichButton) {
3089 mPageInfoDialog = null;
3090 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091
3092 // if we came here from the SSL error dialog
3093 if (fromShowSSLCertificateOnError) {
3094 // go back to the SSL error dialog
3095 showSSLCertificateOnError(
3096 mSSLCertificateOnErrorView,
3097 mSSLCertificateOnErrorHandler,
3098 mSSLCertificateOnErrorError);
3099 } else {
3100 // otherwise, display the top-most certificate from
3101 // the chain
3102 if (view.getCertificate() != null) {
3103 showSSLCertificate(tab);
3104 }
3105 }
3106 }
3107 });
3108 }
3109
3110 mPageInfoDialog = alertDialogBuilder.show();
3111 }
3112
3113 /**
3114 * Displays the main top-level page SSL certificate dialog
3115 * (accessible from the Page-Info dialog).
3116 * @param tab The tab to show certificate for.
3117 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003118 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003119 final View certificateView =
3120 inflateCertificateView(tab.getWebView().getCertificate());
3121 if (certificateView == null) {
3122 return;
3123 }
3124
3125 LayoutInflater factory = LayoutInflater.from(this);
3126
3127 final LinearLayout placeholder =
3128 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3129
3130 LinearLayout ll = (LinearLayout) factory.inflate(
3131 R.layout.ssl_success, placeholder);
3132 ((TextView)ll.findViewById(R.id.success))
3133 .setText(R.string.ssl_certificate_is_valid);
3134
3135 mSSLCertificateView = tab;
3136 mSSLCertificateDialog =
3137 new AlertDialog.Builder(this)
3138 .setTitle(R.string.ssl_certificate).setIcon(
3139 R.drawable.ic_dialog_browser_certificate_secure)
3140 .setView(certificateView)
3141 .setPositiveButton(R.string.ok,
3142 new DialogInterface.OnClickListener() {
3143 public void onClick(DialogInterface dialog,
3144 int whichButton) {
3145 mSSLCertificateDialog = null;
3146 mSSLCertificateView = null;
3147
3148 showPageInfo(tab, false);
3149 }
3150 })
3151 .setOnCancelListener(
3152 new DialogInterface.OnCancelListener() {
3153 public void onCancel(DialogInterface dialog) {
3154 mSSLCertificateDialog = null;
3155 mSSLCertificateView = null;
3156
3157 showPageInfo(tab, false);
3158 }
3159 })
3160 .show();
3161 }
3162
3163 /**
3164 * Displays the SSL error certificate dialog.
3165 * @param view The target web-view.
3166 * @param handler The SSL error handler responsible for cancelling the
3167 * connection that resulted in an SSL error or proceeding per user request.
3168 * @param error The SSL error object.
3169 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003170 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003171 final WebView view, final SslErrorHandler handler, final SslError error) {
3172
3173 final View certificateView =
3174 inflateCertificateView(error.getCertificate());
3175 if (certificateView == null) {
3176 return;
3177 }
3178
3179 LayoutInflater factory = LayoutInflater.from(this);
3180
3181 final LinearLayout placeholder =
3182 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3183
3184 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3185 LinearLayout ll = (LinearLayout)factory
3186 .inflate(R.layout.ssl_warning, placeholder);
3187 ((TextView)ll.findViewById(R.id.warning))
3188 .setText(R.string.ssl_untrusted);
3189 }
3190
3191 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3192 LinearLayout ll = (LinearLayout)factory
3193 .inflate(R.layout.ssl_warning, placeholder);
3194 ((TextView)ll.findViewById(R.id.warning))
3195 .setText(R.string.ssl_mismatch);
3196 }
3197
3198 if (error.hasError(SslError.SSL_EXPIRED)) {
3199 LinearLayout ll = (LinearLayout)factory
3200 .inflate(R.layout.ssl_warning, placeholder);
3201 ((TextView)ll.findViewById(R.id.warning))
3202 .setText(R.string.ssl_expired);
3203 }
3204
3205 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3206 LinearLayout ll = (LinearLayout)factory
3207 .inflate(R.layout.ssl_warning, placeholder);
3208 ((TextView)ll.findViewById(R.id.warning))
3209 .setText(R.string.ssl_not_yet_valid);
3210 }
3211
3212 mSSLCertificateOnErrorHandler = handler;
3213 mSSLCertificateOnErrorView = view;
3214 mSSLCertificateOnErrorError = error;
3215 mSSLCertificateOnErrorDialog =
3216 new AlertDialog.Builder(this)
3217 .setTitle(R.string.ssl_certificate).setIcon(
3218 R.drawable.ic_dialog_browser_certificate_partially_secure)
3219 .setView(certificateView)
3220 .setPositiveButton(R.string.ok,
3221 new DialogInterface.OnClickListener() {
3222 public void onClick(DialogInterface dialog,
3223 int whichButton) {
3224 mSSLCertificateOnErrorDialog = null;
3225 mSSLCertificateOnErrorView = null;
3226 mSSLCertificateOnErrorHandler = null;
3227 mSSLCertificateOnErrorError = null;
3228
Grace Kloba22ac16e2009-10-07 18:00:23 -07003229 view.getWebViewClient().onReceivedSslError(
3230 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003231 }
3232 })
3233 .setNeutralButton(R.string.page_info_view,
3234 new DialogInterface.OnClickListener() {
3235 public void onClick(DialogInterface dialog,
3236 int whichButton) {
3237 mSSLCertificateOnErrorDialog = null;
3238
3239 // do not clear the dialog state: we will
3240 // need to show the dialog again once the
3241 // user is done exploring the page-info details
3242
3243 showPageInfo(mTabControl.getTabFromView(view),
3244 true);
3245 }
3246 })
3247 .setOnCancelListener(
3248 new DialogInterface.OnCancelListener() {
3249 public void onCancel(DialogInterface dialog) {
3250 mSSLCertificateOnErrorDialog = null;
3251 mSSLCertificateOnErrorView = null;
3252 mSSLCertificateOnErrorHandler = null;
3253 mSSLCertificateOnErrorError = null;
3254
Grace Kloba22ac16e2009-10-07 18:00:23 -07003255 view.getWebViewClient().onReceivedSslError(
3256 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003257 }
3258 })
3259 .show();
3260 }
3261
3262 /**
3263 * Inflates the SSL certificate view (helper method).
3264 * @param certificate The SSL certificate.
3265 * @return The resultant certificate view with issued-to, issued-by,
3266 * issued-on, expires-on, and possibly other fields set.
3267 * If the input certificate is null, returns null.
3268 */
3269 private View inflateCertificateView(SslCertificate certificate) {
3270 if (certificate == null) {
3271 return null;
3272 }
3273
3274 LayoutInflater factory = LayoutInflater.from(this);
3275
3276 View certificateView = factory.inflate(
3277 R.layout.ssl_certificate, null);
3278
3279 // issued to:
3280 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3281 if (issuedTo != null) {
3282 ((TextView) certificateView.findViewById(R.id.to_common))
3283 .setText(issuedTo.getCName());
3284 ((TextView) certificateView.findViewById(R.id.to_org))
3285 .setText(issuedTo.getOName());
3286 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3287 .setText(issuedTo.getUName());
3288 }
3289
3290 // issued by:
3291 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3292 if (issuedBy != null) {
3293 ((TextView) certificateView.findViewById(R.id.by_common))
3294 .setText(issuedBy.getCName());
3295 ((TextView) certificateView.findViewById(R.id.by_org))
3296 .setText(issuedBy.getOName());
3297 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3298 .setText(issuedBy.getUName());
3299 }
3300
3301 // issued on:
3302 String issuedOn = reformatCertificateDate(
3303 certificate.getValidNotBefore());
3304 ((TextView) certificateView.findViewById(R.id.issued_on))
3305 .setText(issuedOn);
3306
3307 // expires on:
3308 String expiresOn = reformatCertificateDate(
3309 certificate.getValidNotAfter());
3310 ((TextView) certificateView.findViewById(R.id.expires_on))
3311 .setText(expiresOn);
3312
3313 return certificateView;
3314 }
3315
3316 /**
3317 * Re-formats the certificate date (Date.toString()) string to
3318 * a properly localized date string.
3319 * @return Properly localized version of the certificate date string and
3320 * the original certificate date string if fails to localize.
3321 * If the original string is null, returns an empty string "".
3322 */
3323 private String reformatCertificateDate(String certificateDate) {
3324 String reformattedDate = null;
3325
3326 if (certificateDate != null) {
3327 Date date = null;
3328 try {
3329 date = java.text.DateFormat.getInstance().parse(certificateDate);
3330 } catch (ParseException e) {
3331 date = null;
3332 }
3333
3334 if (date != null) {
3335 reformattedDate =
3336 DateFormat.getDateFormat(this).format(date);
3337 }
3338 }
3339
3340 return reformattedDate != null ? reformattedDate :
3341 (certificateDate != null ? certificateDate : "");
3342 }
3343
3344 /**
3345 * Displays an http-authentication dialog.
3346 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003347 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003348 final String host, final String realm, final String title,
3349 final String name, final String password, int focusId) {
3350 LayoutInflater factory = LayoutInflater.from(this);
3351 final View v = factory
3352 .inflate(R.layout.http_authentication, null);
3353 if (name != null) {
3354 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3355 }
3356 if (password != null) {
3357 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3358 }
3359
3360 String titleText = title;
3361 if (titleText == null) {
3362 titleText = getText(R.string.sign_in_to).toString().replace(
3363 "%s1", host).replace("%s2", realm);
3364 }
3365
3366 mHttpAuthHandler = handler;
3367 AlertDialog dialog = new AlertDialog.Builder(this)
3368 .setTitle(titleText)
3369 .setIcon(android.R.drawable.ic_dialog_alert)
3370 .setView(v)
3371 .setPositiveButton(R.string.action,
3372 new DialogInterface.OnClickListener() {
3373 public void onClick(DialogInterface dialog,
3374 int whichButton) {
3375 String nm = ((EditText) v
3376 .findViewById(R.id.username_edit))
3377 .getText().toString();
3378 String pw = ((EditText) v
3379 .findViewById(R.id.password_edit))
3380 .getText().toString();
3381 BrowserActivity.this.setHttpAuthUsernamePassword
3382 (host, realm, nm, pw);
3383 handler.proceed(nm, pw);
3384 mHttpAuthenticationDialog = null;
3385 mHttpAuthHandler = null;
3386 }})
3387 .setNegativeButton(R.string.cancel,
3388 new DialogInterface.OnClickListener() {
3389 public void onClick(DialogInterface dialog,
3390 int whichButton) {
3391 handler.cancel();
3392 BrowserActivity.this.resetTitleAndRevertLockIcon();
3393 mHttpAuthenticationDialog = null;
3394 mHttpAuthHandler = null;
3395 }})
3396 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3397 public void onCancel(DialogInterface dialog) {
3398 handler.cancel();
3399 BrowserActivity.this.resetTitleAndRevertLockIcon();
3400 mHttpAuthenticationDialog = null;
3401 mHttpAuthHandler = null;
3402 }})
3403 .create();
3404 // Make the IME appear when the dialog is displayed if applicable.
3405 dialog.getWindow().setSoftInputMode(
3406 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3407 dialog.show();
3408 if (focusId != 0) {
3409 dialog.findViewById(focusId).requestFocus();
3410 } else {
3411 v.findViewById(R.id.username_edit).requestFocus();
3412 }
3413 mHttpAuthenticationDialog = dialog;
3414 }
3415
3416 public int getProgress() {
3417 WebView w = mTabControl.getCurrentWebView();
3418 if (w != null) {
3419 return w.getProgress();
3420 } else {
3421 return 100;
3422 }
3423 }
3424
3425 /**
3426 * Set HTTP authentication password.
3427 *
3428 * @param host The host for the password
3429 * @param realm The realm for the password
3430 * @param username The username for the password. If it is null, it means
3431 * password can't be saved.
3432 * @param password The password
3433 */
3434 public void setHttpAuthUsernamePassword(String host, String realm,
3435 String username,
3436 String password) {
3437 WebView w = mTabControl.getCurrentWebView();
3438 if (w != null) {
3439 w.setHttpAuthUsernamePassword(host, realm, username, password);
3440 }
3441 }
3442
3443 /**
3444 * connectivity manager says net has come or gone... inform the user
3445 * @param up true if net has come up, false if net has gone down
3446 */
3447 public void onNetworkToggle(boolean up) {
3448 if (up == mIsNetworkUp) {
3449 return;
3450 } else if (up) {
3451 mIsNetworkUp = true;
3452 if (mAlertDialog != null) {
3453 mAlertDialog.cancel();
3454 mAlertDialog = null;
3455 }
3456 } else {
3457 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003458 if (mInLoad) {
3459 createAndShowNetworkDialog();
3460 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003461 }
3462 WebView w = mTabControl.getCurrentWebView();
3463 if (w != null) {
3464 w.setNetworkAvailable(up);
3465 }
3466 }
3467
Grace Kloba22ac16e2009-10-07 18:00:23 -07003468 boolean isNetworkUp() {
3469 return mIsNetworkUp;
3470 }
3471
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003472 // This method shows the network dialog alerting the user that the net is
3473 // down. It will only show the dialog if mAlertDialog is null.
3474 private void createAndShowNetworkDialog() {
3475 if (mAlertDialog == null) {
3476 mAlertDialog = new AlertDialog.Builder(this)
3477 .setTitle(R.string.loadSuspendedTitle)
3478 .setMessage(R.string.loadSuspended)
3479 .setPositiveButton(R.string.ok, null)
3480 .show();
3481 }
3482 }
3483
The Android Open Source Project0c908882009-03-03 19:32:16 -08003484 @Override
3485 protected void onActivityResult(int requestCode, int resultCode,
3486 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003487 if (getTopWindow() == null) return;
3488
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489 switch (requestCode) {
3490 case COMBO_PAGE:
3491 if (resultCode == RESULT_OK && intent != null) {
3492 String data = intent.getAction();
3493 Bundle extras = intent.getExtras();
3494 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003495 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003496 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003497 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003499 dismissSubWindow(currentTab);
3500 if (data != null && data.length() != 0) {
3501 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502 }
3503 }
3504 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003505 // Deliberately fall through to PREFERENCES_PAGE, since the
3506 // same extra may be attached to the COMBO_PAGE
3507 case PREFERENCES_PAGE:
3508 if (resultCode == RESULT_OK && intent != null) {
3509 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3510 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3511 mTabControl.removeParentChildRelationShips();
3512 }
3513 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003514 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003515 // Choose a file from the file picker.
3516 case FILE_SELECTED:
3517 if (null == mUploadMessage) break;
3518 Uri result = intent == null || resultCode != RESULT_OK ? null
3519 : intent.getData();
3520 mUploadMessage.onReceiveValue(result);
3521 mUploadMessage = null;
3522 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003523 default:
3524 break;
3525 }
Leon Scroggins30444232009-09-04 18:36:20 -04003526 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003527 }
3528
3529 /*
3530 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003531 * menu to see the download window. It shows the download window on top of
3532 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003534 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003535 Intent intent = new Intent(this,
3536 BrowserDownloadPage.class);
3537 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003538 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539
3540 }
3541
Leon Scroggins160a7e72009-08-14 18:28:01 -04003542 /**
3543 * Open the Go page.
3544 * @param startWithHistory If true, open starting on the history tab.
3545 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003546 */
Leon Scroggins30444232009-09-04 18:36:20 -04003547 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003548 WebView current = mTabControl.getCurrentWebView();
3549 if (current == null) {
3550 return;
3551 }
3552 Intent intent = new Intent(this,
3553 CombinedBookmarkHistoryActivity.class);
3554 String title = current.getTitle();
3555 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003556 Bitmap thumbnail = createScreenshot(current);
3557
The Android Open Source Project0c908882009-03-03 19:32:16 -08003558 // Just in case the user opens bookmarks before a page finishes loading
3559 // so the current history item, and therefore the page, is null.
3560 if (null == url) {
3561 url = mLastEnteredUrl;
3562 // This can happen.
3563 if (null == url) {
3564 url = mSettings.getHomePage();
3565 }
3566 }
3567 // In case the web page has not yet received its associated title.
3568 if (title == null) {
3569 title = url;
3570 }
3571 intent.putExtra("title", title);
3572 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003573 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003574 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003575 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003576 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003577 if (startWithHistory) {
3578 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3579 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3580 }
3581 startActivityForResult(intent, COMBO_PAGE);
3582 }
3583
3584 // Called when loading from context menu or LOAD_URL message
3585 private void loadURL(WebView view, String url) {
3586 // In case the user enters nothing.
3587 if (url != null && url.length() != 0 && view != null) {
3588 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003589 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003590 view.loadUrl(url);
3591 }
3592 }
3593 }
3594
The Android Open Source Project0c908882009-03-03 19:32:16 -08003595 private String smartUrlFilter(Uri inUri) {
3596 if (inUri != null) {
3597 return smartUrlFilter(inUri.toString());
3598 }
3599 return null;
3600 }
3601
Feng Qianb34f87a2009-03-24 21:27:26 -07003602 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003603 "(?i)" + // switch on case insensitive matching
3604 "(" + // begin group for schema
3605 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003606 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003607 ")" +
3608 "(.*)" );
3609
3610 /**
3611 * Attempts to determine whether user input is a URL or search
3612 * terms. Anything with a space is passed to search.
3613 *
3614 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3615 * "Http://" converts to "http://"
3616 *
3617 * @return Original or modified URL
3618 *
3619 */
3620 String smartUrlFilter(String url) {
3621
3622 String inUrl = url.trim();
3623 boolean hasSpace = inUrl.indexOf(' ') != -1;
3624
3625 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3626 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003627 // force scheme to lowercase
3628 String scheme = matcher.group(1);
3629 String lcScheme = scheme.toLowerCase();
3630 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003631 inUrl = lcScheme + matcher.group(2);
3632 }
3633 if (hasSpace) {
3634 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003635 }
3636 return inUrl;
3637 }
3638 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003639 // FIXME: Is this the correct place to add to searches?
3640 // what if someone else calls this function?
3641 int shortcut = parseUrlShortcut(inUrl);
3642 if (shortcut != SHORTCUT_INVALID) {
3643 Browser.addSearchUrl(mResolver, inUrl);
3644 String query = inUrl.substring(2);
3645 switch (shortcut) {
3646 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003647 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003648 case SHORTCUT_WIKIPEDIA_SEARCH:
3649 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3650 case SHORTCUT_DICTIONARY_SEARCH:
3651 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3652 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003653 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003654 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 }
3656 }
3657 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003658 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 return URLUtil.guessUrl(inUrl);
3660 }
3661 }
3662
3663 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003664 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 }
3666
Ben Murdochbff2d602009-07-01 20:19:05 +01003667 /* package */ void setShouldShowErrorConsole(boolean flag) {
3668 if (flag == mShouldShowErrorConsole) {
3669 // Nothing to do.
3670 return;
3671 }
3672
3673 mShouldShowErrorConsole = flag;
3674
Grace Kloba22ac16e2009-10-07 18:00:23 -07003675 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3676 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003677
3678 if (flag) {
3679 // Setting the show state of the console will cause it's the layout to be inflated.
3680 if (errorConsole.numberOfErrors() > 0) {
3681 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3682 } else {
3683 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3684 }
3685
3686 // Now we can add it to the main view.
3687 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003688 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003689 ViewGroup.LayoutParams.WRAP_CONTENT));
3690 } else {
3691 mErrorConsoleContainer.removeView(errorConsole);
3692 }
3693
3694 }
3695
Grace Kloba22ac16e2009-10-07 18:00:23 -07003696 boolean shouldShowErrorConsole() {
3697 return mShouldShowErrorConsole;
3698 }
3699
Andrei Popescu163ab742009-10-20 17:58:23 +01003700 private void setStatusBarVisibility(boolean visible) {
3701 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3702 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3703 }
3704
Andrei Popescu56199cc2010-01-12 22:39:16 +00003705
3706 private void sendNetworkType(String type, String subtype) {
3707 WebView w = mTabControl.getCurrentWebView();
3708 if (w != null) {
3709 w.setNetworkType(type, subtype);
3710 }
3711 }
3712
Grace Klobaeb6eef42009-09-15 17:56:32 -07003713 final static int LOCK_ICON_UNSECURE = 0;
3714 final static int LOCK_ICON_SECURE = 1;
3715 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716
The Android Open Source Project0c908882009-03-03 19:32:16 -08003717 private BrowserSettings mSettings;
3718 private TabControl mTabControl;
3719 private ContentResolver mResolver;
3720 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003721 private View mCustomView;
3722 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003723 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003724
3725 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3726 // view, we should rewrite this.
3727 private int mCurrentMenuState = 0;
3728 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003729 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730 private static final int EMPTY_MENU = -1;
3731 private Menu mMenu;
3732
3733 private FindDialog mFindDialog;
3734 // Used to prevent chording to result in firing two shortcuts immediately
3735 // one after another. Fixes bug 1211714.
3736 boolean mCanChord;
3737
3738 private boolean mInLoad;
3739 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003740 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003741
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 private boolean mActivityInPause = true;
3743
3744 private boolean mMenuIsDown;
3745
The Android Open Source Project0c908882009-03-03 19:32:16 -08003746 private static boolean mInTrace;
3747
3748 // Performance probe
3749 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3750 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3751 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3752 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3753 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3754 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3755 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3756 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3757 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3758 };
3759
3760 private long mStart;
3761 private long mProcessStart;
3762 private long mUserStart;
3763 private long mSystemStart;
3764 private long mIdleStart;
3765 private long mIrqStart;
3766
3767 private long mUiStart;
3768
3769 private Drawable mMixLockIcon;
3770 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003771
3772 /* hold a ref so we can auto-cancel if necessary */
3773 private AlertDialog mAlertDialog;
3774
3775 // Wait for credentials before loading google.com
3776 private ProgressDialog mCredsDlg;
3777
3778 // The up-to-date URL and title (these can be different from those stored
3779 // in WebView, since it takes some time for the information in WebView to
3780 // get updated)
3781 private String mUrl;
3782 private String mTitle;
3783
3784 // As PageInfo has different style for landscape / portrait, we have
3785 // to re-open it when configuration changed
3786 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003787 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003788 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3789 // dialog, we should not just dismiss it, but should get back to the
3790 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003791 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003792
3793 // as SSLCertificateOnError has different style for landscape / portrait,
3794 // we have to re-open it when configuration changed
3795 private AlertDialog mSSLCertificateOnErrorDialog;
3796 private WebView mSSLCertificateOnErrorView;
3797 private SslErrorHandler mSSLCertificateOnErrorHandler;
3798 private SslError mSSLCertificateOnErrorError;
3799
3800 // as SSLCertificate has different style for landscape / portrait, we
3801 // have to re-open it when configuration changed
3802 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003803 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003804
3805 // as HttpAuthentication has different style for landscape / portrait, we
3806 // have to re-open it when configuration changed
3807 private AlertDialog mHttpAuthenticationDialog;
3808 private HttpAuthHandler mHttpAuthHandler;
3809
3810 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3811 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003812 ViewGroup.LayoutParams.MATCH_PARENT,
3813 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003814 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3815 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003816 ViewGroup.LayoutParams.MATCH_PARENT,
3817 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003818 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003819 // Google search
3820 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003821 // Wikipedia search
3822 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3823 // Dictionary search
3824 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3825 // Google Mobile Local search
3826 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3827
3828 final static String QUERY_PLACE_HOLDER = "%s";
3829
3830 // "source" parameter for Google search through search key
3831 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3832 // "source" parameter for Google search through goto menu
3833 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3834 // "source" parameter for Google search through simplily type
3835 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3836 // "source" parameter for Google search suggested by the browser
3837 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3838 // "source" parameter for Google search from unknown source
3839 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3840
3841 private final static String LOGTAG = "browser";
3842
The Android Open Source Project0c908882009-03-03 19:32:16 -08003843 private String mLastEnteredUrl;
3844
3845 private PowerManager.WakeLock mWakeLock;
3846 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3847
3848 private Toast mStopToast;
3849
Leon Scroggins68579392009-09-15 15:31:54 -04003850 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003851
Ben Murdochbff2d602009-07-01 20:19:05 +01003852 private LinearLayout mErrorConsoleContainer = null;
3853 private boolean mShouldShowErrorConsole = false;
3854
The Android Open Source Project0c908882009-03-03 19:32:16 -08003855 // As the ids are dynamically created, we can't guarantee that they will
3856 // be in sequence, so this static array maps ids to a window number.
3857 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3858 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3859 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3860 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3861
3862 // monitor platform changes
3863 private IntentFilter mNetworkStateChangedFilter;
3864 private BroadcastReceiver mNetworkStateIntentReceiver;
3865
Grace Klobab4da0ad2009-05-14 14:45:40 -07003866 private BroadcastReceiver mPackageInstallationReceiver;
3867
The Android Open Source Project0c908882009-03-03 19:32:16 -08003868 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003869 final static int COMBO_PAGE = 1;
3870 final static int DOWNLOAD_PAGE = 2;
3871 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003872 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003873
Andrei Popescu540035d2009-09-18 18:59:20 +01003874 // the default <video> poster
3875 private Bitmap mDefaultVideoPoster;
3876 // the video progress view
3877 private View mVideoProgressView;
3878
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003879 /**
3880 * A UrlData class to abstract how the content will be set to WebView.
3881 * This base class uses loadUrl to show the content.
3882 */
3883 private static class UrlData {
3884 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003885 byte[] mPostData;
3886
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003887 UrlData(String url) {
3888 this.mUrl = url;
3889 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003890
3891 void setPostData(byte[] postData) {
3892 mPostData = postData;
3893 }
3894
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003895 boolean isEmpty() {
3896 return mUrl == null || mUrl.length() == 0;
3897 }
3898
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003899 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003900 if (mPostData != null) {
3901 webView.postUrl(mUrl, mPostData);
3902 } else {
3903 webView.loadUrl(mUrl);
3904 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003905 }
3906 };
3907
3908 /**
3909 * A subclass of UrlData class that can display inlined content using
3910 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3911 */
3912 private static class InlinedUrlData extends UrlData {
3913 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3914 super(failUrl);
3915 mInlined = inlined;
3916 mMimeType = mimeType;
3917 mEncoding = encoding;
3918 }
3919 String mMimeType;
3920 String mInlined;
3921 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003922 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003923 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003924 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003925 }
3926
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003927 @Override
3928 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003929 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3930 }
3931 }
3932
Leon Scroggins1f005d32009-08-10 17:36:42 -04003933 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003934}