blob: df71e9e7d59c170f7c8bd572fee0c79e7b517d4b [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
Doug Zongker716d4f52010-01-21 14:35:23 -0800112import com.google.android.gsf.GoogleLoginServiceConstants;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800113
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
Mike Reedd334bf52010-01-26 15:21:44 -0500245 // enable this to test the browser in 32bit
246 if (false) {
247 getWindow().setFormat(PixelFormat.RGBX_8888);
248 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
249 }
250
The Android Open Source Project0c908882009-03-03 19:32:16 -0800251 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
252
253 mResolver = getContentResolver();
254
Grace Kloba0923d692009-09-23 21:37:25 -0700255 // If this was a web search request, pass it on to the default web
256 // search provider and finish this activity.
257 if (handleWebSearchIntent(getIntent())) {
258 finish();
259 return;
260 }
261
The Android Open Source Project0c908882009-03-03 19:32:16 -0800262 mSecLockIcon = Resources.getSystem().getDrawable(
263 android.R.drawable.ic_secure);
264 mMixLockIcon = Resources.getSystem().getDrawable(
265 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800266
Leon Scroggins81db3662009-06-04 17:45:11 -0400267 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
268 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400269 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
270 .inflate(R.layout.custom_screen, null);
271 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
272 R.id.main_content);
273 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
274 .findViewById(R.id.error_console);
275 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
276 .findViewById(R.id.fullscreen_custom_content);
277 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400278 mTitleBar = new TitleBar(this);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400279 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800280
281 // Create the tab control and our initial tab
282 mTabControl = new TabControl(this);
283
284 // Open the icon database and retain all the bookmark urls for favicons
285 retainIconsOnStartup();
286
287 // Keep a settings instance handy.
288 mSettings = BrowserSettings.getInstance();
289 mSettings.setTabControl(mTabControl);
290 mSettings.loadFromDb(this);
291
292 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
293 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
294
Grace Klobaa34f6862009-07-31 16:28:17 -0700295 /* enables registration for changes in network status from
296 http stack */
297 mNetworkStateChangedFilter = new IntentFilter();
298 mNetworkStateChangedFilter.addAction(
299 ConnectivityManager.CONNECTIVITY_ACTION);
300 mNetworkStateIntentReceiver = new BroadcastReceiver() {
301 @Override
302 public void onReceive(Context context, Intent intent) {
303 if (intent.getAction().equals(
304 ConnectivityManager.CONNECTIVITY_ACTION)) {
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700305 boolean noConnectivity = intent.getBooleanExtra(
306 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Andrei Popescu56199cc2010-01-12 22:39:16 +0000307 if (!noConnectivity) {
308 NetworkInfo info = intent.getParcelableExtra(
309 ConnectivityManager.EXTRA_NETWORK_INFO);
310 String typeName = info.getTypeName();
311 String subtypeName = info.getSubtypeName();
312 sendNetworkType(typeName.toLowerCase(),
313 (subtypeName != null ? subtypeName.toLowerCase() : ""));
314 }
Robert Greenwalt7d899d62009-10-23 10:33:48 -0700315 onNetworkToggle(!noConnectivity);
Grace Klobaa34f6862009-07-31 16:28:17 -0700316 }
317 }
318 };
319
Grace Kloba615c6c92009-08-03 10:22:44 -0700320 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
321 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 filter.addDataScheme("package");
323 mPackageInstallationReceiver = new BroadcastReceiver() {
324 @Override
325 public void onReceive(Context context, Intent intent) {
326 final String action = intent.getAction();
327 final String packageName = intent.getData()
328 .getSchemeSpecificPart();
329 final boolean replacing = intent.getBooleanExtra(
330 Intent.EXTRA_REPLACING, false);
331 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
332 // if it is replacing, refreshPlugins() when adding
333 return;
334 }
335 PackageManager pm = BrowserActivity.this.getPackageManager();
336 PackageInfo pkgInfo = null;
337 try {
338 pkgInfo = pm.getPackageInfo(packageName,
339 PackageManager.GET_PERMISSIONS);
340 } catch (PackageManager.NameNotFoundException e) {
341 return;
342 }
343 if (pkgInfo != null) {
344 String permissions[] = pkgInfo.requestedPermissions;
345 if (permissions == null) {
346 return;
347 }
348 boolean permissionOk = false;
349 for (String permit : permissions) {
350 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
351 permissionOk = true;
352 break;
353 }
354 }
355 if (permissionOk) {
356 PluginManager.getInstance(BrowserActivity.this)
357 .refreshPlugins(
358 Intent.ACTION_PACKAGE_ADDED
359 .equals(action));
360 }
361 }
362 }
363 };
364 registerReceiver(mPackageInstallationReceiver, filter);
365
The Android Open Source Project0c908882009-03-03 19:32:16 -0800366 if (!mTabControl.restoreState(icicle)) {
367 // clear up the thumbnail directory if we can't restore the state as
368 // none of the files in the directory are referenced any more.
369 new ClearThumbnails().execute(
370 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700371 // there is no quit on Android. But if we can't restore the state,
372 // we can treat it as a new Browser, remove the old session cookies.
373 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800374 final Intent intent = getIntent();
375 final Bundle extra = intent.getExtras();
376 // Create an initial tab.
377 // If the intent is ACTION_VIEW and data is not null, the Browser is
378 // invoked to view the content by another application. In this case,
379 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700380 UrlData urlData = getUrlDataFromIntent(intent);
381
Grace Kloba22ac16e2009-10-07 18:00:23 -0700382 final Tab t = mTabControl.createNewTab(
The Android Open Source Project0c908882009-03-03 19:32:16 -0800383 Intent.ACTION_VIEW.equals(intent.getAction()) &&
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700384 intent.getData() != null,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700385 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800386 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800387 attachTabToContentView(t);
388 WebView webView = t.getWebView();
389 if (extra != null) {
390 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
391 if (scale > 0 && scale <= 1000) {
392 webView.setInitialScale(scale);
393 }
394 }
395 // If we are not restoring from an icicle, then there is a high
396 // likely hood this is the first run. So, check to see if the
397 // homepage needs to be configured and copy any plugins from our
398 // asset directory to the data partition.
399 if ((extra == null || !extra.getBoolean("testing"))
400 && !mSettings.isLoginInitialized()) {
Fred Quintana752b6562009-12-18 10:18:26 -0800401 startReadOfGoogleAccounts();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800402 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800403
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700404 if (urlData.isEmpty()) {
Leon Scroggins30444232009-09-04 18:36:20 -0400405 if (mSettings.isLoginInitialized()) {
406 webView.loadUrl(mSettings.getHomePage());
407 } else {
408 waitForCredentials();
409 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800410 } else {
Grace Kloba81678d92009-06-30 07:09:56 -0700411 if (extra != null) {
412 urlData.setPostData(extra
413 .getByteArray(Browser.EXTRA_POST_DATA));
414 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700415 urlData.loadIn(webView);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800416 }
417 } else {
418 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400419 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800420 attachTabToContentView(mTabControl.getCurrentTab());
421 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700422
Feng Qianb3c02da2009-06-29 15:58:08 -0700423 // Read JavaScript flags if it exists.
424 String jsFlags = mSettings.getJsFlags();
425 if (jsFlags.trim().length() != 0) {
426 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
427 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800428 }
429
430 @Override
431 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700432 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800433 // When a tab is closed on exit, the current tab index is set to -1.
434 // Reset before proceed as Browser requires the current tab to be set.
435 if (current == null) {
436 // Try to reset the tab in case the index was incorrect.
437 current = mTabControl.getTab(0);
438 if (current == null) {
439 // No tabs at all so just ignore this intent.
440 return;
441 }
442 mTabControl.setCurrentTab(current);
443 attachTabToContentView(current);
444 resetTitleAndIcon(current.getWebView());
445 }
446 final String action = intent.getAction();
447 final int flags = intent.getFlags();
448 if (Intent.ACTION_MAIN.equals(action) ||
449 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
450 // just resume the browser
451 return;
452 }
453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
456 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
460 return;
461 }
462
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800466 }
Grace Kloba81678d92009-06-30 07:09:56 -0700467 urlData.setPostData(intent
468 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700469
Grace Klobacc634032009-07-28 15:58:19 -0700470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
472 if (Intent.ACTION_VIEW.equals(action)
473 && !getPackageName().equals(appId)
474 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700475 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700476 if (appTab != null) {
477 Log.i(LOGTAG, "Reusing tab for " + appId);
478 // Dismiss the subwindow if applicable.
479 dismissSubWindow(appTab);
480 // Since we might kill the WebView, remove it from the
481 // content view first.
482 removeTabFromContentView(appTab);
483 // Recreate the main WebView after destroying the old one.
484 // If the WebView has the same original url and is on that
485 // page, it can be reused.
486 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700487 mTabControl.recreateWebView(appTab, urlData.mUrl);
Ben Murdochbff2d602009-07-01 20:19:05 +0100488
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 switchToTab(mTabControl.getTabIndex(appTab));
491 if (needsLoad) {
492 urlData.loadIn(appTab.getWebView());
493 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700494 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400495 // If the tab was the current tab, we have to attach
496 // it to the view system again.
497 attachTabToContentView(appTab);
498 if (needsLoad) {
499 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700500 }
501 }
502 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400503 } else {
504 // No matching application tab, try to find a regular tab
505 // with a matching url.
506 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400507 if (appTab != null) {
508 if (current != appTab) {
509 switchToTab(mTabControl.getTabIndex(appTab));
510 }
511 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400512 } else {
513 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
514 // will be opened in a new tab unless we have reached
515 // MAX_TABS. Then the url will be opened in the current
516 // tab. If a new tab is created, it will have "true" for
517 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400518 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400519 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700520 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800521 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800522 if (!urlData.isEmpty()
523 && urlData.mUrl.startsWith("about:debug")) {
524 if ("about:debug.dom".equals(urlData.mUrl)) {
525 current.getWebView().dumpDomTree(false);
526 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
527 current.getWebView().dumpDomTree(true);
528 } else if ("about:debug.render".equals(urlData.mUrl)) {
529 current.getWebView().dumpRenderTree(false);
530 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
531 current.getWebView().dumpRenderTree(true);
532 } else if ("about:debug.display".equals(urlData.mUrl)) {
533 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800534 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
535 int index = urlData.mUrl.codePointAt(16) - '0';
536 if (index <= 0 || index > 9) {
537 current.getWebView().setDragTracker(null);
538 } else {
539 current.getWebView().setDragTracker(new MeshTracker(index));
540 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800541 } else {
542 mSettings.toggleDebugSettings();
543 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800544 return;
545 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400546 // Get rid of the subwindow if it exists
547 dismissSubWindow(current);
548 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800549 }
550 }
551 }
552
Satish Sampath565505b2009-05-29 15:37:27 +0100553 private int parseUrlShortcut(String url) {
554 if (url == null) return SHORTCUT_INVALID;
555
556 // FIXME: quick search, need to be customized by setting
557 if (url.length() > 2 && url.charAt(1) == ' ') {
558 switch (url.charAt(0)) {
559 case 'g': return SHORTCUT_GOOGLE_SEARCH;
560 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
561 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
562 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
563 }
564 }
565 return SHORTCUT_INVALID;
566 }
567
568 /**
569 * Launches the default web search activity with the query parameters if the given intent's data
570 * are identified as plain search terms and not URLs/shortcuts.
571 * @return true if the intent was handled and web search activity was launched, false if not.
572 */
573 private boolean handleWebSearchIntent(Intent intent) {
574 if (intent == null) return false;
575
576 String url = null;
577 final String action = intent.getAction();
578 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700579 Uri data = intent.getData();
580 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100581 } else if (Intent.ACTION_SEARCH.equals(action)
582 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
583 || Intent.ACTION_WEB_SEARCH.equals(action)) {
584 url = intent.getStringExtra(SearchManager.QUERY);
585 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100586 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
587 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100588 }
589
590 /**
591 * Launches the default web search activity with the query parameters if the given url string
592 * was identified as plain search terms and not URL/shortcut.
593 * @return true if the request was handled and web search activity was launched, false if not.
594 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100595 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100596 if (inUrl == null) return false;
597
598 // In general, we shouldn't modify URL from Intent.
599 // But currently, we get the user-typed URL from search box as well.
600 String url = fixUrl(inUrl).trim();
601
602 // URLs and site specific search shortcuts are handled by the regular flow of control, so
603 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800604 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100605 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100606 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
607 return false;
608 }
609
610 Browser.updateVisitedHistory(mResolver, url, false);
611 Browser.addSearchUrl(mResolver, url);
612
613 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
614 intent.addCategory(Intent.CATEGORY_DEFAULT);
615 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100616 if (appData != null) {
617 intent.putExtra(SearchManager.APP_DATA, appData);
618 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100619 if (extraData != null) {
620 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
621 }
Grace Klobacc634032009-07-28 15:58:19 -0700622 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
Satish Sampath565505b2009-05-29 15:37:27 +0100623 startActivity(intent);
624
625 return true;
626 }
627
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700628 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800629 String url = null;
630 if (intent != null) {
631 final String action = intent.getAction();
632 if (Intent.ACTION_VIEW.equals(action)) {
633 url = smartUrlFilter(intent.getData());
634 if (url != null && url.startsWith("content:")) {
635 /* Append mimetype so webview knows how to display */
636 String mimeType = intent.resolveType(getContentResolver());
637 if (mimeType != null) {
638 url += "?" + mimeType;
639 }
640 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700641 if ("inline:".equals(url)) {
642 return new InlinedUrlData(
643 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
644 intent.getType(),
645 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
646 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
647 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800648 } else if (Intent.ACTION_SEARCH.equals(action)
649 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
650 || Intent.ACTION_WEB_SEARCH.equals(action)) {
651 url = intent.getStringExtra(SearchManager.QUERY);
652 if (url != null) {
653 mLastEnteredUrl = url;
Leon Scrogginsb4464432009-11-25 12:37:50 -0500654 Browser.updateVisitedHistory(mResolver, url, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800655 // In general, we shouldn't modify URL from Intent.
656 // But currently, we get the user-typed URL from search box as well.
657 url = fixUrl(url);
658 url = smartUrlFilter(url);
659 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
660 if (url.contains(searchSource)) {
661 String source = null;
662 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
663 if (appData != null) {
664 source = appData.getString(SearchManager.SOURCE);
665 }
666 if (TextUtils.isEmpty(source)) {
667 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
668 }
669 url = url.replace(searchSource, "&source=android-"+source+"&");
670 }
671 }
672 }
673 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700674 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800675 }
676
677 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400678 // FIXME: Converting the url to lower case
679 // duplicates functionality in smartUrlFilter().
680 // However, changing all current callers of fixUrl to
681 // call smartUrlFilter in addition may have unwanted
682 // consequences, and is deferred for now.
683 int colon = inUrl.indexOf(':');
684 boolean allLower = true;
685 for (int index = 0; index < colon; index++) {
686 char ch = inUrl.charAt(index);
687 if (!Character.isLetter(ch)) {
688 break;
689 }
690 allLower &= Character.isLowerCase(ch);
691 if (index == colon - 1 && !allLower) {
692 inUrl = inUrl.substring(0, colon).toLowerCase()
693 + inUrl.substring(colon);
694 }
695 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800696 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
697 return inUrl;
698 if (inUrl.startsWith("http:") ||
699 inUrl.startsWith("https:")) {
700 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
701 inUrl = inUrl.replaceFirst("/", "//");
702 } else inUrl = inUrl.replaceFirst(":", "://");
703 }
704 return inUrl;
705 }
706
Grace Kloba22ac16e2009-10-07 18:00:23 -0700707 @Override
708 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800709 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700710 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800711 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
712 }
713
714 if (!mActivityInPause) {
715 Log.e(LOGTAG, "BrowserActivity is already resumed.");
716 return;
717 }
718
Mike Reed7bfa63b2009-05-28 11:08:32 -0400719 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800720 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400721 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800722
723 if (mWakeLock.isHeld()) {
724 mHandler.removeMessages(RELEASE_WAKELOCK);
725 mWakeLock.release();
726 }
727
728 if (mCredsDlg != null) {
729 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
730 // In case credential request never comes back
731 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
732 }
733 }
734
735 registerReceiver(mNetworkStateIntentReceiver,
736 mNetworkStateChangedFilter);
737 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800738 }
739
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400740 /**
741 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400742 * would change its appearance, use a different TitleBar to show overlayed
743 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400744 */
745 private TitleBar mFakeTitleBar;
746
747 /**
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400748 * Holder for the fake title bar. It will have a foreground shadow, as well
749 * as a white background, so the fake title bar looks like the real one.
750 */
751 private ViewGroup mFakeTitleBarHolder;
752
753 /**
754 * Layout parameters for the fake title bar within mFakeTitleBarHolder
755 */
756 private FrameLayout.LayoutParams mFakeTitleBarParams
757 = new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800758 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400759 ViewGroup.LayoutParams.WRAP_CONTENT);
760 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400761 * Keeps track of whether the options menu is open. This is important in
762 * determining whether to show or hide the title bar overlay.
763 */
764 private boolean mOptionsMenuOpen;
765
766 /**
767 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
768 * of whether the configuration has changed. The first onMenuOpened call
769 * after a configuration change is simply a reopening of the same menu
770 * (i.e. mIconView did not change).
771 */
772 private boolean mConfigChanged;
773
774 /**
775 * Whether or not the options menu is in its smaller, icon menu form. When
776 * true, we want the title bar overlay to be up. When false, we do not.
777 * Only meaningful if mOptionsMenuOpen is true.
778 */
779 private boolean mIconView;
780
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400781 @Override
782 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400783 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
784 if (mOptionsMenuOpen) {
785 if (mConfigChanged) {
786 // We do not need to make any changes to the state of the
787 // title bar, since the only thing that happened was a
788 // change in orientation
789 mConfigChanged = false;
790 } else {
791 if (mIconView) {
792 // Switching the menu to expanded view, so hide the
793 // title bar.
794 hideFakeTitleBar();
795 mIconView = false;
796 } else {
797 // Switching the menu back to icon view, so show the
798 // title bar once again.
799 showFakeTitleBar();
800 mIconView = true;
801 }
802 }
803 } else {
804 // The options menu is closed, so open it, and show the title
805 showFakeTitleBar();
806 mOptionsMenuOpen = true;
807 mConfigChanged = false;
808 mIconView = true;
809 }
810 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400811 return true;
812 }
813
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400814 /**
815 * Special class used exclusively for the shadow drawn underneath the fake
816 * title bar. The shadow does not need to be drawn if the WebView
817 * underneath is scrolled to the top, because it will draw directly on top
818 * of the embedded shadow.
819 */
820 private static class Shadow extends View {
821 private WebView mWebView;
822
823 public Shadow(Context context, AttributeSet attrs) {
824 super(context, attrs);
825 }
826
827 public void setWebView(WebView view) {
828 mWebView = view;
829 }
830
831 @Override
832 public void draw(Canvas canvas) {
833 // In general onDraw is the method to override, but we care about
834 // whether or not the background gets drawn, which happens in draw()
835 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
836 super.draw(canvas);
837 }
838 // Need to invalidate so that if the scroll position changes, we
839 // still draw as appropriate.
840 invalidate();
841 }
842 }
843
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400844 private void showFakeTitleBar() {
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400845 final View decor = getWindow().peekDecorView();
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400846 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Patrick Scottf8de8ec2009-09-21 16:37:29 -0400847 && !mActivityInPause && decor != null
848 && decor.getWindowToken() != null) {
Cary Clarka0464552009-09-29 13:00:45 -0400849 Rect visRect = new Rect();
850 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
851 if (LOGD_ENABLED) {
852 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
853 }
854 return;
855 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400856
857 WindowManager manager
858 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
859
860 // Add the title bar to the window manager so it can receive touches
861 // while the menu is up
862 WindowManager.LayoutParams params
863 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800864 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400865 ViewGroup.LayoutParams.WRAP_CONTENT,
866 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
867 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400868 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400869 params.gravity = Gravity.TOP;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400870 WebView mainView = mTabControl.getCurrentWebView();
Leon Scroggins68549862009-09-21 16:02:01 -0400871 boolean atTop = mainView != null && mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400872 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400873 // XXX : Without providing an offset, the fake title bar will be
874 // placed underneath the status bar. Use the global visible rect
875 // of mBrowserFrameLayout to determine the bottom of the status bar
Cary Clarka0464552009-09-29 13:00:45 -0400876 params.y = visRect.top;
Leon Scroggins68549862009-09-21 16:02:01 -0400877 // Add a holder for the title bar. It also holds a shadow to show
878 // below the title bar.
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400879 if (mFakeTitleBarHolder == null) {
880 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
881 .inflate(R.layout.title_bar_bg, null);
882 }
Leon Scrogginsb94bf272009-09-25 15:22:08 -0400883 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
884 R.id.shadow);
885 shadow.setWebView(mainView);
Leon Scroggins68549862009-09-21 16:02:01 -0400886 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400887 manager.addView(mFakeTitleBarHolder, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400888 }
889 }
890
891 @Override
892 public void onOptionsMenuClosed(Menu menu) {
893 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400894 if (!mInLoad) {
895 hideFakeTitleBar();
896 } else if (!mIconView) {
897 // The page is currently loading, and we are in expanded mode, so
898 // we were not showing the menu. Show it once again. It will be
899 // removed when the page finishes.
900 showFakeTitleBar();
901 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400902 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700903
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400904 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400905 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400906 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
907 mFakeTitleBarHolder.getLayoutParams();
908 WebView mainView = mTabControl.getCurrentWebView();
909 // Although we decided whether or not to animate based on the current
910 // scroll position, the scroll position may have changed since the
911 // fake title bar was displayed. Make sure it has the appropriate
912 // animation/lack thereof before removing.
913 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400914 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400915 WindowManager manager
916 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Leon Scroggins20329572009-09-23 17:42:41 -0400917 manager.updateViewLayout(mFakeTitleBarHolder, params);
Leon Scrogginsd8fd2fc2009-09-16 11:12:09 -0400918 mFakeTitleBarHolder.removeView(mFakeTitleBar);
919 manager.removeView(mFakeTitleBarHolder);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400920 }
921
The Android Open Source Project0c908882009-03-03 19:32:16 -0800922 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400923 * Special method for the fake title bar to call when displaying its context
924 * menu, since it is in its own Window, and its parent does not show a
925 * context menu.
926 */
927 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400928 if (null == mTitleBar.getParent()) {
929 return;
930 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400931 openContextMenu(mTitleBar);
932 }
933
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400934 @Override
935 public void onContextMenuClosed(Menu menu) {
936 super.onContextMenuClosed(menu);
937 if (mInLoad) {
938 showFakeTitleBar();
939 }
940 }
941
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400942 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800943 * onSaveInstanceState(Bundle map)
944 * onSaveInstanceState is called right before onStop(). The map contains
945 * the saved state.
946 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700947 @Override
948 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700949 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
951 }
952 // the default implementation requires each view to have an id. As the
953 // browser handles the state itself and it doesn't use id for the views,
954 // don't call the default implementation. Otherwise it will trigger the
955 // warning like this, "couldn't save which view has focus because the
956 // focused view XXX has no id".
957
958 // Save all the tabs
959 mTabControl.saveState(outState);
960 }
961
Grace Kloba22ac16e2009-10-07 18:00:23 -0700962 @Override
963 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800964 super.onPause();
965
966 if (mActivityInPause) {
967 Log.e(LOGTAG, "BrowserActivity is already paused.");
968 return;
969 }
970
Mike Reed7bfa63b2009-05-28 11:08:32 -0400971 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800972 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400973 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800974 mWakeLock.acquire();
975 mHandler.sendMessageDelayed(mHandler
976 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
977 }
978
979 // Clear the credentials toast if it is up
980 if (mCredsDlg != null && mCredsDlg.isShowing()) {
981 mCredsDlg.dismiss();
982 }
983 mCredsDlg = null;
984
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400985 // FIXME: This removes the active tabs page and resets the menu to
986 // MAIN_MENU. A better solution might be to do this work in onNewIntent
987 // but then we would need to save it in onSaveInstanceState and restore
988 // it in onCreate/onRestoreInstanceState
989 if (mActiveTabsPage != null) {
990 removeActiveTabPage(true);
991 }
992
The Android Open Source Project0c908882009-03-03 19:32:16 -0800993 cancelStopToast();
994
995 // unregister network state listener
996 unregisterReceiver(mNetworkStateIntentReceiver);
997 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800998 }
999
Grace Kloba22ac16e2009-10-07 18:00:23 -07001000 @Override
1001 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001002 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001003 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1004 }
1005 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -07001006
Leon Scroggins8d5fa432009-10-02 15:55:59 -04001007 if (mUploadMessage != null) {
1008 mUploadMessage.onReceiveValue(null);
1009 mUploadMessage = null;
1010 }
1011
Grace Kloba0923d692009-09-23 21:37:25 -07001012 if (mTabControl == null) return;
1013
Grace Kloba1fc98a32009-10-21 13:23:08 -07001014 // Remove the fake title bar if it is there
1015 hideFakeTitleBar();
1016
The Android Open Source Project0c908882009-03-03 19:32:16 -08001017 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -07001018 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001019 if (t != null) {
1020 dismissSubWindow(t);
1021 removeTabFromContentView(t);
1022 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 // Destroy all the tabs
1024 mTabControl.destroy();
1025 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001026
Grace Klobab4da0ad2009-05-14 14:45:40 -07001027 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001028 }
1029
1030 @Override
1031 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04001032 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001033 super.onConfigurationChanged(newConfig);
1034
1035 if (mPageInfoDialog != null) {
1036 mPageInfoDialog.dismiss();
1037 showPageInfo(
1038 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05001039 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001040 }
1041 if (mSSLCertificateDialog != null) {
1042 mSSLCertificateDialog.dismiss();
1043 showSSLCertificate(
1044 mSSLCertificateView);
1045 }
1046 if (mSSLCertificateOnErrorDialog != null) {
1047 mSSLCertificateOnErrorDialog.dismiss();
1048 showSSLCertificateOnError(
1049 mSSLCertificateOnErrorView,
1050 mSSLCertificateOnErrorHandler,
1051 mSSLCertificateOnErrorError);
1052 }
1053 if (mHttpAuthenticationDialog != null) {
1054 String title = ((TextView) mHttpAuthenticationDialog
1055 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1056 .toString();
1057 String name = ((TextView) mHttpAuthenticationDialog
1058 .findViewById(R.id.username_edit)).getText().toString();
1059 String password = ((TextView) mHttpAuthenticationDialog
1060 .findViewById(R.id.password_edit)).getText().toString();
1061 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1062 .getId();
1063 mHttpAuthenticationDialog.dismiss();
1064 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1065 name, password, focusId);
1066 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001067 }
1068
Grace Kloba22ac16e2009-10-07 18:00:23 -07001069 @Override
1070 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001071 super.onLowMemory();
1072 mTabControl.freeMemory();
1073 }
1074
Mike Reed7bfa63b2009-05-28 11:08:32 -04001075 private boolean resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001076 Tab tab = mTabControl.getCurrentTab();
1077 boolean inLoad = tab.inLoad();
1078 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001079 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001080 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001081 if (w != null) {
1082 w.resumeTimers();
1083 }
1084 return true;
1085 } else {
1086 return false;
1087 }
1088 }
1089
Mike Reed7bfa63b2009-05-28 11:08:32 -04001090 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001091 Tab tab = mTabControl.getCurrentTab();
1092 boolean inLoad = tab.inLoad();
1093 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001094 CookieSyncManager.getInstance().stopSync();
1095 WebView w = mTabControl.getCurrentWebView();
1096 if (w != null) {
1097 w.pauseTimers();
1098 }
1099 return true;
1100 } else {
1101 return false;
1102 }
1103 }
1104
Leon Scroggins1f005d32009-08-10 17:36:42 -04001105 // FIXME: Do we want to call this when loading google for the first time?
The Android Open Source Project0c908882009-03-03 19:32:16 -08001106 /*
1107 * This function is called when we are launching for the first time. We
1108 * are waiting for the login credentials before loading Google home
1109 * pages. This way the user will be logged in straight away.
1110 */
1111 private void waitForCredentials() {
1112 // Show a toast
1113 mCredsDlg = new ProgressDialog(this);
1114 mCredsDlg.setIndeterminate(true);
1115 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1116 // If the user cancels the operation, then cancel the Google
1117 // Credentials request.
1118 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1119 mCredsDlg.show();
1120
1121 // We set a timeout for the retrieval of credentials in onResume()
1122 // as that is when we have freed up some CPU time to get
1123 // the login credentials.
1124 }
1125
1126 /*
1127 * If we have received the credentials or we have timed out and we are
1128 * showing the credentials dialog, then it is time to move on.
1129 */
1130 private void resumeAfterCredentials() {
1131 if (mCredsDlg == null) {
1132 return;
1133 }
1134
1135 // Clear the toast
1136 if (mCredsDlg.isShowing()) {
1137 mCredsDlg.dismiss();
1138 }
1139 mCredsDlg = null;
1140
1141 // Clear any pending timeout
1142 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1143
1144 // Load the page
1145 WebView w = mTabControl.getCurrentWebView();
1146 if (w != null) {
1147 w.loadUrl(mSettings.getHomePage());
1148 }
1149
1150 // Update the settings, need to do this last as it can take a moment
1151 // to persist the settings. In the mean time we could be loading
1152 // content.
1153 mSettings.setLoginInitialized(this);
1154 }
1155
1156 // Open the icon database and retain all the icons for visited sites.
1157 private void retainIconsOnStartup() {
1158 final WebIconDatabase db = WebIconDatabase.getInstance();
1159 db.open(getDir("icons", 0).getPath());
1160 try {
1161 Cursor c = Browser.getAllBookmarks(mResolver);
1162 if (!c.moveToFirst()) {
1163 c.deactivate();
1164 return;
1165 }
1166 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1167 do {
1168 String url = c.getString(urlIndex);
1169 db.retainIconForPageUrl(url);
1170 } while (c.moveToNext());
1171 c.deactivate();
1172 } catch (IllegalStateException e) {
1173 Log.e(LOGTAG, "retainIconsOnStartup", e);
1174 }
1175 }
1176
1177 // Helper method for getting the top window.
1178 WebView getTopWindow() {
1179 return mTabControl.getCurrentTopWebView();
1180 }
1181
Grace Kloba22ac16e2009-10-07 18:00:23 -07001182 TabControl getTabControl() {
1183 return mTabControl;
1184 }
1185
The Android Open Source Project0c908882009-03-03 19:32:16 -08001186 @Override
1187 public boolean onCreateOptionsMenu(Menu menu) {
1188 super.onCreateOptionsMenu(menu);
1189
1190 MenuInflater inflater = getMenuInflater();
1191 inflater.inflate(R.menu.browser, menu);
1192 mMenu = menu;
1193 updateInLoadMenuItems();
1194 return true;
1195 }
1196
1197 /**
1198 * As the menu can be open when loading state changes
1199 * we must manually update the state of the stop/reload menu
1200 * item
1201 */
1202 private void updateInLoadMenuItems() {
1203 if (mMenu == null) {
1204 return;
1205 }
1206 MenuItem src = mInLoad ?
1207 mMenu.findItem(R.id.stop_menu_id):
1208 mMenu.findItem(R.id.reload_menu_id);
1209 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1210 dest.setIcon(src.getIcon());
1211 dest.setTitle(src.getTitle());
1212 }
1213
1214 @Override
1215 public boolean onContextItemSelected(MenuItem item) {
1216 // chording is not an issue with context menus, but we use the same
1217 // options selector, so set mCanChord to true so we can access them.
1218 mCanChord = true;
1219 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001220 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001222 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001223 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001224 Tab currentTab = mTabControl.getCurrentTab();
1225 if (null == currentTab) {
1226 result = false;
1227 break;
1228 }
1229 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001230 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001231 result = false;
1232 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001233 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001234 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001235 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001236 // -- Browser context menu
1237 case R.id.open_context_menu_id:
1238 case R.id.open_newtab_context_menu_id:
1239 case R.id.bookmark_context_menu_id:
1240 case R.id.save_link_context_menu_id:
1241 case R.id.share_link_context_menu_id:
1242 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001243 final WebView webView = getTopWindow();
1244 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001245 result = false;
1246 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001247 }
1248 final HashMap hrefMap = new HashMap();
1249 hrefMap.put("webview", webView);
1250 final Message msg = mHandler.obtainMessage(
1251 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001252 webView.requestFocusNodeHref(msg);
1253 break;
1254
1255 default:
1256 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001257 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001258 }
1259 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001260 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001261 }
1262
1263 private Bundle createGoogleSearchSourceBundle(String source) {
1264 Bundle bundle = new Bundle();
1265 bundle.putString(SearchManager.SOURCE, source);
1266 return bundle;
1267 }
1268
1269 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001270 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001271 */
1272 @Override
1273 public boolean onSearchRequested() {
Leon Scroggins68579392009-09-15 15:31:54 -04001274 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001275 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001276 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001277 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001278 return true;
1279 }
1280
1281 @Override
1282 public void startSearch(String initialQuery, boolean selectInitialQuery,
1283 Bundle appSearchData, boolean globalSearch) {
1284 if (appSearchData == null) {
1285 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1286 }
1287 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1288 }
1289
Leon Scroggins1f005d32009-08-10 17:36:42 -04001290 /**
1291 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1292 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001293 * @param index Index of the tab to change to, as defined by
1294 * mTabControl.getTabIndex(Tab t).
1295 * @return boolean True if we successfully switched to a different tab. If
1296 * the indexth tab is null, or if that tab is the same as
1297 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001298 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001299 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001300 Tab tab = mTabControl.getTab(index);
1301 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001302 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001303 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001304 }
1305 if (currentTab != null) {
1306 // currentTab may be null if it was just removed. In that case,
1307 // we do not need to remove it
1308 removeTabFromContentView(currentTab);
1309 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001310 mTabControl.setCurrentTab(tab);
1311 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001312 resetTitleIconAndProgress();
1313 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001314 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001315 }
1316
Grace Kloba22ac16e2009-10-07 18:00:23 -07001317 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001318 return openTabAndShow(mSettings.getHomePage(), false, null);
1319 }
1320
Leon Scroggins1f005d32009-08-10 17:36:42 -04001321 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001322 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001323 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001324 // This is the last tab. Open a new one, with the home
1325 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001326 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001327 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001328 return;
1329 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001330 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001331 int indexToShow = -1;
1332 if (parent != null) {
1333 indexToShow = mTabControl.getTabIndex(parent);
1334 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001335 final int currentIndex = mTabControl.getCurrentIndex();
1336 // Try to move to the tab to the right
1337 indexToShow = currentIndex + 1;
1338 if (indexToShow > mTabControl.getTabCount() - 1) {
1339 // Try to move to the tab to the left
1340 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001341 }
1342 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001343 if (switchToTab(indexToShow)) {
1344 // Close window
1345 closeTab(current);
1346 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001347 }
1348
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001349 private ActiveTabsPage mActiveTabsPage;
1350
1351 /**
1352 * Remove the active tabs page.
1353 * @param needToAttach If true, the active tabs page did not attach a tab
1354 * to the content view, so we need to do that here.
1355 */
1356 /* package */ void removeActiveTabPage(boolean needToAttach) {
1357 mContentView.removeView(mActiveTabsPage);
1358 mActiveTabsPage = null;
1359 mMenuState = R.id.MAIN_MENU;
1360 if (needToAttach) {
1361 attachTabToContentView(mTabControl.getCurrentTab());
1362 }
1363 getTopWindow().requestFocus();
1364 }
1365
The Android Open Source Project0c908882009-03-03 19:32:16 -08001366 @Override
1367 public boolean onOptionsItemSelected(MenuItem item) {
1368 if (!mCanChord) {
1369 // The user has already fired a shortcut with this hold down of the
1370 // menu key.
1371 return false;
1372 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001373 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001374 return false;
1375 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001376 if (mMenuIsDown) {
1377 // The shortcut action consumes the MENU. Even if it is still down,
1378 // it won't trigger the next shortcut action. In the case of the
1379 // shortcut action triggering a new activity, like Bookmarks, we
1380 // won't get onKeyUp for MENU. So it is important to reset it here.
1381 mMenuIsDown = false;
1382 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001383 switch (item.getItemId()) {
1384 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001385 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001386 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001387 break;
1388
Leon Scroggins64b80f32009-08-07 12:03:34 -04001389 case R.id.goto_menu_id:
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001390 onSearchRequested();
1391 break;
1392
1393 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001394 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001395 break;
1396
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001397 case R.id.active_tabs_menu_id:
1398 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1399 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001400 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001401 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1402 mActiveTabsPage.requestFocus();
1403 mMenuState = EMPTY_MENU;
1404 break;
1405
Leon Scroggins1f005d32009-08-10 17:36:42 -04001406 case R.id.add_bookmark_menu_id:
1407 Intent i = new Intent(BrowserActivity.this,
1408 AddBookmarkPage.class);
1409 WebView w = getTopWindow();
1410 i.putExtra("url", w.getUrl());
1411 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001412 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001413 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001414 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001415 break;
1416
1417 case R.id.stop_reload_menu_id:
1418 if (mInLoad) {
1419 stopLoading();
1420 } else {
1421 getTopWindow().reload();
1422 }
1423 break;
1424
1425 case R.id.back_menu_id:
1426 getTopWindow().goBack();
1427 break;
1428
1429 case R.id.forward_menu_id:
1430 getTopWindow().goForward();
1431 break;
1432
1433 case R.id.close_menu_id:
1434 // Close the subwindow if it exists.
1435 if (mTabControl.getCurrentSubWindow() != null) {
1436 dismissSubWindow(mTabControl.getCurrentTab());
1437 break;
1438 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001439 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001440 break;
1441
1442 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001443 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001444 if (current != null) {
1445 dismissSubWindow(current);
1446 current.getWebView().loadUrl(mSettings.getHomePage());
1447 }
1448 break;
1449
1450 case R.id.preferences_menu_id:
1451 Intent intent = new Intent(this,
1452 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001453 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1454 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001455 startActivityForResult(intent, PREFERENCES_PAGE);
1456 break;
1457
1458 case R.id.find_menu_id:
1459 if (null == mFindDialog) {
1460 mFindDialog = new FindDialog(this);
1461 }
1462 mFindDialog.setWebView(getTopWindow());
1463 mFindDialog.show();
1464 mMenuState = EMPTY_MENU;
1465 break;
1466
1467 case R.id.select_text_id:
1468 getTopWindow().emulateShiftHeld();
1469 break;
1470 case R.id.page_info_menu_id:
1471 showPageInfo(mTabControl.getCurrentTab(), false);
1472 break;
1473
1474 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001475 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001476 break;
1477
Leon Scroggins96afcb12009-12-10 12:35:56 -05001478 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001479 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001480 Tab currentTab = mTabControl.getCurrentTab();
1481 if (null == currentTab) {
1482 mCanChord = false;
1483 return false;
1484 }
1485 currentTab.populatePickerData();
1486 sharePage(this, currentTab.getTitle(),
1487 currentTab.getUrl(), currentTab.getFavicon(),
1488 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001489 break;
1490
1491 case R.id.dump_nav_menu_id:
1492 getTopWindow().debugDump();
1493 break;
1494
1495 case R.id.zoom_in_menu_id:
1496 getTopWindow().zoomIn();
1497 break;
1498
1499 case R.id.zoom_out_menu_id:
1500 getTopWindow().zoomOut();
1501 break;
1502
1503 case R.id.view_downloads_menu_id:
1504 viewDownloads(null);
1505 break;
1506
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 case R.id.window_one_menu_id:
1508 case R.id.window_two_menu_id:
1509 case R.id.window_three_menu_id:
1510 case R.id.window_four_menu_id:
1511 case R.id.window_five_menu_id:
1512 case R.id.window_six_menu_id:
1513 case R.id.window_seven_menu_id:
1514 case R.id.window_eight_menu_id:
1515 {
1516 int menuid = item.getItemId();
1517 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1518 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001519 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001520 if (desiredTab != null &&
1521 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001522 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001523 }
1524 break;
1525 }
1526 }
1527 }
1528 break;
1529
1530 default:
1531 if (!super.onOptionsItemSelected(item)) {
1532 return false;
1533 }
1534 // Otherwise fall through.
1535 }
1536 mCanChord = false;
1537 return true;
1538 }
1539
1540 public void closeFind() {
1541 mMenuState = R.id.MAIN_MENU;
1542 }
1543
Grace Kloba22ac16e2009-10-07 18:00:23 -07001544 @Override
1545 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001546 // This happens when the user begins to hold down the menu key, so
1547 // allow them to chord to get a shortcut.
1548 mCanChord = true;
1549 // Note: setVisible will decide whether an item is visible; while
1550 // setEnabled() will decide whether an item is enabled, which also means
1551 // whether the matching shortcut key will function.
1552 super.onPrepareOptionsMenu(menu);
1553 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001554 case EMPTY_MENU:
1555 if (mCurrentMenuState != mMenuState) {
1556 menu.setGroupVisible(R.id.MAIN_MENU, false);
1557 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1558 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001559 }
1560 break;
1561 default:
1562 if (mCurrentMenuState != mMenuState) {
1563 menu.setGroupVisible(R.id.MAIN_MENU, true);
1564 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1565 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001566 }
1567 final WebView w = getTopWindow();
1568 boolean canGoBack = false;
1569 boolean canGoForward = false;
1570 boolean isHome = false;
1571 if (w != null) {
1572 canGoBack = w.canGoBack();
1573 canGoForward = w.canGoForward();
1574 isHome = mSettings.getHomePage().equals(w.getUrl());
1575 }
1576 final MenuItem back = menu.findItem(R.id.back_menu_id);
1577 back.setEnabled(canGoBack);
1578
1579 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1580 home.setEnabled(!isHome);
1581
1582 menu.findItem(R.id.forward_menu_id)
1583 .setEnabled(canGoForward);
1584
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001585 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001586 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001587
The Android Open Source Project0c908882009-03-03 19:32:16 -08001588 // decide whether to show the share link option
1589 PackageManager pm = getPackageManager();
1590 Intent send = new Intent(Intent.ACTION_SEND);
1591 send.setType("text/plain");
1592 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1593 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1594
The Android Open Source Project0c908882009-03-03 19:32:16 -08001595 boolean isNavDump = mSettings.isNavDump();
1596 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1597 nav.setVisible(isNavDump);
1598 nav.setEnabled(isNavDump);
1599 break;
1600 }
1601 mCurrentMenuState = mMenuState;
1602 return true;
1603 }
1604
1605 @Override
1606 public void onCreateContextMenu(ContextMenu menu, View v,
1607 ContextMenuInfo menuInfo) {
1608 WebView webview = (WebView) v;
1609 WebView.HitTestResult result = webview.getHitTestResult();
1610 if (result == null) {
1611 return;
1612 }
1613
1614 int type = result.getType();
1615 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1616 Log.w(LOGTAG,
1617 "We should not show context menu when nothing is touched");
1618 return;
1619 }
1620 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1621 // let TextView handles context menu
1622 return;
1623 }
1624
1625 // Note, http://b/issue?id=1106666 is requesting that
1626 // an inflated menu can be used again. This is not available
1627 // yet, so inflate each time (yuk!)
1628 MenuInflater inflater = getMenuInflater();
1629 inflater.inflate(R.menu.browsercontext, menu);
1630
1631 // Show the correct menu group
1632 String extra = result.getExtra();
1633 menu.setGroupVisible(R.id.PHONE_MENU,
1634 type == WebView.HitTestResult.PHONE_TYPE);
1635 menu.setGroupVisible(R.id.EMAIL_MENU,
1636 type == WebView.HitTestResult.EMAIL_TYPE);
1637 menu.setGroupVisible(R.id.GEO_MENU,
1638 type == WebView.HitTestResult.GEO_TYPE);
1639 menu.setGroupVisible(R.id.IMAGE_MENU,
1640 type == WebView.HitTestResult.IMAGE_TYPE
1641 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1642 menu.setGroupVisible(R.id.ANCHOR_MENU,
1643 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1644 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1645
1646 // Setup custom handling depending on the type
1647 switch (type) {
1648 case WebView.HitTestResult.PHONE_TYPE:
1649 menu.setHeaderTitle(Uri.decode(extra));
1650 menu.findItem(R.id.dial_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_TEL + extra)));
1653 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1654 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001655 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001656 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1657 addIntent);
1658 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1659 new Copy(extra));
1660 break;
1661
1662 case WebView.HitTestResult.EMAIL_TYPE:
1663 menu.setHeaderTitle(extra);
1664 menu.findItem(R.id.email_context_menu_id).setIntent(
1665 new Intent(Intent.ACTION_VIEW, Uri
1666 .parse(WebView.SCHEME_MAILTO + extra)));
1667 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1668 new Copy(extra));
1669 break;
1670
1671 case WebView.HitTestResult.GEO_TYPE:
1672 menu.setHeaderTitle(extra);
1673 menu.findItem(R.id.map_context_menu_id).setIntent(
1674 new Intent(Intent.ACTION_VIEW, Uri
1675 .parse(WebView.SCHEME_GEO
1676 + URLEncoder.encode(extra))));
1677 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1678 new Copy(extra));
1679 break;
1680
1681 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1682 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1683 TextView titleView = (TextView) LayoutInflater.from(this)
1684 .inflate(android.R.layout.browser_link_context_header,
1685 null);
1686 titleView.setText(extra);
1687 menu.setHeaderView(titleView);
1688 // decide whether to show the open link in new tab option
1689 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001690 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001691 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1692 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 PackageManager pm = getPackageManager();
1694 Intent send = new Intent(Intent.ACTION_SEND);
1695 send.setType("text/plain");
1696 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1697 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1698 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1699 break;
1700 }
1701 // otherwise fall through to handle image part
1702 case WebView.HitTestResult.IMAGE_TYPE:
1703 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1704 menu.setHeaderTitle(extra);
1705 }
1706 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1708 menu.findItem(R.id.download_context_menu_id).
1709 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001710 menu.findItem(R.id.set_wallpaper_context_menu_id).
1711 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001712 break;
1713
1714 default:
1715 Log.w(LOGTAG, "We should not get here.");
1716 break;
1717 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001718 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001719 }
1720
The Android Open Source Project0c908882009-03-03 19:32:16 -08001721 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001722 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001723 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001724 // Attach the container that contains the main WebView and any other UI
1725 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001726 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001727
1728 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001729 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001730 if (errorConsole.numberOfErrors() == 0) {
1731 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1732 } else {
1733 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1734 }
1735
1736 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001737 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001738 ViewGroup.LayoutParams.WRAP_CONTENT));
1739 }
1740
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001741 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001742 view.setEmbeddedTitleBar(mTitleBar);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001743 // Request focus on the top window.
1744 t.getTopWindow().requestFocus();
1745 }
1746
1747 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001748 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001749 t.attachSubWindow(mContentView);
1750 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001751 }
1752
1753 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001754 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001755 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001756 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001757
Grace Kloba22ac16e2009-10-07 18:00:23 -07001758 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1759 if (errorConsole != null) {
1760 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001761 }
1762
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001763 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001764 if (view != null) {
1765 view.setEmbeddedTitleBar(null);
1766 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001767 }
1768
1769 // Remove the sub window if it exists. Also called by TabControl when the
1770 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001771 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001772 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001773 // dismiss the subwindow. This will destroy the WebView.
1774 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001775 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001776 }
1777
Leon Scroggins1f005d32009-08-10 17:36:42 -04001778 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001779 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001780 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001781 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001782 }
1783
1784 // This method does a ton of stuff. It will attempt to create a new tab
1785 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001786 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001787 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1788 String appId) {
1789 final Tab currentTab = mTabControl.getCurrentTab();
1790 if (mTabControl.canCreateNewTab()) {
1791 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1792 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001793 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001794 // If the last tab was removed from the active tabs page, currentTab
1795 // will be null.
1796 if (currentTab != null) {
1797 removeTabFromContentView(currentTab);
1798 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001799 // We must set the new tab as the current tab to reflect the old
1800 // animation behavior.
1801 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001802 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001803 if (!urlData.isEmpty()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001804 urlData.loadIn(webview);
1805 }
1806 return tab;
1807 } else {
1808 // Get rid of the subwindow if it exists
1809 dismissSubWindow(currentTab);
1810 if (!urlData.isEmpty()) {
1811 // Load the given url.
1812 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001813 }
1814 }
Grace Klobac9181842009-04-14 08:53:22 -07001815 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001816 }
1817
Grace Kloba22ac16e2009-10-07 18:00:23 -07001818 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001819 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001820 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001821 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001822 WebView view = t.getWebView();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001823 view.loadUrl(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001824 }
Grace Klobac9181842009-04-14 08:53:22 -07001825 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001826 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001827 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001828 }
1829 }
1830
1831 private class Copy implements OnMenuItemClickListener {
1832 private CharSequence mText;
1833
1834 public boolean onMenuItemClick(MenuItem item) {
1835 copy(mText);
1836 return true;
1837 }
1838
1839 public Copy(CharSequence toCopy) {
1840 mText = toCopy;
1841 }
1842 }
1843
1844 private class Download implements OnMenuItemClickListener {
1845 private String mText;
1846
1847 public boolean onMenuItemClick(MenuItem item) {
1848 onDownloadStartNoStream(mText, null, null, null, -1);
1849 return true;
1850 }
1851
1852 public Download(String toDownload) {
1853 mText = toDownload;
1854 }
1855 }
1856
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001857 private class SetAsWallpaper extends Thread implements
1858 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1859 private URL mUrl;
1860 private ProgressDialog mWallpaperProgress;
1861 private boolean mCanceled = false;
1862
1863 public SetAsWallpaper(String url) {
1864 try {
1865 mUrl = new URL(url);
1866 } catch (MalformedURLException e) {
1867 mUrl = null;
1868 }
1869 }
1870
1871 public void onCancel(DialogInterface dialog) {
1872 mCanceled = true;
1873 }
1874
1875 public boolean onMenuItemClick(MenuItem item) {
1876 if (mUrl != null) {
1877 // The user may have tried to set a image with a large file size as their
1878 // background so it may take a few moments to perform the operation. Display
1879 // a progress spinner while it is working.
1880 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1881 mWallpaperProgress.setIndeterminate(true);
1882 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1883 mWallpaperProgress.setCancelable(true);
1884 mWallpaperProgress.setOnCancelListener(this);
1885 mWallpaperProgress.show();
1886 start();
1887 }
1888 return true;
1889 }
1890
1891 public void run() {
1892 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1893 try {
1894 // TODO: This will cause the resource to be downloaded again, when we
1895 // should in most cases be able to grab it from the cache. To fix this
1896 // we should query WebCore to see if we can access a cached version and
1897 // instead open an input stream on that. This pattern could also be used
1898 // in the download manager where the same problem exists.
1899 InputStream inputstream = mUrl.openStream();
1900 if (inputstream != null) {
1901 setWallpaper(inputstream);
1902 }
1903 } catch (IOException e) {
1904 Log.e(LOGTAG, "Unable to set new wallpaper");
1905 // Act as though the user canceled the operation so we try to
1906 // restore the old wallpaper.
1907 mCanceled = true;
1908 }
1909
1910 if (mCanceled) {
1911 // Restore the old wallpaper if the user cancelled whilst we were setting
1912 // the new wallpaper.
1913 int width = oldWallpaper.getIntrinsicWidth();
1914 int height = oldWallpaper.getIntrinsicHeight();
1915 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1916 Canvas canvas = new Canvas(bm);
1917 oldWallpaper.setBounds(0, 0, width, height);
1918 oldWallpaper.draw(canvas);
1919 try {
1920 setWallpaper(bm);
1921 } catch (IOException e) {
1922 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1923 }
1924 mCanceled = false;
1925 }
1926
1927 if (mWallpaperProgress.isShowing()) {
1928 mWallpaperProgress.dismiss();
1929 }
1930 }
1931 }
1932
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 private void copy(CharSequence text) {
1934 try {
1935 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1936 if (clip != null) {
1937 clip.setClipboardText(text);
1938 }
1939 } catch (android.os.RemoteException e) {
1940 Log.e(LOGTAG, "Copy failed", e);
1941 }
1942 }
1943
1944 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001945 * Resets the browser title-view to whatever it must be
1946 * (for example, if we had a loading error)
1947 * When we have a new page, we call resetTitle, when we
1948 * have to reset the titlebar to whatever it used to be
1949 * (for example, if the user chose to stop loading), we
1950 * call resetTitleAndRevertLockIcon.
1951 */
1952 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001953 mTabControl.getCurrentTab().revertLockIcon();
1954 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955 resetTitleIconAndProgress();
1956 }
1957
1958 /**
1959 * Reset the title, favicon, and progress.
1960 */
1961 private void resetTitleIconAndProgress() {
1962 WebView current = mTabControl.getCurrentWebView();
1963 if (current == null) {
1964 return;
1965 }
1966 resetTitleAndIcon(current);
1967 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001968 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001969 }
1970
1971 // Reset the title and the icon based on the given item.
1972 private void resetTitleAndIcon(WebView view) {
1973 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1974 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001975 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001976 setFavicon(item.getFavicon());
1977 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001978 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001979 setFavicon(null);
1980 }
1981 }
1982
1983 /**
1984 * Sets a title composed of the URL and the title string.
1985 * @param url The URL of the site being loaded.
1986 * @param title The title of the site being loaded.
1987 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001988 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001989 mUrl = url;
1990 mTitle = title;
1991
Leon Scroggins68579392009-09-15 15:31:54 -04001992 mTitleBar.setTitleAndUrl(title, url);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001993 mFakeTitleBar.setTitleAndUrl(title, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 }
1995
1996 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001997 * @param url The URL to build a title version of the URL from.
1998 * @return The title version of the URL or null if fails.
1999 * The title version of the URL can be either the URL hostname,
2000 * or the hostname with an "https://" prefix (for secure URLs),
2001 * or an empty string if, for example, the URL in question is a
2002 * file:// URL with no hostname.
2003 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002004 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002005 String titleUrl = null;
2006
2007 if (url != null) {
2008 try {
2009 // parse the url string
2010 URL urlObj = new URL(url);
2011 if (urlObj != null) {
2012 titleUrl = "";
2013
2014 String protocol = urlObj.getProtocol();
2015 String host = urlObj.getHost();
2016
2017 if (host != null && 0 < host.length()) {
2018 titleUrl = host;
2019 if (protocol != null) {
2020 // if a secure site, add an "https://" prefix!
2021 if (protocol.equalsIgnoreCase("https")) {
2022 titleUrl = protocol + "://" + host;
2023 }
2024 }
2025 }
2026 }
2027 } catch (MalformedURLException e) {}
2028 }
2029
2030 return titleUrl;
2031 }
2032
2033 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002034 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04002035 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002036 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002037 }
2038
2039 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002040 * Close the tab, remove its associated title bar, and adjust mTabControl's
2041 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04002042 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002043 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002044 int currentIndex = mTabControl.getCurrentIndex();
2045 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04002046 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04002047 if (currentIndex >= removeIndex && currentIndex != 0) {
2048 currentIndex--;
2049 }
2050 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01002051 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002052 }
2053
2054 private void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002055 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002056 if (current == null) {
2057 /*
2058 * Instead of finishing the activity, simply push this to the back
2059 * of the stack and let ActivityManager to choose the foreground
2060 * activity. As BrowserActivity is singleTask, it will be always the
2061 * root of the task. So we can use either true or false for
2062 * moveTaskToBack().
2063 */
2064 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07002065 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002066 }
2067 WebView w = current.getWebView();
2068 if (w.canGoBack()) {
2069 w.goBack();
2070 } else {
2071 // Check to see if we are closing a window that was created by
2072 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002073 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002074 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002075 switchToTab(mTabControl.getTabIndex(parent));
2076 // Now we close the other tab
2077 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002078 } else {
2079 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002080 // force the tab's inLoad() to be false as we are going to
2081 // either finish the activity or remove the tab. This will
2082 // ensure pauseWebViewTimers() taking action.
2083 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 if (mTabControl.getTabCount() == 1) {
2085 finish();
2086 return;
2087 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002088 // call pauseWebViewTimers() now, we won't be able to call
2089 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002090 // Temporarily change mActivityInPause to be true as
2091 // pauseWebViewTimers() will do nothing if mActivityInPause
2092 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002093 boolean savedState = mActivityInPause;
2094 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002095 Log.e(LOGTAG, "BrowserActivity is already paused "
2096 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002097 }
2098 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002099 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002100 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 removeTabFromContentView(current);
2102 mTabControl.removeTab(current);
2103 }
2104 /*
2105 * Instead of finishing the activity, simply push this to the back
2106 * of the stack and let ActivityManager to choose the foreground
2107 * activity. As BrowserActivity is singleTask, it will be always the
2108 * root of the task. So we can use either true or false for
2109 * moveTaskToBack().
2110 */
2111 moveTaskToBack(true);
2112 }
2113 }
2114 }
2115
Grace Kloba22ac16e2009-10-07 18:00:23 -07002116 boolean isMenuDown() {
2117 return mMenuIsDown;
2118 }
2119
Grace Kloba5942df02009-09-18 11:48:29 -07002120 @Override
2121 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002122 // Even if MENU is already held down, we need to call to super to open
2123 // the IME on long press.
2124 if (KeyEvent.KEYCODE_MENU == keyCode) {
2125 mMenuIsDown = true;
2126 return super.onKeyDown(keyCode, event);
2127 }
Grace Kloba5942df02009-09-18 11:48:29 -07002128 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2129 // still down, we don't want to trigger the search. Pretend to consume
2130 // the key and do nothing.
2131 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002132
Grace Kloba5942df02009-09-18 11:48:29 -07002133 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002134 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002135 // WebView/WebTextView handle the keys in the KeyDown. As
2136 // the Activity's shortcut keys are only handled when WebView
2137 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2138 if (event.isShiftPressed()) {
2139 getTopWindow().pageUp(false);
2140 } else {
2141 getTopWindow().pageDown(false);
2142 }
Grace Kloba5942df02009-09-18 11:48:29 -07002143 return true;
2144 case KeyEvent.KEYCODE_BACK:
2145 if (event.getRepeatCount() == 0) {
2146 event.startTracking();
2147 return true;
2148 } else if (mCustomView == null && mActiveTabsPage == null
2149 && event.isLongPress()) {
2150 bookmarksOrHistoryPicker(true);
2151 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002152 }
Grace Kloba5942df02009-09-18 11:48:29 -07002153 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002154 }
Grace Kloba5942df02009-09-18 11:48:29 -07002155 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002156 }
2157
Grace Kloba5942df02009-09-18 11:48:29 -07002158 @Override
2159 public boolean onKeyUp(int keyCode, KeyEvent event) {
2160 switch(keyCode) {
2161 case KeyEvent.KEYCODE_MENU:
2162 mMenuIsDown = false;
2163 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002164 case KeyEvent.KEYCODE_BACK:
2165 if (event.isTracking() && !event.isCanceled()) {
2166 if (mCustomView != null) {
2167 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002168 mTabControl.getCurrentWebView().getWebChromeClient()
2169 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002170 } else if (mActiveTabsPage != null) {
2171 // if tab page is showing, hide it
2172 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002174 WebView subwindow = mTabControl.getCurrentSubWindow();
2175 if (subwindow != null) {
2176 if (subwindow.canGoBack()) {
2177 subwindow.goBack();
2178 } else {
2179 dismissSubWindow(mTabControl.getCurrentTab());
2180 }
2181 } else {
2182 goBackOnePageOrQuit();
2183 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002184 }
Grace Kloba5942df02009-09-18 11:48:29 -07002185 return true;
2186 }
2187 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002188 }
Grace Kloba5942df02009-09-18 11:48:29 -07002189 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002190 }
2191
Leon Scroggins68579392009-09-15 15:31:54 -04002192 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002193 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002194 resetTitleAndRevertLockIcon();
2195 WebView w = getTopWindow();
2196 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002197 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2198 // same logic here. But for subwindow case, should we call into the main
2199 // WebView's onPageFinished as we never call its onPageStarted and if
2200 // the page finishes itself, we don't call onPageFinished.
2201 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2202 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002203
2204 cancelStopToast();
2205 mStopToast = Toast
2206 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2207 mStopToast.show();
2208 }
2209
Grace Kloba22ac16e2009-10-07 18:00:23 -07002210 boolean didUserStopLoading() {
2211 return mDidStopLoad;
2212 }
2213
The Android Open Source Project0c908882009-03-03 19:32:16 -08002214 private void cancelStopToast() {
2215 if (mStopToast != null) {
2216 mStopToast.cancel();
2217 mStopToast = null;
2218 }
2219 }
2220
Grace Kloba22ac16e2009-10-07 18:00:23 -07002221 // called by a UI or non-UI thread to post the message
2222 public void postMessage(int what, int arg1, int arg2, Object obj,
2223 long delayMillis) {
2224 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2225 obj), delayMillis);
2226 }
2227
2228 // called by a UI or non-UI thread to remove the message
2229 void removeMessages(int what, Object object) {
2230 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002231 }
2232
2233 // public message ids
2234 public final static int LOAD_URL = 1001;
2235 public final static int STOP_LOAD = 1002;
2236
2237 // Message Ids
2238 private static final int FOCUS_NODE_HREF = 102;
2239 private static final int CANCEL_CREDS_REQUEST = 103;
Grace Kloba92c18a52009-07-31 23:48:32 -07002240 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002241
Grace Kloba22ac16e2009-10-07 18:00:23 -07002242 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002243
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 // Private handler for handling javascript and saving passwords
2245 private Handler mHandler = new Handler() {
2246
2247 public void handleMessage(Message msg) {
2248 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002249 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002250 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002251 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002252 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 if (url == null || url.length() == 0) {
2254 break;
2255 }
2256 HashMap focusNodeMap = (HashMap) msg.obj;
2257 WebView view = (WebView) focusNodeMap.get("webview");
2258 // Only apply the action if the top window did not change.
2259 if (getTopWindow() != view) {
2260 break;
2261 }
2262 switch (msg.arg1) {
2263 case R.id.open_context_menu_id:
2264 case R.id.view_image_context_menu_id:
2265 loadURL(getTopWindow(), url);
2266 break;
2267 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002268 final Tab parent = mTabControl.getCurrentTab();
2269 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002270 if (newTab != parent) {
2271 parent.addChildTab(newTab);
2272 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002273 break;
2274 case R.id.bookmark_context_menu_id:
2275 Intent intent = new Intent(BrowserActivity.this,
2276 AddBookmarkPage.class);
2277 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002278 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002279 startActivity(intent);
2280 break;
2281 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002282 // See if this site has been visited before
2283 StringBuilder sb = new StringBuilder(
2284 Browser.BookmarkColumns.URL + " = ");
2285 DatabaseUtils.appendEscapedSQLString(sb, url);
2286 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2287 Browser.HISTORY_PROJECTION,
2288 sb.toString(),
2289 null,
2290 null);
2291 if (c.moveToFirst()) {
2292 // The site has been visited before, so grab the
2293 // info from the database.
2294 Bitmap favicon = null;
2295 Bitmap thumbnail = null;
2296 String linkTitle = c.getString(Browser.
2297 HISTORY_PROJECTION_TITLE_INDEX);
2298 byte[] data = c.getBlob(Browser.
2299 HISTORY_PROJECTION_FAVICON_INDEX);
2300 if (data != null) {
2301 favicon = BitmapFactory.decodeByteArray(
2302 data, 0, data.length);
2303 }
2304 data = c.getBlob(Browser.
2305 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2306 if (data != null) {
2307 thumbnail = BitmapFactory.decodeByteArray(
2308 data, 0, data.length);
2309 }
2310 sharePage(BrowserActivity.this,
2311 linkTitle, url, favicon, thumbnail);
2312 } else {
2313 Browser.sendString(BrowserActivity.this, url,
2314 getString(
2315 R.string.choosertitle_sharevia));
2316 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002317 break;
2318 case R.id.copy_link_context_menu_id:
2319 copy(url);
2320 break;
2321 case R.id.save_link_context_menu_id:
2322 case R.id.download_context_menu_id:
2323 onDownloadStartNoStream(url, null, null, null, -1);
2324 break;
2325 }
2326 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002327 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002328
2329 case LOAD_URL:
2330 loadURL(getTopWindow(), (String) msg.obj);
2331 break;
2332
2333 case STOP_LOAD:
2334 stopLoading();
2335 break;
2336
2337 case CANCEL_CREDS_REQUEST:
2338 resumeAfterCredentials();
2339 break;
2340
The Android Open Source Project0c908882009-03-03 19:32:16 -08002341 case RELEASE_WAKELOCK:
2342 if (mWakeLock.isHeld()) {
2343 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002344 // if we reach here, Browser should be still in the
2345 // background loading after WAKELOCK_TIMEOUT (5-min).
2346 // To avoid burning the battery, stop loading.
2347 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 }
2349 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002350
2351 case UPDATE_BOOKMARK_THUMBNAIL:
2352 WebView view = (WebView) msg.obj;
2353 if (view != null) {
2354 updateScreenshot(view);
2355 }
2356 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002357 }
2358 }
2359 };
2360
Leon Scroggins96afcb12009-12-10 12:35:56 -05002361 /**
2362 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2363 * an {@link Intent} to launch the Activity chooser.
2364 * @param c Context used to launch a new Activity.
2365 * @param title Title of the page. Stored in the Intent with
2366 * {@link Browser#EXTRA_SHARE_TITLE}
2367 * @param url URL of the page. Stored in the Intent with
2368 * {@link Intent#EXTRA_TEXT}
2369 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2370 * with {@link Browser#EXTRA_SHARE_FAVICON}
2371 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2372 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2373 */
2374 public static final void sharePage(Context c, String title, String url,
2375 Bitmap favicon, Bitmap screenshot) {
2376 Intent send = new Intent(Intent.ACTION_SEND);
2377 send.setType("text/plain");
2378 send.putExtra(Intent.EXTRA_TEXT, url);
2379 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2380 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2381 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2382 try {
2383 c.startActivity(Intent.createChooser(send, c.getString(
2384 R.string.choosertitle_sharevia)));
2385 } catch(android.content.ActivityNotFoundException ex) {
2386 // if no app handles it, do nothing
2387 }
2388 }
2389
Leon Scroggins89c6d362009-07-15 16:54:37 -04002390 private void updateScreenshot(WebView view) {
2391 // If this is a bookmarked site, add a screenshot to the database.
2392 // FIXME: When should we update? Every time?
2393 // FIXME: Would like to make sure there is actually something to
2394 // draw, but the API for that (WebViewCore.pictureReady()) is not
2395 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002396
Patrick Scott3918d442009-08-04 13:22:29 -04002397 ContentResolver cr = getContentResolver();
2398 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Ben Murdochaac7aa62009-09-17 16:57:40 +01002399 cr, view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04002400 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002401 boolean succeed = c.moveToFirst();
2402 ContentValues values = null;
2403 while (succeed) {
2404 if (values == null) {
2405 final ByteArrayOutputStream os
2406 = new ByteArrayOutputStream();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002407 Bitmap bm = createScreenshot(view);
Leon Scroggins45800572009-09-29 16:38:47 -04002408 if (bm == null) {
2409 c.close();
2410 return;
2411 }
Leon Scroggins89c6d362009-07-15 16:54:37 -04002412 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2413 values = new ContentValues();
2414 values.put(Browser.BookmarkColumns.THUMBNAIL,
2415 os.toByteArray());
2416 }
2417 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2418 c.getInt(0)), values, null, null);
2419 succeed = c.moveToNext();
2420 }
2421 c.close();
2422 }
2423 }
2424
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002425 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002426 * Values for the size of the thumbnail created when taking a screenshot.
2427 * Lazily initialized. Instead of using these directly, use
2428 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002429 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002430 private static int THUMBNAIL_WIDTH = 0;
2431 private static int THUMBNAIL_HEIGHT = 0;
2432
2433 /**
2434 * Return the desired width for thumbnail screenshots, which are stored in
2435 * the database, and used on the bookmarks screen.
2436 * @param context Context for finding out the density of the screen.
2437 * @return int desired width for thumbnail screenshot.
2438 */
2439 /* package */ static int getDesiredThumbnailWidth(Context context) {
2440 if (THUMBNAIL_WIDTH == 0) {
2441 float density = context.getResources().getDisplayMetrics().density;
2442 THUMBNAIL_WIDTH = (int) (90 * density);
2443 THUMBNAIL_HEIGHT = (int) (80 * density);
2444 }
2445 return THUMBNAIL_WIDTH;
2446 }
2447
2448 /**
2449 * Return the desired height for thumbnail screenshots, which are stored in
2450 * the database, and used on the bookmarks screen.
2451 * @param context Context for finding out the density of the screen.
2452 * @return int desired height for thumbnail screenshot.
2453 */
2454 /* package */ static int getDesiredThumbnailHeight(Context context) {
2455 // To ensure that they are both initialized.
2456 getDesiredThumbnailWidth(context);
2457 return THUMBNAIL_HEIGHT;
2458 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002459
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002460 private Bitmap createScreenshot(WebView view) {
2461 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002462 if (thumbnail == null) {
2463 return null;
2464 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002465 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2466 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002467 Canvas canvas = new Canvas(bm);
2468 // May need to tweak these values to determine what is the
2469 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002470 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002471 int thumbnailHeight = thumbnail.getHeight();
2472 float scaleFactorX = 1.0f;
2473 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002474 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002475 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002476 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002477 } else {
2478 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002479 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002480
2481 if (view.getWidth() > view.getHeight() &&
2482 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2483 // If the device is in landscape and the page is shorter
2484 // than the height of the view, stretch the thumbnail to fill the
2485 // space.
2486 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2487 (float)thumbnailHeight;
2488 } else {
2489 // In the portrait case, this looks nice.
2490 scaleFactorY = scaleFactorX;
2491 }
2492
2493 canvas.scale(scaleFactorX, scaleFactorY);
2494
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002495 thumbnail.draw(canvas);
2496 return bm;
2497 }
2498
The Android Open Source Project0c908882009-03-03 19:32:16 -08002499 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002500 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002501 //-------------------------------------------------------------------------
2502
2503 // Use in overrideUrlLoading
2504 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2505 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2506 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2507 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2508
Grace Kloba22ac16e2009-10-07 18:00:23 -07002509 void onPageStarted(WebView view, String url, Bitmap favicon) {
2510 // when BrowserActivity just starts, onPageStarted may be called before
2511 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2512 // to start the timer. As we won't switch tabs while an activity is in
2513 // pause state, we can ensure calling resume and pause in pair.
2514 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002515
Grace Kloba22ac16e2009-10-07 18:00:23 -07002516 resetLockIcon(url);
2517 setUrlTitle(url, null);
2518 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002519 // Keep this initial progress in sync with initialProgressValue (* 100)
2520 // in ProgressTracker.cpp
2521 // Show some progress so that the user knows the page is beginning to
2522 // load
2523 onProgressChanged(view, 10);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002524 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002525 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002526
Grace Kloba22ac16e2009-10-07 18:00:23 -07002527 if (mSettings.isTracing()) {
2528 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002529 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002530 WebAddress uri = new WebAddress(url);
2531 host = uri.mHost;
2532 } catch (android.net.ParseException ex) {
2533 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002534 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002535 host = host.replace('.', '_');
2536 host += ".trace";
2537 mInTrace = true;
2538 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2539 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002540
Grace Kloba22ac16e2009-10-07 18:00:23 -07002541 // Performance probe
2542 if (false) {
2543 mStart = SystemClock.uptimeMillis();
2544 mProcessStart = Process.getElapsedCpuTime();
2545 long[] sysCpu = new long[7];
2546 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2547 sysCpu, null)) {
2548 mUserStart = sysCpu[0] + sysCpu[1];
2549 mSystemStart = sysCpu[2];
2550 mIdleStart = sysCpu[3];
2551 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2552 }
2553 mUiStart = SystemClock.currentThreadTimeMillis();
2554 }
2555 }
2556
2557 void onPageFinished(WebView view, String url) {
2558 // Reset the title and icon in case we stopped a provisional load.
2559 resetTitleAndIcon(view);
2560 // Update the lock icon image only once we are done loading
2561 updateLockIconToLatest();
2562 // pause the WebView timer and release the wake lock if it is finished
2563 // while BrowserActivity is in pause state.
2564 if (mActivityInPause && pauseWebViewTimers()) {
2565 if (mWakeLock.isHeld()) {
2566 mHandler.removeMessages(RELEASE_WAKELOCK);
2567 mWakeLock.release();
2568 }
2569 }
2570
2571 // Performance probe
2572 if (false) {
2573 long[] sysCpu = new long[7];
2574 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2575 sysCpu, null)) {
2576 String uiInfo = "UI thread used "
2577 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2578 + " ms";
2579 if (LOGD_ENABLED) {
2580 Log.d(LOGTAG, uiInfo);
2581 }
2582 //The string that gets written to the log
2583 String performanceString = "It took total "
2584 + (SystemClock.uptimeMillis() - mStart)
2585 + " ms clock time to load the page."
2586 + "\nbrowser process used "
2587 + (Process.getElapsedCpuTime() - mProcessStart)
2588 + " ms, user processes used "
2589 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2590 + " ms, kernel used "
2591 + (sysCpu[2] - mSystemStart) * 10
2592 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2593 + " ms and irq took "
2594 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2595 * 10 + " ms, " + uiInfo;
2596 if (LOGD_ENABLED) {
2597 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2598 }
2599 if (url != null) {
2600 // strip the url to maintain consistency
2601 String newUrl = new String(url);
2602 if (newUrl.startsWith("http://www.")) {
2603 newUrl = newUrl.substring(11);
2604 } else if (newUrl.startsWith("http://")) {
2605 newUrl = newUrl.substring(7);
2606 } else if (newUrl.startsWith("https://www.")) {
2607 newUrl = newUrl.substring(12);
2608 } else if (newUrl.startsWith("https://")) {
2609 newUrl = newUrl.substring(8);
2610 }
2611 if (LOGD_ENABLED) {
2612 Log.d(LOGTAG, newUrl + " loaded");
2613 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002614 }
2615 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002616 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002617
Grace Kloba22ac16e2009-10-07 18:00:23 -07002618 if (mInTrace) {
2619 mInTrace = false;
2620 Debug.stopMethodTracing();
2621 }
2622 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623
Grace Kloba22ac16e2009-10-07 18:00:23 -07002624 boolean shouldOverrideUrlLoading(WebView view, String url) {
2625 if (url.startsWith(SCHEME_WTAI)) {
2626 // wtai://wp/mc;number
2627 // number=string(phone-number)
2628 if (url.startsWith(SCHEME_WTAI_MC)) {
2629 Intent intent = new Intent(Intent.ACTION_VIEW,
2630 Uri.parse(WebView.SCHEME_TEL +
2631 url.substring(SCHEME_WTAI_MC.length())));
2632 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002633 return true;
2634 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002635 // wtai://wp/sd;dtmf
2636 // dtmf=string(dialstring)
2637 if (url.startsWith(SCHEME_WTAI_SD)) {
2638 // TODO: only send when there is active voice connection
2639 return false;
2640 }
2641 // wtai://wp/ap;number;name
2642 // number=string(phone-number)
2643 // name=string
2644 if (url.startsWith(SCHEME_WTAI_AP)) {
2645 // TODO
2646 return false;
2647 }
2648 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002649
Grace Kloba22ac16e2009-10-07 18:00:23 -07002650 // The "about:" schemes are internal to the browser; don't want these to
2651 // be dispatched to other apps.
2652 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002653 return false;
2654 }
2655
Grace Kloba22ac16e2009-10-07 18:00:23 -07002656 Intent intent;
2657 // perform generic parsing of the URI to turn it into an Intent.
2658 try {
2659 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2660 } catch (URISyntaxException ex) {
2661 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2662 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002663 }
2664
Grace Kloba22ac16e2009-10-07 18:00:23 -07002665 // check whether the intent can be resolved. If not, we will see
2666 // whether we can download it from the Market.
2667 if (getPackageManager().resolveActivity(intent, 0) == null) {
2668 String packagename = intent.getPackage();
2669 if (packagename != null) {
2670 intent = new Intent(Intent.ACTION_VIEW, Uri
2671 .parse("market://search?q=pname:" + packagename));
2672 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2673 startActivity(intent);
2674 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002675 } else {
2676 return false;
2677 }
2678 }
2679
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 // sanitize the Intent, ensuring web pages can not bypass browser
2681 // security (only access to BROWSABLE activities).
2682 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2683 intent.setComponent(null);
2684 try {
2685 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002686 return true;
2687 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688 } catch (ActivityNotFoundException ex) {
2689 // ignore the error. If no application can handle the URL,
2690 // eg about:blank, assume the browser can handle it.
2691 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002692
Grace Kloba22ac16e2009-10-07 18:00:23 -07002693 if (mMenuIsDown) {
2694 openTab(url);
2695 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002696 return true;
2697 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002698 return false;
2699 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002700
Grace Kloba22ac16e2009-10-07 18:00:23 -07002701 // -------------------------------------------------------------------------
2702 // Helper function for WebChromeClient
2703 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002704
Grace Kloba22ac16e2009-10-07 18:00:23 -07002705 void onProgressChanged(WebView view, int newProgress) {
2706 mTitleBar.setProgress(newProgress);
2707 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002708
Grace Kloba22ac16e2009-10-07 18:00:23 -07002709 if (newProgress == 100) {
2710 // onProgressChanged() may continue to be called after the main
2711 // frame has finished loading, as any remaining sub frames continue
2712 // to load. We'll only get called once though with newProgress as
2713 // 100 when everything is loaded. (onPageFinished is called once
2714 // when the main frame completes loading regardless of the state of
2715 // any sub frames so calls to onProgressChanges may continue after
2716 // onPageFinished has executed)
2717 if (mInLoad) {
2718 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002719 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002720 // If the options menu is open, leave the title bar
2721 if (!mOptionsMenuOpen || !mIconView) {
2722 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002724 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002725 } else if (!mInLoad) {
2726 // onPageFinished may have already been called but a subframe is
2727 // still loading and updating the progress. Reset mInLoad and update
2728 // the menu items.
2729 mInLoad = true;
2730 updateInLoadMenuItems();
2731 if (!mOptionsMenuOpen || mIconView) {
2732 // This page has begun to load, so show the title bar
2733 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002734 }
2735 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002736 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002739 // if a view already exists then immediately terminate the new one
2740 if (mCustomView != null) {
2741 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002742 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002743 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002744
2745 // Add the custom view to its container.
2746 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2747 mCustomView = view;
2748 mCustomViewCallback = callback;
2749 // Save the menu state and set it to empty while the custom
2750 // view is showing.
2751 mOldMenuState = mMenuState;
2752 mMenuState = EMPTY_MENU;
2753 // Hide the content view.
2754 mContentView.setVisibility(View.GONE);
2755 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002756 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002757 mCustomViewContainer.setVisibility(View.VISIBLE);
2758 mCustomViewContainer.bringToFront();
2759 }
2760
2761 void onHideCustomView() {
2762 if (mCustomView == null)
2763 return;
2764
2765 // Hide the custom view.
2766 mCustomView.setVisibility(View.GONE);
2767 // Remove the custom view from its container.
2768 mCustomViewContainer.removeView(mCustomView);
2769 mCustomView = null;
2770 // Reset the old menu state.
2771 mMenuState = mOldMenuState;
2772 mOldMenuState = EMPTY_MENU;
2773 mCustomViewContainer.setVisibility(View.GONE);
2774 mCustomViewCallback.onCustomViewHidden();
2775 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002776 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002777 mContentView.setVisibility(View.VISIBLE);
2778 }
2779
2780 Bitmap getDefaultVideoPoster() {
2781 if (mDefaultVideoPoster == null) {
2782 mDefaultVideoPoster = BitmapFactory.decodeResource(
2783 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002784 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002785 return mDefaultVideoPoster;
2786 }
Patrick Scott3918d442009-08-04 13:22:29 -04002787
Grace Kloba22ac16e2009-10-07 18:00:23 -07002788 View getVideoLoadingProgressView() {
2789 if (mVideoProgressView == null) {
2790 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2791 mVideoProgressView = inflater.inflate(
2792 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002793 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002794 return mVideoProgressView;
2795 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002796
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002797 /*
2798 * The Object used to inform the WebView of the file to upload.
2799 */
2800 private ValueCallback<Uri> mUploadMessage;
2801
Grace Kloba22ac16e2009-10-07 18:00:23 -07002802 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2803 if (mUploadMessage != null) return;
2804 mUploadMessage = uploadMsg;
2805 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2806 i.addCategory(Intent.CATEGORY_OPENABLE);
2807 i.setType("*/*");
2808 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2809 getString(R.string.choose_upload)), FILE_SELECTED);
2810 }
2811
2812 // -------------------------------------------------------------------------
2813 // Implement functions for DownloadListener
2814 // -------------------------------------------------------------------------
2815
The Android Open Source Project0c908882009-03-03 19:32:16 -08002816 /**
2817 * Notify the host application a download should be done, or that
2818 * the data should be streamed if a streaming viewer is available.
2819 * @param url The full url to the content that should be downloaded
2820 * @param contentDisposition Content-disposition http header, if
2821 * present.
2822 * @param mimetype The mimetype of the content reported by the server
2823 * @param contentLength The file size reported by the server
2824 */
2825 public void onDownloadStart(String url, String userAgent,
2826 String contentDisposition, String mimetype, long contentLength) {
2827 // if we're dealing wih A/V content that's not explicitly marked
2828 // for download, check if it's streamable.
2829 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002830 || !contentDisposition.regionMatches(
2831 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002832 // query the package manager to see if there's a registered handler
2833 // that matches.
2834 Intent intent = new Intent(Intent.ACTION_VIEW);
2835 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002836 ResolveInfo info = getPackageManager().resolveActivity(intent,
2837 PackageManager.MATCH_DEFAULT_ONLY);
2838 if (info != null) {
2839 ComponentName myName = getComponentName();
2840 // If we resolved to ourselves, we don't want to attempt to
2841 // load the url only to try and download it again.
2842 if (!myName.getPackageName().equals(
2843 info.activityInfo.packageName)
2844 || !myName.getClassName().equals(
2845 info.activityInfo.name)) {
2846 // someone (other than us) knows how to handle this mime
2847 // type with this scheme, don't download.
2848 try {
2849 startActivity(intent);
2850 return;
2851 } catch (ActivityNotFoundException ex) {
2852 if (LOGD_ENABLED) {
2853 Log.d(LOGTAG, "activity not found for " + mimetype
2854 + " over " + Uri.parse(url).getScheme(),
2855 ex);
2856 }
2857 // Best behavior is to fall back to a download in this
2858 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860 }
2861 }
2862 }
2863 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2864 }
2865
2866 /**
2867 * Notify the host application a download should be done, even if there
2868 * is a streaming viewer available for thise type.
2869 * @param url The full url to the content that should be downloaded
2870 * @param contentDisposition Content-disposition http header, if
2871 * present.
2872 * @param mimetype The mimetype of the content reported by the server
2873 * @param contentLength The file size reported by the server
2874 */
2875 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2876 String contentDisposition, String mimetype, long contentLength) {
2877
2878 String filename = URLUtil.guessFileName(url,
2879 contentDisposition, mimetype);
2880
2881 // Check to see if we have an SDCard
2882 String status = Environment.getExternalStorageState();
2883 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2884 int title;
2885 String msg;
2886
2887 // Check to see if the SDCard is busy, same as the music app
2888 if (status.equals(Environment.MEDIA_SHARED)) {
2889 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2890 title = R.string.download_sdcard_busy_dlg_title;
2891 } else {
2892 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2893 title = R.string.download_no_sdcard_dlg_title;
2894 }
2895
2896 new AlertDialog.Builder(this)
2897 .setTitle(title)
2898 .setIcon(android.R.drawable.ic_dialog_alert)
2899 .setMessage(msg)
2900 .setPositiveButton(R.string.ok, null)
2901 .show();
2902 return;
2903 }
2904
2905 // java.net.URI is a lot stricter than KURL so we have to undo
2906 // KURL's percent-encoding and redo the encoding using java.net.URI.
2907 URI uri = null;
2908 try {
2909 // Undo the percent-encoding that KURL may have done.
2910 String newUrl = new String(URLUtil.decode(url.getBytes()));
2911 // Parse the url into pieces
2912 WebAddress w = new WebAddress(newUrl);
2913 String frag = null;
2914 String query = null;
2915 String path = w.mPath;
2916 // Break the path into path, query, and fragment
2917 if (path.length() > 0) {
2918 // Strip the fragment
2919 int idx = path.lastIndexOf('#');
2920 if (idx != -1) {
2921 frag = path.substring(idx + 1);
2922 path = path.substring(0, idx);
2923 }
2924 idx = path.lastIndexOf('?');
2925 if (idx != -1) {
2926 query = path.substring(idx + 1);
2927 path = path.substring(0, idx);
2928 }
2929 }
2930 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2931 query, frag);
2932 } catch (Exception e) {
2933 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2934 return;
2935 }
2936
2937 // XXX: Have to use the old url since the cookies were stored using the
2938 // old percent-encoded url.
2939 String cookies = CookieManager.getInstance().getCookie(url);
2940
2941 ContentValues values = new ContentValues();
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002942 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2943 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2944 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2945 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002946 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002947 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002948 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002949 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2950 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2951 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2952 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2953 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002954 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002955 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956 }
2957 if (mimetype == null) {
2958 // We must have long pressed on a link or image to download it. We
2959 // are not sure of the mimetype in this case, so do a head request
2960 new FetchUrlMimeType(this).execute(values);
2961 } else {
2962 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002963 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 }
2965
2966 }
2967
Grace Kloba22ac16e2009-10-07 18:00:23 -07002968 // -------------------------------------------------------------------------
2969
The Android Open Source Project0c908882009-03-03 19:32:16 -08002970 /**
2971 * Resets the lock icon. This method is called when we start a new load and
2972 * know the url to be loaded.
2973 */
2974 private void resetLockIcon(String url) {
2975 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002976 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002977 updateLockIconImage(LOCK_ICON_UNSECURE);
2978 }
2979
The Android Open Source Project0c908882009-03-03 19:32:16 -08002980 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002981 * Update the lock icon to correspond to our latest state.
2982 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002983 private void updateLockIconToLatest() {
2984 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002985 }
2986
2987 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002988 * Updates the lock-icon image in the title-bar.
2989 */
2990 private void updateLockIconImage(int lockIconType) {
2991 Drawable d = null;
2992 if (lockIconType == LOCK_ICON_SECURE) {
2993 d = mSecLockIcon;
2994 } else if (lockIconType == LOCK_ICON_MIXED) {
2995 d = mMixLockIcon;
2996 }
Leon Scroggins68579392009-09-15 15:31:54 -04002997 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002998 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002999 }
3000
3001 /**
3002 * Displays a page-info dialog.
3003 * @param tab The tab to show info about
3004 * @param fromShowSSLCertificateOnError The flag that indicates whether
3005 * this dialog was opened from the SSL-certificate-on-error dialog or
3006 * not. This is important, since we need to know whether to return to
3007 * the parent dialog or simply dismiss.
3008 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003009 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003010 final boolean fromShowSSLCertificateOnError) {
3011 final LayoutInflater factory = LayoutInflater
3012 .from(this);
3013
3014 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3015
3016 final WebView view = tab.getWebView();
3017
3018 String url = null;
3019 String title = null;
3020
3021 if (view == null) {
3022 url = tab.getUrl();
3023 title = tab.getTitle();
3024 } else if (view == mTabControl.getCurrentWebView()) {
3025 // Use the cached title and url if this is the current WebView
3026 url = mUrl;
3027 title = mTitle;
3028 } else {
3029 url = view.getUrl();
3030 title = view.getTitle();
3031 }
3032
3033 if (url == null) {
3034 url = "";
3035 }
3036 if (title == null) {
3037 title = "";
3038 }
3039
3040 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3041 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3042
3043 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003044 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003045
3046 AlertDialog.Builder alertDialogBuilder =
3047 new AlertDialog.Builder(this)
3048 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3049 .setView(pageInfoView)
3050 .setPositiveButton(
3051 R.string.ok,
3052 new DialogInterface.OnClickListener() {
3053 public void onClick(DialogInterface dialog,
3054 int whichButton) {
3055 mPageInfoDialog = null;
3056 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003057
3058 // if we came here from the SSL error dialog
3059 if (fromShowSSLCertificateOnError) {
3060 // go back to the SSL error dialog
3061 showSSLCertificateOnError(
3062 mSSLCertificateOnErrorView,
3063 mSSLCertificateOnErrorHandler,
3064 mSSLCertificateOnErrorError);
3065 }
3066 }
3067 })
3068 .setOnCancelListener(
3069 new DialogInterface.OnCancelListener() {
3070 public void onCancel(DialogInterface dialog) {
3071 mPageInfoDialog = null;
3072 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003073
3074 // if we came here from the SSL error dialog
3075 if (fromShowSSLCertificateOnError) {
3076 // go back to the SSL error dialog
3077 showSSLCertificateOnError(
3078 mSSLCertificateOnErrorView,
3079 mSSLCertificateOnErrorHandler,
3080 mSSLCertificateOnErrorError);
3081 }
3082 }
3083 });
3084
3085 // if we have a main top-level page SSL certificate set or a certificate
3086 // error
3087 if (fromShowSSLCertificateOnError ||
3088 (view != null && view.getCertificate() != null)) {
3089 // add a 'View Certificate' button
3090 alertDialogBuilder.setNeutralButton(
3091 R.string.view_certificate,
3092 new DialogInterface.OnClickListener() {
3093 public void onClick(DialogInterface dialog,
3094 int whichButton) {
3095 mPageInfoDialog = null;
3096 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003097
3098 // if we came here from the SSL error dialog
3099 if (fromShowSSLCertificateOnError) {
3100 // go back to the SSL error dialog
3101 showSSLCertificateOnError(
3102 mSSLCertificateOnErrorView,
3103 mSSLCertificateOnErrorHandler,
3104 mSSLCertificateOnErrorError);
3105 } else {
3106 // otherwise, display the top-most certificate from
3107 // the chain
3108 if (view.getCertificate() != null) {
3109 showSSLCertificate(tab);
3110 }
3111 }
3112 }
3113 });
3114 }
3115
3116 mPageInfoDialog = alertDialogBuilder.show();
3117 }
3118
3119 /**
3120 * Displays the main top-level page SSL certificate dialog
3121 * (accessible from the Page-Info dialog).
3122 * @param tab The tab to show certificate for.
3123 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003124 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003125 final View certificateView =
3126 inflateCertificateView(tab.getWebView().getCertificate());
3127 if (certificateView == null) {
3128 return;
3129 }
3130
3131 LayoutInflater factory = LayoutInflater.from(this);
3132
3133 final LinearLayout placeholder =
3134 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3135
3136 LinearLayout ll = (LinearLayout) factory.inflate(
3137 R.layout.ssl_success, placeholder);
3138 ((TextView)ll.findViewById(R.id.success))
3139 .setText(R.string.ssl_certificate_is_valid);
3140
3141 mSSLCertificateView = tab;
3142 mSSLCertificateDialog =
3143 new AlertDialog.Builder(this)
3144 .setTitle(R.string.ssl_certificate).setIcon(
3145 R.drawable.ic_dialog_browser_certificate_secure)
3146 .setView(certificateView)
3147 .setPositiveButton(R.string.ok,
3148 new DialogInterface.OnClickListener() {
3149 public void onClick(DialogInterface dialog,
3150 int whichButton) {
3151 mSSLCertificateDialog = null;
3152 mSSLCertificateView = null;
3153
3154 showPageInfo(tab, false);
3155 }
3156 })
3157 .setOnCancelListener(
3158 new DialogInterface.OnCancelListener() {
3159 public void onCancel(DialogInterface dialog) {
3160 mSSLCertificateDialog = null;
3161 mSSLCertificateView = null;
3162
3163 showPageInfo(tab, false);
3164 }
3165 })
3166 .show();
3167 }
3168
3169 /**
3170 * Displays the SSL error certificate dialog.
3171 * @param view The target web-view.
3172 * @param handler The SSL error handler responsible for cancelling the
3173 * connection that resulted in an SSL error or proceeding per user request.
3174 * @param error The SSL error object.
3175 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003176 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 final WebView view, final SslErrorHandler handler, final SslError error) {
3178
3179 final View certificateView =
3180 inflateCertificateView(error.getCertificate());
3181 if (certificateView == null) {
3182 return;
3183 }
3184
3185 LayoutInflater factory = LayoutInflater.from(this);
3186
3187 final LinearLayout placeholder =
3188 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3189
3190 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3191 LinearLayout ll = (LinearLayout)factory
3192 .inflate(R.layout.ssl_warning, placeholder);
3193 ((TextView)ll.findViewById(R.id.warning))
3194 .setText(R.string.ssl_untrusted);
3195 }
3196
3197 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3198 LinearLayout ll = (LinearLayout)factory
3199 .inflate(R.layout.ssl_warning, placeholder);
3200 ((TextView)ll.findViewById(R.id.warning))
3201 .setText(R.string.ssl_mismatch);
3202 }
3203
3204 if (error.hasError(SslError.SSL_EXPIRED)) {
3205 LinearLayout ll = (LinearLayout)factory
3206 .inflate(R.layout.ssl_warning, placeholder);
3207 ((TextView)ll.findViewById(R.id.warning))
3208 .setText(R.string.ssl_expired);
3209 }
3210
3211 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3212 LinearLayout ll = (LinearLayout)factory
3213 .inflate(R.layout.ssl_warning, placeholder);
3214 ((TextView)ll.findViewById(R.id.warning))
3215 .setText(R.string.ssl_not_yet_valid);
3216 }
3217
3218 mSSLCertificateOnErrorHandler = handler;
3219 mSSLCertificateOnErrorView = view;
3220 mSSLCertificateOnErrorError = error;
3221 mSSLCertificateOnErrorDialog =
3222 new AlertDialog.Builder(this)
3223 .setTitle(R.string.ssl_certificate).setIcon(
3224 R.drawable.ic_dialog_browser_certificate_partially_secure)
3225 .setView(certificateView)
3226 .setPositiveButton(R.string.ok,
3227 new DialogInterface.OnClickListener() {
3228 public void onClick(DialogInterface dialog,
3229 int whichButton) {
3230 mSSLCertificateOnErrorDialog = null;
3231 mSSLCertificateOnErrorView = null;
3232 mSSLCertificateOnErrorHandler = null;
3233 mSSLCertificateOnErrorError = null;
3234
Grace Kloba22ac16e2009-10-07 18:00:23 -07003235 view.getWebViewClient().onReceivedSslError(
3236 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003237 }
3238 })
3239 .setNeutralButton(R.string.page_info_view,
3240 new DialogInterface.OnClickListener() {
3241 public void onClick(DialogInterface dialog,
3242 int whichButton) {
3243 mSSLCertificateOnErrorDialog = null;
3244
3245 // do not clear the dialog state: we will
3246 // need to show the dialog again once the
3247 // user is done exploring the page-info details
3248
3249 showPageInfo(mTabControl.getTabFromView(view),
3250 true);
3251 }
3252 })
3253 .setOnCancelListener(
3254 new DialogInterface.OnCancelListener() {
3255 public void onCancel(DialogInterface dialog) {
3256 mSSLCertificateOnErrorDialog = null;
3257 mSSLCertificateOnErrorView = null;
3258 mSSLCertificateOnErrorHandler = null;
3259 mSSLCertificateOnErrorError = null;
3260
Grace Kloba22ac16e2009-10-07 18:00:23 -07003261 view.getWebViewClient().onReceivedSslError(
3262 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003263 }
3264 })
3265 .show();
3266 }
3267
3268 /**
3269 * Inflates the SSL certificate view (helper method).
3270 * @param certificate The SSL certificate.
3271 * @return The resultant certificate view with issued-to, issued-by,
3272 * issued-on, expires-on, and possibly other fields set.
3273 * If the input certificate is null, returns null.
3274 */
3275 private View inflateCertificateView(SslCertificate certificate) {
3276 if (certificate == null) {
3277 return null;
3278 }
3279
3280 LayoutInflater factory = LayoutInflater.from(this);
3281
3282 View certificateView = factory.inflate(
3283 R.layout.ssl_certificate, null);
3284
3285 // issued to:
3286 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3287 if (issuedTo != null) {
3288 ((TextView) certificateView.findViewById(R.id.to_common))
3289 .setText(issuedTo.getCName());
3290 ((TextView) certificateView.findViewById(R.id.to_org))
3291 .setText(issuedTo.getOName());
3292 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3293 .setText(issuedTo.getUName());
3294 }
3295
3296 // issued by:
3297 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3298 if (issuedBy != null) {
3299 ((TextView) certificateView.findViewById(R.id.by_common))
3300 .setText(issuedBy.getCName());
3301 ((TextView) certificateView.findViewById(R.id.by_org))
3302 .setText(issuedBy.getOName());
3303 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3304 .setText(issuedBy.getUName());
3305 }
3306
3307 // issued on:
3308 String issuedOn = reformatCertificateDate(
3309 certificate.getValidNotBefore());
3310 ((TextView) certificateView.findViewById(R.id.issued_on))
3311 .setText(issuedOn);
3312
3313 // expires on:
3314 String expiresOn = reformatCertificateDate(
3315 certificate.getValidNotAfter());
3316 ((TextView) certificateView.findViewById(R.id.expires_on))
3317 .setText(expiresOn);
3318
3319 return certificateView;
3320 }
3321
3322 /**
3323 * Re-formats the certificate date (Date.toString()) string to
3324 * a properly localized date string.
3325 * @return Properly localized version of the certificate date string and
3326 * the original certificate date string if fails to localize.
3327 * If the original string is null, returns an empty string "".
3328 */
3329 private String reformatCertificateDate(String certificateDate) {
3330 String reformattedDate = null;
3331
3332 if (certificateDate != null) {
3333 Date date = null;
3334 try {
3335 date = java.text.DateFormat.getInstance().parse(certificateDate);
3336 } catch (ParseException e) {
3337 date = null;
3338 }
3339
3340 if (date != null) {
3341 reformattedDate =
3342 DateFormat.getDateFormat(this).format(date);
3343 }
3344 }
3345
3346 return reformattedDate != null ? reformattedDate :
3347 (certificateDate != null ? certificateDate : "");
3348 }
3349
3350 /**
3351 * Displays an http-authentication dialog.
3352 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003353 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003354 final String host, final String realm, final String title,
3355 final String name, final String password, int focusId) {
3356 LayoutInflater factory = LayoutInflater.from(this);
3357 final View v = factory
3358 .inflate(R.layout.http_authentication, null);
3359 if (name != null) {
3360 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3361 }
3362 if (password != null) {
3363 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3364 }
3365
3366 String titleText = title;
3367 if (titleText == null) {
3368 titleText = getText(R.string.sign_in_to).toString().replace(
3369 "%s1", host).replace("%s2", realm);
3370 }
3371
3372 mHttpAuthHandler = handler;
3373 AlertDialog dialog = new AlertDialog.Builder(this)
3374 .setTitle(titleText)
3375 .setIcon(android.R.drawable.ic_dialog_alert)
3376 .setView(v)
3377 .setPositiveButton(R.string.action,
3378 new DialogInterface.OnClickListener() {
3379 public void onClick(DialogInterface dialog,
3380 int whichButton) {
3381 String nm = ((EditText) v
3382 .findViewById(R.id.username_edit))
3383 .getText().toString();
3384 String pw = ((EditText) v
3385 .findViewById(R.id.password_edit))
3386 .getText().toString();
3387 BrowserActivity.this.setHttpAuthUsernamePassword
3388 (host, realm, nm, pw);
3389 handler.proceed(nm, pw);
3390 mHttpAuthenticationDialog = null;
3391 mHttpAuthHandler = null;
3392 }})
3393 .setNegativeButton(R.string.cancel,
3394 new DialogInterface.OnClickListener() {
3395 public void onClick(DialogInterface dialog,
3396 int whichButton) {
3397 handler.cancel();
3398 BrowserActivity.this.resetTitleAndRevertLockIcon();
3399 mHttpAuthenticationDialog = null;
3400 mHttpAuthHandler = null;
3401 }})
3402 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3403 public void onCancel(DialogInterface dialog) {
3404 handler.cancel();
3405 BrowserActivity.this.resetTitleAndRevertLockIcon();
3406 mHttpAuthenticationDialog = null;
3407 mHttpAuthHandler = null;
3408 }})
3409 .create();
3410 // Make the IME appear when the dialog is displayed if applicable.
3411 dialog.getWindow().setSoftInputMode(
3412 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3413 dialog.show();
3414 if (focusId != 0) {
3415 dialog.findViewById(focusId).requestFocus();
3416 } else {
3417 v.findViewById(R.id.username_edit).requestFocus();
3418 }
3419 mHttpAuthenticationDialog = dialog;
3420 }
3421
3422 public int getProgress() {
3423 WebView w = mTabControl.getCurrentWebView();
3424 if (w != null) {
3425 return w.getProgress();
3426 } else {
3427 return 100;
3428 }
3429 }
3430
3431 /**
3432 * Set HTTP authentication password.
3433 *
3434 * @param host The host for the password
3435 * @param realm The realm for the password
3436 * @param username The username for the password. If it is null, it means
3437 * password can't be saved.
3438 * @param password The password
3439 */
3440 public void setHttpAuthUsernamePassword(String host, String realm,
3441 String username,
3442 String password) {
3443 WebView w = mTabControl.getCurrentWebView();
3444 if (w != null) {
3445 w.setHttpAuthUsernamePassword(host, realm, username, password);
3446 }
3447 }
3448
3449 /**
3450 * connectivity manager says net has come or gone... inform the user
3451 * @param up true if net has come up, false if net has gone down
3452 */
3453 public void onNetworkToggle(boolean up) {
3454 if (up == mIsNetworkUp) {
3455 return;
3456 } else if (up) {
3457 mIsNetworkUp = true;
3458 if (mAlertDialog != null) {
3459 mAlertDialog.cancel();
3460 mAlertDialog = null;
3461 }
3462 } else {
3463 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003464 if (mInLoad) {
3465 createAndShowNetworkDialog();
3466 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003467 }
3468 WebView w = mTabControl.getCurrentWebView();
3469 if (w != null) {
3470 w.setNetworkAvailable(up);
3471 }
3472 }
3473
Grace Kloba22ac16e2009-10-07 18:00:23 -07003474 boolean isNetworkUp() {
3475 return mIsNetworkUp;
3476 }
3477
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003478 // This method shows the network dialog alerting the user that the net is
3479 // down. It will only show the dialog if mAlertDialog is null.
3480 private void createAndShowNetworkDialog() {
3481 if (mAlertDialog == null) {
3482 mAlertDialog = new AlertDialog.Builder(this)
3483 .setTitle(R.string.loadSuspendedTitle)
3484 .setMessage(R.string.loadSuspended)
3485 .setPositiveButton(R.string.ok, null)
3486 .show();
3487 }
3488 }
3489
The Android Open Source Project0c908882009-03-03 19:32:16 -08003490 @Override
3491 protected void onActivityResult(int requestCode, int resultCode,
3492 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003493 if (getTopWindow() == null) return;
3494
The Android Open Source Project0c908882009-03-03 19:32:16 -08003495 switch (requestCode) {
3496 case COMBO_PAGE:
3497 if (resultCode == RESULT_OK && intent != null) {
3498 String data = intent.getAction();
3499 Bundle extras = intent.getExtras();
3500 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003501 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003502 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003503 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003504 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003505 dismissSubWindow(currentTab);
3506 if (data != null && data.length() != 0) {
3507 getTopWindow().loadUrl(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003508 }
3509 }
3510 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003511 // Deliberately fall through to PREFERENCES_PAGE, since the
3512 // same extra may be attached to the COMBO_PAGE
3513 case PREFERENCES_PAGE:
3514 if (resultCode == RESULT_OK && intent != null) {
3515 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3516 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3517 mTabControl.removeParentChildRelationShips();
3518 }
3519 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003520 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003521 // Choose a file from the file picker.
3522 case FILE_SELECTED:
3523 if (null == mUploadMessage) break;
3524 Uri result = intent == null || resultCode != RESULT_OK ? null
3525 : intent.getData();
3526 mUploadMessage.onReceiveValue(result);
3527 mUploadMessage = null;
3528 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003529 default:
3530 break;
3531 }
Leon Scroggins30444232009-09-04 18:36:20 -04003532 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533 }
3534
3535 /*
3536 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003537 * menu to see the download window. It shows the download window on top of
3538 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003539 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003540 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541 Intent intent = new Intent(this,
3542 BrowserDownloadPage.class);
3543 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003544 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003545
3546 }
3547
Leon Scroggins160a7e72009-08-14 18:28:01 -04003548 /**
3549 * Open the Go page.
3550 * @param startWithHistory If true, open starting on the history tab.
3551 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003552 */
Leon Scroggins30444232009-09-04 18:36:20 -04003553 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003554 WebView current = mTabControl.getCurrentWebView();
3555 if (current == null) {
3556 return;
3557 }
3558 Intent intent = new Intent(this,
3559 CombinedBookmarkHistoryActivity.class);
3560 String title = current.getTitle();
3561 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003562 Bitmap thumbnail = createScreenshot(current);
3563
The Android Open Source Project0c908882009-03-03 19:32:16 -08003564 // Just in case the user opens bookmarks before a page finishes loading
3565 // so the current history item, and therefore the page, is null.
3566 if (null == url) {
3567 url = mLastEnteredUrl;
3568 // This can happen.
3569 if (null == url) {
3570 url = mSettings.getHomePage();
3571 }
3572 }
3573 // In case the web page has not yet received its associated title.
3574 if (title == null) {
3575 title = url;
3576 }
3577 intent.putExtra("title", title);
3578 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003579 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003580 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003581 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003582 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003583 if (startWithHistory) {
3584 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3585 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3586 }
3587 startActivityForResult(intent, COMBO_PAGE);
3588 }
3589
3590 // Called when loading from context menu or LOAD_URL message
3591 private void loadURL(WebView view, String url) {
3592 // In case the user enters nothing.
3593 if (url != null && url.length() != 0 && view != null) {
3594 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003595 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003596 view.loadUrl(url);
3597 }
3598 }
3599 }
3600
The Android Open Source Project0c908882009-03-03 19:32:16 -08003601 private String smartUrlFilter(Uri inUri) {
3602 if (inUri != null) {
3603 return smartUrlFilter(inUri.toString());
3604 }
3605 return null;
3606 }
3607
Feng Qianb34f87a2009-03-24 21:27:26 -07003608 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003609 "(?i)" + // switch on case insensitive matching
3610 "(" + // begin group for schema
3611 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003612 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003613 ")" +
3614 "(.*)" );
3615
3616 /**
3617 * Attempts to determine whether user input is a URL or search
3618 * terms. Anything with a space is passed to search.
3619 *
3620 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3621 * "Http://" converts to "http://"
3622 *
3623 * @return Original or modified URL
3624 *
3625 */
3626 String smartUrlFilter(String url) {
3627
3628 String inUrl = url.trim();
3629 boolean hasSpace = inUrl.indexOf(' ') != -1;
3630
3631 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3632 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003633 // force scheme to lowercase
3634 String scheme = matcher.group(1);
3635 String lcScheme = scheme.toLowerCase();
3636 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003637 inUrl = lcScheme + matcher.group(2);
3638 }
3639 if (hasSpace) {
3640 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003641 }
3642 return inUrl;
3643 }
3644 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003645 // FIXME: Is this the correct place to add to searches?
3646 // what if someone else calls this function?
3647 int shortcut = parseUrlShortcut(inUrl);
3648 if (shortcut != SHORTCUT_INVALID) {
3649 Browser.addSearchUrl(mResolver, inUrl);
3650 String query = inUrl.substring(2);
3651 switch (shortcut) {
3652 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003653 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003654 case SHORTCUT_WIKIPEDIA_SEARCH:
3655 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3656 case SHORTCUT_DICTIONARY_SEARCH:
3657 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3658 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003659 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003660 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661 }
3662 }
3663 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003664 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003665 return URLUtil.guessUrl(inUrl);
3666 }
3667 }
3668
3669 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003670 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003671 }
3672
Ben Murdochbff2d602009-07-01 20:19:05 +01003673 /* package */ void setShouldShowErrorConsole(boolean flag) {
3674 if (flag == mShouldShowErrorConsole) {
3675 // Nothing to do.
3676 return;
3677 }
3678
3679 mShouldShowErrorConsole = flag;
3680
Grace Kloba22ac16e2009-10-07 18:00:23 -07003681 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3682 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003683
3684 if (flag) {
3685 // Setting the show state of the console will cause it's the layout to be inflated.
3686 if (errorConsole.numberOfErrors() > 0) {
3687 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3688 } else {
3689 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3690 }
3691
3692 // Now we can add it to the main view.
3693 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003694 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003695 ViewGroup.LayoutParams.WRAP_CONTENT));
3696 } else {
3697 mErrorConsoleContainer.removeView(errorConsole);
3698 }
3699
3700 }
3701
Grace Kloba22ac16e2009-10-07 18:00:23 -07003702 boolean shouldShowErrorConsole() {
3703 return mShouldShowErrorConsole;
3704 }
3705
Andrei Popescu163ab742009-10-20 17:58:23 +01003706 private void setStatusBarVisibility(boolean visible) {
3707 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3708 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3709 }
3710
Andrei Popescu56199cc2010-01-12 22:39:16 +00003711
3712 private void sendNetworkType(String type, String subtype) {
3713 WebView w = mTabControl.getCurrentWebView();
3714 if (w != null) {
3715 w.setNetworkType(type, subtype);
3716 }
3717 }
3718
Grace Klobaeb6eef42009-09-15 17:56:32 -07003719 final static int LOCK_ICON_UNSECURE = 0;
3720 final static int LOCK_ICON_SECURE = 1;
3721 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722
The Android Open Source Project0c908882009-03-03 19:32:16 -08003723 private BrowserSettings mSettings;
3724 private TabControl mTabControl;
3725 private ContentResolver mResolver;
3726 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003727 private View mCustomView;
3728 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003729 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730
3731 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3732 // view, we should rewrite this.
3733 private int mCurrentMenuState = 0;
3734 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003735 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 private static final int EMPTY_MENU = -1;
3737 private Menu mMenu;
3738
3739 private FindDialog mFindDialog;
3740 // Used to prevent chording to result in firing two shortcuts immediately
3741 // one after another. Fixes bug 1211714.
3742 boolean mCanChord;
3743
3744 private boolean mInLoad;
3745 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003746 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003747
The Android Open Source Project0c908882009-03-03 19:32:16 -08003748 private boolean mActivityInPause = true;
3749
3750 private boolean mMenuIsDown;
3751
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 private static boolean mInTrace;
3753
3754 // Performance probe
3755 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3756 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3757 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3758 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3759 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3760 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3761 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3762 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3763 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3764 };
3765
3766 private long mStart;
3767 private long mProcessStart;
3768 private long mUserStart;
3769 private long mSystemStart;
3770 private long mIdleStart;
3771 private long mIrqStart;
3772
3773 private long mUiStart;
3774
3775 private Drawable mMixLockIcon;
3776 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003777
3778 /* hold a ref so we can auto-cancel if necessary */
3779 private AlertDialog mAlertDialog;
3780
3781 // Wait for credentials before loading google.com
3782 private ProgressDialog mCredsDlg;
3783
3784 // The up-to-date URL and title (these can be different from those stored
3785 // in WebView, since it takes some time for the information in WebView to
3786 // get updated)
3787 private String mUrl;
3788 private String mTitle;
3789
3790 // As PageInfo has different style for landscape / portrait, we have
3791 // to re-open it when configuration changed
3792 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003793 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003794 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3795 // dialog, we should not just dismiss it, but should get back to the
3796 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003797 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003798
3799 // as SSLCertificateOnError has different style for landscape / portrait,
3800 // we have to re-open it when configuration changed
3801 private AlertDialog mSSLCertificateOnErrorDialog;
3802 private WebView mSSLCertificateOnErrorView;
3803 private SslErrorHandler mSSLCertificateOnErrorHandler;
3804 private SslError mSSLCertificateOnErrorError;
3805
3806 // as SSLCertificate has different style for landscape / portrait, we
3807 // have to re-open it when configuration changed
3808 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003809 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003810
3811 // as HttpAuthentication has different style for landscape / portrait, we
3812 // have to re-open it when configuration changed
3813 private AlertDialog mHttpAuthenticationDialog;
3814 private HttpAuthHandler mHttpAuthHandler;
3815
3816 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3817 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003818 ViewGroup.LayoutParams.MATCH_PARENT,
3819 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003820 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3821 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003822 ViewGroup.LayoutParams.MATCH_PARENT,
3823 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003824 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003825 // Google search
3826 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003827 // Wikipedia search
3828 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3829 // Dictionary search
3830 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3831 // Google Mobile Local search
3832 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3833
3834 final static String QUERY_PLACE_HOLDER = "%s";
3835
3836 // "source" parameter for Google search through search key
3837 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3838 // "source" parameter for Google search through goto menu
3839 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3840 // "source" parameter for Google search through simplily type
3841 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3842 // "source" parameter for Google search suggested by the browser
3843 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3844 // "source" parameter for Google search from unknown source
3845 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3846
3847 private final static String LOGTAG = "browser";
3848
The Android Open Source Project0c908882009-03-03 19:32:16 -08003849 private String mLastEnteredUrl;
3850
3851 private PowerManager.WakeLock mWakeLock;
3852 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3853
3854 private Toast mStopToast;
3855
Leon Scroggins68579392009-09-15 15:31:54 -04003856 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003857
Ben Murdochbff2d602009-07-01 20:19:05 +01003858 private LinearLayout mErrorConsoleContainer = null;
3859 private boolean mShouldShowErrorConsole = false;
3860
The Android Open Source Project0c908882009-03-03 19:32:16 -08003861 // As the ids are dynamically created, we can't guarantee that they will
3862 // be in sequence, so this static array maps ids to a window number.
3863 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3864 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3865 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3866 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3867
3868 // monitor platform changes
3869 private IntentFilter mNetworkStateChangedFilter;
3870 private BroadcastReceiver mNetworkStateIntentReceiver;
3871
Grace Klobab4da0ad2009-05-14 14:45:40 -07003872 private BroadcastReceiver mPackageInstallationReceiver;
3873
The Android Open Source Project0c908882009-03-03 19:32:16 -08003874 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003875 final static int COMBO_PAGE = 1;
3876 final static int DOWNLOAD_PAGE = 2;
3877 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003878 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003879
Andrei Popescu540035d2009-09-18 18:59:20 +01003880 // the default <video> poster
3881 private Bitmap mDefaultVideoPoster;
3882 // the video progress view
3883 private View mVideoProgressView;
3884
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003885 /**
3886 * A UrlData class to abstract how the content will be set to WebView.
3887 * This base class uses loadUrl to show the content.
3888 */
3889 private static class UrlData {
3890 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07003891 byte[] mPostData;
3892
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003893 UrlData(String url) {
3894 this.mUrl = url;
3895 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003896
3897 void setPostData(byte[] postData) {
3898 mPostData = postData;
3899 }
3900
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003901 boolean isEmpty() {
3902 return mUrl == null || mUrl.length() == 0;
3903 }
3904
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003905 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07003906 if (mPostData != null) {
3907 webView.postUrl(mUrl, mPostData);
3908 } else {
3909 webView.loadUrl(mUrl);
3910 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003911 }
3912 };
3913
3914 /**
3915 * A subclass of UrlData class that can display inlined content using
3916 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3917 */
3918 private static class InlinedUrlData extends UrlData {
3919 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3920 super(failUrl);
3921 mInlined = inlined;
3922 mMimeType = mimeType;
3923 mEncoding = encoding;
3924 }
3925 String mMimeType;
3926 String mInlined;
3927 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003928 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003929 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01003930 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003931 }
3932
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07003933 @Override
3934 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003935 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3936 }
3937 }
3938
Leon Scroggins1f005d32009-08-10 17:36:42 -04003939 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003940}