blob: 5583466e565a01d7e3bc8f9375b2345e847ed42f [file] [log] [blame]
The Android Open Source Project0c908882009-03-03 19:32:16 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.browser;
18
The Android Open Source Project0c908882009-03-03 19:32:16 -080019import android.app.Activity;
The Android Open Source Project0c908882009-03-03 19:32:16 -080020import android.app.AlertDialog;
21import android.app.ProgressDialog;
22import android.app.SearchManager;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Leon Scroggins58d56c62010-01-28 15:12:40 -050026import android.content.ContentProvider;
27import android.content.ContentProviderClient;
The Android Open Source Project0c908882009-03-03 19:32:16 -080028import android.content.ContentResolver;
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -040029import android.content.ContentUris;
The Android Open Source Project0c908882009-03-03 19:32:16 -080030import android.content.ContentValues;
31import android.content.Context;
32import android.content.DialogInterface;
33import android.content.Intent;
34import android.content.IntentFilter;
Grace Klobab4da0ad2009-05-14 14:45:40 -070035import android.content.pm.PackageInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080036import android.content.pm.PackageManager;
37import android.content.pm.ResolveInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080038import android.content.res.Configuration;
39import android.content.res.Resources;
40import android.database.Cursor;
Leon Scroggins96afcb12009-12-10 12:35:56 -050041import android.database.DatabaseUtils;
The Android Open Source Project0c908882009-03-03 19:32:16 -080042import android.graphics.Bitmap;
Andrei Popescu540035d2009-09-18 18:59:20 +010043import android.graphics.BitmapFactory;
The Android Open Source Project0c908882009-03-03 19:32:16 -080044import android.graphics.Canvas;
The Android Open Source Project0c908882009-03-03 19:32:16 -080045import android.graphics.Picture;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -040046import android.graphics.PixelFormat;
47import android.graphics.Rect;
The Android Open Source Project0c908882009-03-03 19:32:16 -080048import android.graphics.drawable.Drawable;
The Android Open Source Project0c908882009-03-03 19:32:16 -080049import android.net.ConnectivityManager;
Andrei Popescu56199cc2010-01-12 22:39:16 +000050import android.net.NetworkInfo;
The Android Open Source Project0c908882009-03-03 19:32:16 -080051import android.net.Uri;
52import android.net.WebAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -080053import android.net.http.SslCertificate;
54import android.net.http.SslError;
55import android.os.AsyncTask;
56import android.os.Bundle;
57import android.os.Debug;
58import android.os.Environment;
59import android.os.Handler;
The Android Open Source Project0c908882009-03-03 19:32:16 -080060import android.os.Message;
61import android.os.PowerManager;
62import android.os.Process;
The Android Open Source Project0c908882009-03-03 19:32:16 -080063import android.os.ServiceManager;
64import android.os.SystemClock;
The Android Open Source Project0c908882009-03-03 19:32:16 -080065import android.provider.Browser;
Cary Clark5e335a32009-09-22 14:53:11 -040066import android.provider.ContactsContract;
67import android.provider.ContactsContract.Intents.Insert;
The Android Open Source Project0c908882009-03-03 19:32:16 -080068import android.provider.Downloads;
69import android.provider.MediaStore;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -050070import android.speech.RecognizerResultsIntent;
The Android Open Source Project0c908882009-03-03 19:32:16 -080071import android.text.IClipboard;
72import android.text.TextUtils;
73import android.text.format.DateFormat;
Leon Scrogginsb94bf272009-09-25 15:22:08 -040074import android.util.AttributeSet;
The Android Open Source Project0c908882009-03-03 19:32:16 -080075import android.util.Log;
Dianne Hackborn385effd2010-02-24 20:03:04 -080076import android.util.Patterns;
The Android Open Source Project0c908882009-03-03 19:32:16 -080077import android.view.ContextMenu;
78import android.view.Gravity;
79import android.view.KeyEvent;
80import android.view.LayoutInflater;
81import android.view.Menu;
82import android.view.MenuInflater;
83import android.view.MenuItem;
84import android.view.View;
85import android.view.ViewGroup;
86import android.view.Window;
87import android.view.WindowManager;
88import android.view.ContextMenu.ContextMenuInfo;
89import android.view.MenuItem.OnMenuItemClickListener;
The Android Open Source Project0c908882009-03-03 19:32:16 -080090import android.webkit.CookieManager;
91import android.webkit.CookieSyncManager;
92import android.webkit.DownloadListener;
93import android.webkit.HttpAuthHandler;
Grace Klobab4da0ad2009-05-14 14:45:40 -070094import android.webkit.PluginManager;
The Android Open Source Project0c908882009-03-03 19:32:16 -080095import android.webkit.SslErrorHandler;
96import android.webkit.URLUtil;
Leon Clarkecb6cc862009-09-29 18:35:13 +010097import android.webkit.ValueCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -080098import android.webkit.WebChromeClient;
99import android.webkit.WebHistoryItem;
100import android.webkit.WebIconDatabase;
101import android.webkit.WebView;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800102import android.widget.EditText;
103import android.widget.FrameLayout;
104import android.widget.LinearLayout;
105import android.widget.TextView;
106import android.widget.Toast;
Fred Quintana752b6562009-12-18 10:18:26 -0800107import android.accounts.Account;
108import android.accounts.AccountManager;
109import android.accounts.AccountManagerFuture;
110import android.accounts.AuthenticatorException;
111import android.accounts.OperationCanceledException;
112import android.accounts.AccountManagerCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800113
Bjorn Bringertd2670652010-09-13 14:06:41 +0100114import com.android.browser.search.SearchEngine;
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000115import com.android.common.Search;
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500116import com.android.common.speech.LoggingEvents;
Dan Egnor5ee906c2009-11-18 12:11:49 -0800117
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -0400118import java.io.ByteArrayOutputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800119import java.io.File;
Ben Murdoch4f75ba22009-10-27 11:48:28 +0000120import java.io.IOException;
121import java.io.InputStream;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800122import java.net.MalformedURLException;
123import java.net.URI;
Dianne Hackborn99189432009-06-17 18:06:18 -0700124import java.net.URISyntaxException;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800125import java.net.URL;
126import java.net.URLEncoder;
127import java.text.ParseException;
128import java.util.Date;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800129import java.util.HashMap;
Andrei Popescu30995e72010-02-09 16:59:58 +0000130import java.util.HashSet;
Grace Kloba00f54c52010-01-27 14:53:51 -0800131import java.util.Iterator;
Andrei Popescu30995e72010-02-09 16:59:58 +0000132import java.util.List;
Grace Kloba068e48b2010-01-26 18:11:27 -0800133import java.util.Map;
Andrei Popescu30995e72010-02-09 16:59:58 +0000134import java.util.Set;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800135import java.util.regex.Matcher;
136import java.util.regex.Pattern;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800137
138public class BrowserActivity extends Activity
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700139 implements View.OnCreateContextMenuListener, DownloadListener {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800140
Dave Bort31a6d1c2009-04-13 15:56:49 -0700141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
143 */
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
147
Satish Sampath565505b2009-05-29 15:37:27 +0100148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
154
Cary Clarka9771242009-08-11 16:42:26 -0400155 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800156 @Override
157 public Void doInBackground(File... files) {
158 if (files != null) {
159 for (File f : files) {
Cary Clarkd6be1752009-08-12 12:56:42 -0400160 if (!f.delete()) {
161 Log.e(LOGTAG, f.getPath() + " was not deleted");
162 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800163 }
164 }
165 return null;
166 }
167 }
168
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400169 /**
170 * This layout holds everything you see below the status bar, including the
171 * error console, the custom view container, and the webviews.
172 */
173 private FrameLayout mBrowserFrameLayout;
Leon Scroggins81db3662009-06-04 17:45:11 -0400174
Grace Kloba22ac16e2009-10-07 18:00:23 -0700175 @Override
176 public void onCreate(Bundle icicle) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700177 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800178 Log.v(LOGTAG, this + " onStart");
179 }
180 super.onCreate(icicle);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800181 // test the browser in OpenGL
182 // requestWindowFeature(Window.FEATURE_OPENGL);
183
Mike Reedd334bf52010-01-26 15:21:44 -0500184 // enable this to test the browser in 32bit
185 if (false) {
186 getWindow().setFormat(PixelFormat.RGBX_8888);
187 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
188 }
189
The Android Open Source Project0c908882009-03-03 19:32:16 -0800190 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
191
192 mResolver = getContentResolver();
193
Grace Kloba0923d692009-09-23 21:37:25 -0700194 // If this was a web search request, pass it on to the default web
195 // search provider and finish this activity.
196 if (handleWebSearchIntent(getIntent())) {
197 finish();
198 return;
199 }
200
The Android Open Source Project0c908882009-03-03 19:32:16 -0800201 mSecLockIcon = Resources.getSystem().getDrawable(
202 android.R.drawable.ic_secure);
203 mMixLockIcon = Resources.getSystem().getDrawable(
204 android.R.drawable.ic_partial_secure);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800205
Leon Scroggins81db3662009-06-04 17:45:11 -0400206 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
207 .findViewById(com.android.internal.R.id.content);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400208 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
209 .inflate(R.layout.custom_screen, null);
210 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
211 R.id.main_content);
212 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
213 .findViewById(R.id.error_console);
214 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
215 .findViewById(R.id.fullscreen_custom_content);
216 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
Leon Scroggins68579392009-09-15 15:31:54 -0400217 mTitleBar = new TitleBar(this);
Grace Kloba1542f742010-03-17 21:11:15 -0700218 // mTitleBar will be always shown in the fully loaded mode
219 mTitleBar.setProgress(100);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400220 mFakeTitleBar = new TitleBar(this);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800221
222 // Create the tab control and our initial tab
223 mTabControl = new TabControl(this);
224
225 // Open the icon database and retain all the bookmark urls for favicons
226 retainIconsOnStartup();
227
228 // Keep a settings instance handy.
229 mSettings = BrowserSettings.getInstance();
230 mSettings.setTabControl(mTabControl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800231
232 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
233 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
234
Patrick Scott6adacc92010-03-05 08:24:51 -0500235 // Find out if the network is currently up.
236 ConnectivityManager cm = (ConnectivityManager) getSystemService(
237 Context.CONNECTIVITY_SERVICE);
238 NetworkInfo info = cm.getActiveNetworkInfo();
239 if (info != null) {
240 mIsNetworkUp = info.isAvailable();
241 }
242
Grace Klobaa34f6862009-07-31 16:28:17 -0700243 /* enables registration for changes in network status from
244 http stack */
245 mNetworkStateChangedFilter = new IntentFilter();
246 mNetworkStateChangedFilter.addAction(
247 ConnectivityManager.CONNECTIVITY_ACTION);
248 mNetworkStateIntentReceiver = new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context, Intent intent) {
251 if (intent.getAction().equals(
252 ConnectivityManager.CONNECTIVITY_ACTION)) {
Andrei Popescue4c98462010-02-19 15:44:13 +0000253
254 NetworkInfo info = intent.getParcelableExtra(
255 ConnectivityManager.EXTRA_NETWORK_INFO);
256 String typeName = info.getTypeName();
257 String subtypeName = info.getSubtypeName();
258 sendNetworkType(typeName.toLowerCase(),
259 (subtypeName != null ? subtypeName.toLowerCase() : ""));
260
261 onNetworkToggle(info.isAvailable());
Grace Klobaa34f6862009-07-31 16:28:17 -0700262 }
263 }
264 };
265
Grace Kloba615c6c92009-08-03 10:22:44 -0700266 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
267 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
268 filter.addDataScheme("package");
269 mPackageInstallationReceiver = new BroadcastReceiver() {
270 @Override
271 public void onReceive(Context context, Intent intent) {
272 final String action = intent.getAction();
273 final String packageName = intent.getData()
274 .getSchemeSpecificPart();
275 final boolean replacing = intent.getBooleanExtra(
276 Intent.EXTRA_REPLACING, false);
277 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
278 // if it is replacing, refreshPlugins() when adding
279 return;
280 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000281
282 if (sGoogleApps.contains(packageName)) {
283 BrowserActivity.this.packageChanged(packageName,
284 Intent.ACTION_PACKAGE_ADDED.equals(action));
285 }
286
Grace Kloba615c6c92009-08-03 10:22:44 -0700287 PackageManager pm = BrowserActivity.this.getPackageManager();
288 PackageInfo pkgInfo = null;
289 try {
290 pkgInfo = pm.getPackageInfo(packageName,
291 PackageManager.GET_PERMISSIONS);
292 } catch (PackageManager.NameNotFoundException e) {
293 return;
294 }
295 if (pkgInfo != null) {
296 String permissions[] = pkgInfo.requestedPermissions;
297 if (permissions == null) {
298 return;
299 }
300 boolean permissionOk = false;
301 for (String permit : permissions) {
302 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
303 permissionOk = true;
304 break;
305 }
306 }
307 if (permissionOk) {
308 PluginManager.getInstance(BrowserActivity.this)
309 .refreshPlugins(
310 Intent.ACTION_PACKAGE_ADDED
311 .equals(action));
312 }
313 }
314 }
315 };
316 registerReceiver(mPackageInstallationReceiver, filter);
317
The Android Open Source Project0c908882009-03-03 19:32:16 -0800318 if (!mTabControl.restoreState(icicle)) {
319 // clear up the thumbnail directory if we can't restore the state as
320 // none of the files in the directory are referenced any more.
321 new ClearThumbnails().execute(
322 mTabControl.getThumbnailDir().listFiles());
Grace Klobaaab3f092009-07-30 12:29:51 -0700323 // there is no quit on Android. But if we can't restore the state,
324 // we can treat it as a new Browser, remove the old session cookies.
325 CookieManager.getInstance().removeSessionCookie();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800326 final Intent intent = getIntent();
327 final Bundle extra = intent.getExtras();
328 // Create an initial tab.
329 // If the intent is ACTION_VIEW and data is not null, the Browser is
330 // invoked to view the content by another application. In this case,
331 // the tab will be close when exit.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700332 UrlData urlData = getUrlDataFromIntent(intent);
333
Leon Scroggins58d56c62010-01-28 15:12:40 -0500334 String action = intent.getAction();
Grace Kloba22ac16e2009-10-07 18:00:23 -0700335 final Tab t = mTabControl.createNewTab(
Leon Scroggins58d56c62010-01-28 15:12:40 -0500336 (Intent.ACTION_VIEW.equals(action) &&
337 intent.getData() != null)
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500338 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
339 .equals(action),
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700340 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800341 mTabControl.setCurrentTab(t);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800342 attachTabToContentView(t);
343 WebView webView = t.getWebView();
344 if (extra != null) {
345 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
346 if (scale > 0 && scale <= 1000) {
347 webView.setInitialScale(scale);
348 }
349 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800350
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700351 if (urlData.isEmpty()) {
Shimeng (Simon) Wang98d5fce2010-03-16 13:23:39 -0700352 loadUrl(webView, mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800353 } else {
Patrick Scott9d53da02010-02-19 10:19:01 -0500354 loadUrlDataIn(t, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800355 }
356 } else {
357 // TabControl.restoreState() will create a new tab even if
Leon Scroggins1f005d32009-08-10 17:36:42 -0400358 // restoring the state fails.
The Android Open Source Project0c908882009-03-03 19:32:16 -0800359 attachTabToContentView(mTabControl.getCurrentTab());
360 }
Grace Kloba615c6c92009-08-03 10:22:44 -0700361
Feng Qianb3c02da2009-06-29 15:58:08 -0700362 // Read JavaScript flags if it exists.
363 String jsFlags = mSettings.getJsFlags();
364 if (jsFlags.trim().length() != 0) {
365 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
366 }
Andrei Popescu30995e72010-02-09 16:59:58 +0000367 // Work out which packages are installed on the system.
368 getInstalledPackages();
Bjorn Bringerta7611812010-03-24 11:12:02 +0000369
370 // Start watching the default geolocation permissions
371 mSystemAllowGeolocationOrigins
372 = new SystemAllowGeolocationOrigins(getApplicationContext());
373 mSystemAllowGeolocationOrigins.start();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800374 }
375
Leon Scroggins58d56c62010-01-28 15:12:40 -0500376 /**
377 * Feed the previously stored results strings to the BrowserProvider so that
378 * the SearchDialog will show them instead of the standard searches.
379 * @param result String to show on the editable line of the SearchDialog.
380 */
381 /* package */ void showVoiceSearchResults(String result) {
382 ContentProviderClient client = mResolver.acquireContentProviderClient(
383 Browser.BOOKMARKS_URI);
384 ContentProvider prov = client.getLocalContentProvider();
385 BrowserProvider bp = (BrowserProvider) prov;
386 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
387 client.release();
388
Leon Scrogginsfbb3f152010-03-09 17:26:56 -0500389 Bundle bundle = createGoogleSearchSourceBundle(
390 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
391 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
392 startSearch(result, false, bundle, false);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500393 }
394
The Android Open Source Project0c908882009-03-03 19:32:16 -0800395 @Override
396 protected void onNewIntent(Intent intent) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700397 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800398 // When a tab is closed on exit, the current tab index is set to -1.
399 // Reset before proceed as Browser requires the current tab to be set.
400 if (current == null) {
401 // Try to reset the tab in case the index was incorrect.
402 current = mTabControl.getTab(0);
403 if (current == null) {
404 // No tabs at all so just ignore this intent.
405 return;
406 }
407 mTabControl.setCurrentTab(current);
408 attachTabToContentView(current);
409 resetTitleAndIcon(current.getWebView());
410 }
411 final String action = intent.getAction();
412 final int flags = intent.getFlags();
413 if (Intent.ACTION_MAIN.equals(action) ||
414 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
415 // just resume the browser
416 return;
417 }
Leon Scrogginsb8a844d2010-03-18 15:06:15 -0400418 // In case the SearchDialog is open.
419 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
420 .stopSearch();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500421 boolean activateVoiceSearch = RecognizerResultsIntent
422 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800423 if (Intent.ACTION_VIEW.equals(action)
424 || Intent.ACTION_SEARCH.equals(action)
425 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
Leon Scroggins58d56c62010-01-28 15:12:40 -0500426 || Intent.ACTION_WEB_SEARCH.equals(action)
427 || activateVoiceSearch) {
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500428 if (current.isInVoiceSearchMode()) {
429 String title = current.getVoiceDisplayTitle();
430 if (title != null && title.equals(intent.getStringExtra(
431 SearchManager.QUERY))) {
432 // The user submitted the same search as the last voice
433 // search, so do nothing.
434 return;
435 }
Leon Scroggins1fe13a52010-02-09 15:31:26 -0500436 if (Intent.ACTION_SEARCH.equals(action)
437 && current.voiceSearchSourceIsGoogle()) {
438 Intent logIntent = new Intent(
439 LoggingEvents.ACTION_LOG_EVENT);
440 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
441 LoggingEvents.VoiceSearch.QUERY_UPDATED);
442 logIntent.putExtra(
443 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
444 intent.getDataString());
445 sendBroadcast(logIntent);
446 // Note, onPageStarted will revert the voice title bar
447 // When http://b/issue?id=2379215 is fixed, we should update
448 // the title bar here.
449 }
Leon Scroggins3b18ce32010-02-08 17:35:59 -0500450 }
Satish Sampath565505b2009-05-29 15:37:27 +0100451 // If this was a search request (e.g. search query directly typed into the address bar),
452 // pass it on to the default web search provider.
453 if (handleWebSearchIntent(intent)) {
454 return;
455 }
456
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700457 UrlData urlData = getUrlDataFromIntent(intent);
458 if (urlData.isEmpty()) {
459 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800460 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700461
Grace Klobacc634032009-07-28 15:58:19 -0700462 final String appId = intent
463 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
Leon Scroggins47208682010-04-07 17:59:48 -0400464 if ((Intent.ACTION_VIEW.equals(action)
465 // If a voice search has no appId, it means that it came
466 // from the browser. In that case, reuse the current tab.
467 || (activateVoiceSearch && appId != null))
Grace Klobacc634032009-07-28 15:58:19 -0700468 && !getPackageName().equals(appId)
469 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
Grace Kloba22ac16e2009-10-07 18:00:23 -0700470 Tab appTab = mTabControl.getTabFromId(appId);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700471 if (appTab != null) {
472 Log.i(LOGTAG, "Reusing tab for " + appId);
473 // Dismiss the subwindow if applicable.
474 dismissSubWindow(appTab);
475 // Since we might kill the WebView, remove it from the
476 // content view first.
477 removeTabFromContentView(appTab);
478 // Recreate the main WebView after destroying the old one.
479 // If the WebView has the same original url and is on that
480 // page, it can be reused.
481 boolean needsLoad =
Leon Scroggins6eac63e2010-03-15 18:19:14 -0400482 mTabControl.recreateWebView(appTab, urlData);
Ben Murdochbff2d602009-07-01 20:19:05 +0100483
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700484 if (current != appTab) {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400485 switchToTab(mTabControl.getTabIndex(appTab));
486 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500487 loadUrlDataIn(appTab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -0400488 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700489 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -0400490 // If the tab was the current tab, we have to attach
491 // it to the view system again.
492 attachTabToContentView(appTab);
493 if (needsLoad) {
Patrick Scott9d53da02010-02-19 10:19:01 -0500494 loadUrlDataIn(appTab, urlData);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700495 }
496 }
497 return;
Patrick Scottcd115892009-07-16 09:42:58 -0400498 } else {
499 // No matching application tab, try to find a regular tab
500 // with a matching url.
501 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
Leon Scroggins25515f82009-08-19 15:31:58 -0400502 if (appTab != null) {
503 if (current != appTab) {
504 switchToTab(mTabControl.getTabIndex(appTab));
505 }
506 // Otherwise, we are already viewing the correct tab.
Patrick Scottcd115892009-07-16 09:42:58 -0400507 } else {
508 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
509 // will be opened in a new tab unless we have reached
510 // MAX_TABS. Then the url will be opened in the current
511 // tab. If a new tab is created, it will have "true" for
512 // exit on close.
Leon Scroggins1f005d32009-08-10 17:36:42 -0400513 openTabAndShow(urlData, true, appId);
Patrick Scottcd115892009-07-16 09:42:58 -0400514 }
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700515 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800516 } else {
Grace Kloba638d3f42009-11-23 10:35:04 -0800517 if (!urlData.isEmpty()
518 && urlData.mUrl.startsWith("about:debug")) {
519 if ("about:debug.dom".equals(urlData.mUrl)) {
520 current.getWebView().dumpDomTree(false);
521 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
522 current.getWebView().dumpDomTree(true);
523 } else if ("about:debug.render".equals(urlData.mUrl)) {
524 current.getWebView().dumpRenderTree(false);
525 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
526 current.getWebView().dumpRenderTree(true);
527 } else if ("about:debug.display".equals(urlData.mUrl)) {
528 current.getWebView().dumpDisplayTree();
Mike Reed9b78e1d2010-01-13 14:40:52 -0800529 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
530 int index = urlData.mUrl.codePointAt(16) - '0';
531 if (index <= 0 || index > 9) {
532 current.getWebView().setDragTracker(null);
533 } else {
534 current.getWebView().setDragTracker(new MeshTracker(index));
535 }
Grace Kloba638d3f42009-11-23 10:35:04 -0800536 } else {
537 mSettings.toggleDebugSettings();
538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800539 return;
540 }
Leon Scroggins1f005d32009-08-10 17:36:42 -0400541 // Get rid of the subwindow if it exists
542 dismissSubWindow(current);
Leon Scroggins8588d152010-04-15 11:01:53 -0400543 // If the current Tab is being used as an application tab,
544 // remove the association, since the new Intent means that it is
545 // no longer associated with that application.
546 current.setAppId(null);
Patrick Scott9d53da02010-02-19 10:19:01 -0500547 loadUrlDataIn(current, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800548 }
549 }
550 }
551
Satish Sampath565505b2009-05-29 15:37:27 +0100552 private int parseUrlShortcut(String url) {
553 if (url == null) return SHORTCUT_INVALID;
554
555 // FIXME: quick search, need to be customized by setting
556 if (url.length() > 2 && url.charAt(1) == ' ') {
557 switch (url.charAt(0)) {
558 case 'g': return SHORTCUT_GOOGLE_SEARCH;
559 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
560 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
561 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
562 }
563 }
564 return SHORTCUT_INVALID;
565 }
566
567 /**
568 * Launches the default web search activity with the query parameters if the given intent's data
569 * are identified as plain search terms and not URLs/shortcuts.
570 * @return true if the intent was handled and web search activity was launched, false if not.
571 */
572 private boolean handleWebSearchIntent(Intent intent) {
573 if (intent == null) return false;
574
575 String url = null;
576 final String action = intent.getAction();
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -0500577 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
578 action)) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500579 return false;
580 }
Satish Sampath565505b2009-05-29 15:37:27 +0100581 if (Intent.ACTION_VIEW.equals(action)) {
Grace Kloba1e705052009-09-29 13:13:36 -0700582 Uri data = intent.getData();
583 if (data != null) url = data.toString();
Satish Sampath565505b2009-05-29 15:37:27 +0100584 } else if (Intent.ACTION_SEARCH.equals(action)
585 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
586 || Intent.ACTION_WEB_SEARCH.equals(action)) {
587 url = intent.getStringExtra(SearchManager.QUERY);
588 }
Bjorn Bringert04851702009-09-22 10:36:01 +0100589 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
590 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
Satish Sampath565505b2009-05-29 15:37:27 +0100591 }
592
593 /**
594 * Launches the default web search activity with the query parameters if the given url string
595 * was identified as plain search terms and not URL/shortcut.
596 * @return true if the request was handled and web search activity was launched, false if not.
597 */
Bjorn Bringert04851702009-09-22 10:36:01 +0100598 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100599 if (inUrl == null) return false;
600
601 // In general, we shouldn't modify URL from Intent.
602 // But currently, we get the user-typed URL from search box as well.
603 String url = fixUrl(inUrl).trim();
604
605 // URLs and site specific search shortcuts are handled by the regular flow of control, so
606 // return early.
Dan Egnor5ee906c2009-11-18 12:11:49 -0800607 if (Patterns.WEB_URL.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +0100608 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +0100609 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
610 return false;
611 }
612
Leon Scroggins8d06e362010-03-24 14:45:57 -0400613 final ContentResolver cr = mResolver;
614 final String newUrl = url;
615 new AsyncTask<Void, Void, Void>() {
616 protected Void doInBackground(Void... unused) {
617 Browser.updateVisitedHistory(cr, newUrl, false);
618 Browser.addSearchUrl(cr, newUrl);
619 return null;
620 }
621 }.execute();
Satish Sampath565505b2009-05-29 15:37:27 +0100622
Bjorn Bringertd2670652010-09-13 14:06:41 +0100623 SearchEngine searchEngine = mSettings.getSearchEngine();
624 if (searchEngine == null) return false;
625 searchEngine.startSearch(this, url, appData, extraData);
Satish Sampath565505b2009-05-29 15:37:27 +0100626
627 return true;
628 }
629
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700630 private UrlData getUrlDataFromIntent(Intent intent) {
Leon Scroggins58d56c62010-01-28 15:12:40 -0500631 String url = "";
Grace Kloba068e48b2010-01-26 18:11:27 -0800632 Map<String, String> headers = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800633 if (intent != null) {
634 final String action = intent.getAction();
635 if (Intent.ACTION_VIEW.equals(action)) {
636 url = smartUrlFilter(intent.getData());
637 if (url != null && url.startsWith("content:")) {
638 /* Append mimetype so webview knows how to display */
639 String mimeType = intent.resolveType(getContentResolver());
640 if (mimeType != null) {
641 url += "?" + mimeType;
642 }
643 }
Grace Kloba068e48b2010-01-26 18:11:27 -0800644 if (url != null && url.startsWith("http")) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800645 final Bundle pairs = intent
646 .getBundleExtra(Browser.EXTRA_HEADERS);
Grace Kloba2d508ed2010-01-28 11:39:15 -0800647 if (pairs != null && !pairs.isEmpty()) {
Grace Kloba00f54c52010-01-27 14:53:51 -0800648 Iterator<String> iter = pairs.keySet().iterator();
Grace Kloba068e48b2010-01-26 18:11:27 -0800649 headers = new HashMap<String, String>();
Grace Kloba00f54c52010-01-27 14:53:51 -0800650 while (iter.hasNext()) {
651 String key = iter.next();
652 headers.put(key, pairs.getString(key));
Grace Kloba068e48b2010-01-26 18:11:27 -0800653 }
654 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700655 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800656 } else if (Intent.ACTION_SEARCH.equals(action)
657 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
658 || Intent.ACTION_WEB_SEARCH.equals(action)) {
659 url = intent.getStringExtra(SearchManager.QUERY);
660 if (url != null) {
661 mLastEnteredUrl = url;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800662 // In general, we shouldn't modify URL from Intent.
663 // But currently, we get the user-typed URL from search box as well.
664 url = fixUrl(url);
665 url = smartUrlFilter(url);
Leon Scroggins8d06e362010-03-24 14:45:57 -0400666 final ContentResolver cr = mResolver;
667 final String newUrl = url;
668 new AsyncTask<Void, Void, Void>() {
669 protected Void doInBackground(Void... unused) {
670 Browser.updateVisitedHistory(cr, newUrl, false);
671 return null;
672 }
673 }.execute();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800674 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
675 if (url.contains(searchSource)) {
676 String source = null;
677 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
678 if (appData != null) {
Bjorn Bringert10d1cca2010-02-10 14:22:12 +0000679 source = appData.getString(Search.SOURCE);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800680 }
681 if (TextUtils.isEmpty(source)) {
682 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
683 }
684 url = url.replace(searchSource, "&source=android-"+source+"&");
685 }
686 }
687 }
688 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500689 return new UrlData(url, headers, intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800690 }
Leon Scroggins58d56c62010-01-28 15:12:40 -0500691 /* package */ void showVoiceTitleBar(String title) {
692 mTitleBar.setInVoiceMode(true);
693 mFakeTitleBar.setInVoiceMode(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800694
Leon Scroggins58d56c62010-01-28 15:12:40 -0500695 mTitleBar.setDisplayTitle(title);
696 mFakeTitleBar.setDisplayTitle(title);
697 }
698 /* package */ void revertVoiceTitleBar() {
699 mTitleBar.setInVoiceMode(false);
700 mFakeTitleBar.setInVoiceMode(false);
701
Leon Scroggins003a5dd2010-03-10 12:13:14 -0500702 mTitleBar.setDisplayTitle(mUrl);
703 mFakeTitleBar.setDisplayTitle(mUrl);
Leon Scroggins58d56c62010-01-28 15:12:40 -0500704 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800705 /* package */ static String fixUrl(String inUrl) {
Cary Clark652ff872009-09-10 13:34:44 -0400706 // FIXME: Converting the url to lower case
707 // duplicates functionality in smartUrlFilter().
708 // However, changing all current callers of fixUrl to
709 // call smartUrlFilter in addition may have unwanted
710 // consequences, and is deferred for now.
711 int colon = inUrl.indexOf(':');
712 boolean allLower = true;
713 for (int index = 0; index < colon; index++) {
714 char ch = inUrl.charAt(index);
715 if (!Character.isLetter(ch)) {
716 break;
717 }
718 allLower &= Character.isLowerCase(ch);
719 if (index == colon - 1 && !allLower) {
720 inUrl = inUrl.substring(0, colon).toLowerCase()
721 + inUrl.substring(colon);
722 }
723 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800724 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
725 return inUrl;
726 if (inUrl.startsWith("http:") ||
727 inUrl.startsWith("https:")) {
728 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
729 inUrl = inUrl.replaceFirst("/", "//");
730 } else inUrl = inUrl.replaceFirst(":", "://");
731 }
732 return inUrl;
733 }
734
Grace Kloba22ac16e2009-10-07 18:00:23 -0700735 @Override
736 protected void onResume() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800737 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -0700738 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800739 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
740 }
741
742 if (!mActivityInPause) {
743 Log.e(LOGTAG, "BrowserActivity is already resumed.");
744 return;
745 }
746
Mike Reed7bfa63b2009-05-28 11:08:32 -0400747 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800748 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400749 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800750
751 if (mWakeLock.isHeld()) {
752 mHandler.removeMessages(RELEASE_WAKELOCK);
753 mWakeLock.release();
754 }
755
The Android Open Source Project0c908882009-03-03 19:32:16 -0800756 registerReceiver(mNetworkStateIntentReceiver,
757 mNetworkStateChangedFilter);
758 WebView.enablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800759 }
760
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400761 /**
762 * Since the actual title bar is embedded in the WebView, and removing it
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400763 * would change its appearance, use a different TitleBar to show overlayed
764 * at the top of the screen, when the menu is open or the page is loading.
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400765 */
766 private TitleBar mFakeTitleBar;
767
768 /**
769 * Keeps track of whether the options menu is open. This is important in
770 * determining whether to show or hide the title bar overlay.
771 */
772 private boolean mOptionsMenuOpen;
773
774 /**
775 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
776 * of whether the configuration has changed. The first onMenuOpened call
777 * after a configuration change is simply a reopening of the same menu
778 * (i.e. mIconView did not change).
779 */
780 private boolean mConfigChanged;
781
782 /**
783 * Whether or not the options menu is in its smaller, icon menu form. When
784 * true, we want the title bar overlay to be up. When false, we do not.
785 * Only meaningful if mOptionsMenuOpen is true.
786 */
787 private boolean mIconView;
788
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400789 @Override
790 public boolean onMenuOpened(int featureId, Menu menu) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400791 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
792 if (mOptionsMenuOpen) {
793 if (mConfigChanged) {
794 // We do not need to make any changes to the state of the
795 // title bar, since the only thing that happened was a
796 // change in orientation
797 mConfigChanged = false;
798 } else {
799 if (mIconView) {
800 // Switching the menu to expanded view, so hide the
801 // title bar.
802 hideFakeTitleBar();
803 mIconView = false;
804 } else {
805 // Switching the menu back to icon view, so show the
806 // title bar once again.
807 showFakeTitleBar();
808 mIconView = true;
809 }
810 }
811 } else {
812 // The options menu is closed, so open it, and show the title
813 showFakeTitleBar();
814 mOptionsMenuOpen = true;
815 mConfigChanged = false;
816 mIconView = true;
817 }
818 }
Leon Scrogginsa81a7642009-08-31 17:05:41 -0400819 return true;
820 }
821
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400822 private void showFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400823 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
Grace Kloba847c25b2010-03-30 16:00:26 -0700824 && !mActivityInPause) {
825 WebView mainView = mTabControl.getCurrentWebView();
826 // if there is no current WebView, don't show the faked title bar;
Grace Kloba65190702010-04-02 23:37:26 -0700827 if (mainView == null) {
Cary Clarka0464552009-09-29 13:00:45 -0400828 return;
829 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400830
831 WindowManager manager
832 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
833
834 // Add the title bar to the window manager so it can receive touches
835 // while the menu is up
836 WindowManager.LayoutParams params
837 = new WindowManager.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -0800838 ViewGroup.LayoutParams.MATCH_PARENT,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400839 ViewGroup.LayoutParams.WRAP_CONTENT,
Grace Kloba847c25b2010-03-30 16:00:26 -0700840 WindowManager.LayoutParams.TYPE_APPLICATION,
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400841 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
Leon Scroggins68549862009-09-21 16:02:01 -0400842 PixelFormat.TRANSLUCENT);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400843 params.gravity = Gravity.TOP;
Grace Kloba847c25b2010-03-30 16:00:26 -0700844 boolean atTop = mainView.getScrollY() == 0;
Leon Scroggins83932c72009-09-30 11:55:54 -0400845 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
Grace Kloba13f9ace2010-03-18 21:44:14 -0700846 manager.addView(mFakeTitleBar, params);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400847 }
848 }
849
850 @Override
851 public void onOptionsMenuClosed(Menu menu) {
852 mOptionsMenuOpen = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -0400853 if (!mInLoad) {
854 hideFakeTitleBar();
855 } else if (!mIconView) {
856 // The page is currently loading, and we are in expanded mode, so
857 // we were not showing the menu. Show it once again. It will be
858 // removed when the page finishes.
859 showFakeTitleBar();
860 }
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400861 }
Grace Kloba22ac16e2009-10-07 18:00:23 -0700862
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400863 private void hideFakeTitleBar() {
Leon Scrogginsfe87bd32009-10-06 10:10:00 -0400864 if (mFakeTitleBar.getParent() == null) return;
Leon Scroggins20329572009-09-23 17:42:41 -0400865 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
Grace Kloba13f9ace2010-03-18 21:44:14 -0700866 mFakeTitleBar.getLayoutParams();
Leon Scroggins20329572009-09-23 17:42:41 -0400867 WebView mainView = mTabControl.getCurrentWebView();
868 // Although we decided whether or not to animate based on the current
869 // scroll position, the scroll position may have changed since the
870 // fake title bar was displayed. Make sure it has the appropriate
871 // animation/lack thereof before removing.
872 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
Leon Scroggins83932c72009-09-30 11:55:54 -0400873 ? 0 : R.style.TitleBar;
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400874 WindowManager manager
875 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Grace Kloba13f9ace2010-03-18 21:44:14 -0700876 manager.updateViewLayout(mFakeTitleBar, params);
877 manager.removeView(mFakeTitleBar);
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400878 }
879
The Android Open Source Project0c908882009-03-03 19:32:16 -0800880 /**
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400881 * Special method for the fake title bar to call when displaying its context
882 * menu, since it is in its own Window, and its parent does not show a
883 * context menu.
884 */
885 /* package */ void showTitleBarContextMenu() {
Cary Clark65f4a3c2009-09-28 17:05:06 -0400886 if (null == mTitleBar.getParent()) {
887 return;
888 }
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400889 openContextMenu(mTitleBar);
890 }
891
Leon Scrogginsb2b19f52009-10-09 16:10:00 -0400892 @Override
893 public void onContextMenuClosed(Menu menu) {
894 super.onContextMenuClosed(menu);
895 if (mInLoad) {
896 showFakeTitleBar();
897 }
898 }
899
Leon Scrogginsc6fa1102009-09-21 10:40:01 -0400900 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -0800901 * onSaveInstanceState(Bundle map)
902 * onSaveInstanceState is called right before onStop(). The map contains
903 * the saved state.
904 */
Grace Kloba22ac16e2009-10-07 18:00:23 -0700905 @Override
906 protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700907 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800908 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
909 }
910 // the default implementation requires each view to have an id. As the
911 // browser handles the state itself and it doesn't use id for the views,
912 // don't call the default implementation. Otherwise it will trigger the
913 // warning like this, "couldn't save which view has focus because the
914 // focused view XXX has no id".
915
916 // Save all the tabs
917 mTabControl.saveState(outState);
918 }
919
Grace Kloba22ac16e2009-10-07 18:00:23 -0700920 @Override
921 protected void onPause() {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800922 super.onPause();
923
924 if (mActivityInPause) {
925 Log.e(LOGTAG, "BrowserActivity is already paused.");
926 return;
927 }
928
Mike Reed7bfa63b2009-05-28 11:08:32 -0400929 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800930 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -0400931 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800932 mWakeLock.acquire();
933 mHandler.sendMessageDelayed(mHandler
934 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
935 }
936
Leon Scrogginsa2ab6a72009-09-11 11:49:52 -0400937 // FIXME: This removes the active tabs page and resets the menu to
938 // MAIN_MENU. A better solution might be to do this work in onNewIntent
939 // but then we would need to save it in onSaveInstanceState and restore
940 // it in onCreate/onRestoreInstanceState
941 if (mActiveTabsPage != null) {
942 removeActiveTabPage(true);
943 }
944
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 cancelStopToast();
946
947 // unregister network state listener
948 unregisterReceiver(mNetworkStateIntentReceiver);
949 WebView.disablePlatformNotifications();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 }
951
Grace Kloba22ac16e2009-10-07 18:00:23 -0700952 @Override
953 protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -0700954 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800955 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
956 }
957 super.onDestroy();
Grace Kloba0923d692009-09-23 21:37:25 -0700958
Leon Scroggins8d5fa432009-10-02 15:55:59 -0400959 if (mUploadMessage != null) {
960 mUploadMessage.onReceiveValue(null);
961 mUploadMessage = null;
962 }
963
Grace Kloba0923d692009-09-23 21:37:25 -0700964 if (mTabControl == null) return;
965
Grace Kloba1fc98a32009-10-21 13:23:08 -0700966 // Remove the fake title bar if it is there
967 hideFakeTitleBar();
968
The Android Open Source Project0c908882009-03-03 19:32:16 -0800969 // Remove the current tab and sub window
Grace Kloba22ac16e2009-10-07 18:00:23 -0700970 Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -0700971 if (t != null) {
972 dismissSubWindow(t);
973 removeTabFromContentView(t);
974 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800975 // Destroy all the tabs
976 mTabControl.destroy();
977 WebIconDatabase.getInstance().close();
The Android Open Source Project0c908882009-03-03 19:32:16 -0800978
Grace Klobab4da0ad2009-05-14 14:45:40 -0700979 unregisterReceiver(mPackageInstallationReceiver);
Bjorn Bringerta7611812010-03-24 11:12:02 +0000980
981 // Stop watching the default geolocation permissions
982 mSystemAllowGeolocationOrigins.stop();
983 mSystemAllowGeolocationOrigins = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800984 }
985
986 @Override
987 public void onConfigurationChanged(Configuration newConfig) {
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -0400988 mConfigChanged = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -0800989 super.onConfigurationChanged(newConfig);
990
991 if (mPageInfoDialog != null) {
992 mPageInfoDialog.dismiss();
993 showPageInfo(
994 mPageInfoView,
Leon Scrogginsc7b92f82010-01-11 18:17:31 -0500995 mPageInfoFromShowSSLCertificateOnError);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800996 }
997 if (mSSLCertificateDialog != null) {
998 mSSLCertificateDialog.dismiss();
999 showSSLCertificate(
1000 mSSLCertificateView);
1001 }
1002 if (mSSLCertificateOnErrorDialog != null) {
1003 mSSLCertificateOnErrorDialog.dismiss();
1004 showSSLCertificateOnError(
1005 mSSLCertificateOnErrorView,
1006 mSSLCertificateOnErrorHandler,
1007 mSSLCertificateOnErrorError);
1008 }
1009 if (mHttpAuthenticationDialog != null) {
1010 String title = ((TextView) mHttpAuthenticationDialog
1011 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1012 .toString();
1013 String name = ((TextView) mHttpAuthenticationDialog
1014 .findViewById(R.id.username_edit)).getText().toString();
1015 String password = ((TextView) mHttpAuthenticationDialog
1016 .findViewById(R.id.password_edit)).getText().toString();
1017 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1018 .getId();
1019 mHttpAuthenticationDialog.dismiss();
1020 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1021 name, password, focusId);
1022 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001023 }
1024
Grace Kloba22ac16e2009-10-07 18:00:23 -07001025 @Override
1026 public void onLowMemory() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001027 super.onLowMemory();
1028 mTabControl.freeMemory();
1029 }
1030
Cary Clarkff4d92c2010-03-25 11:17:03 -04001031 private void resumeWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001032 Tab tab = mTabControl.getCurrentTab();
Cary Clarkff4d92c2010-03-25 11:17:03 -04001033 if (tab == null) return; // monkey can trigger this
Grace Kloba22ac16e2009-10-07 18:00:23 -07001034 boolean inLoad = tab.inLoad();
1035 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001036 CookieSyncManager.getInstance().startSync();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001037 WebView w = tab.getWebView();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001038 if (w != null) {
1039 w.resumeTimers();
1040 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001041 }
1042 }
1043
Mike Reed7bfa63b2009-05-28 11:08:32 -04001044 private boolean pauseWebViewTimers() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001045 Tab tab = mTabControl.getCurrentTab();
1046 boolean inLoad = tab.inLoad();
1047 if (mActivityInPause && !inLoad) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001048 CookieSyncManager.getInstance().stopSync();
1049 WebView w = mTabControl.getCurrentWebView();
1050 if (w != null) {
1051 w.pauseTimers();
1052 }
1053 return true;
1054 } else {
1055 return false;
1056 }
1057 }
1058
The Android Open Source Project0c908882009-03-03 19:32:16 -08001059 // Open the icon database and retain all the icons for visited sites.
1060 private void retainIconsOnStartup() {
1061 final WebIconDatabase db = WebIconDatabase.getInstance();
1062 db.open(getDir("icons", 0).getPath());
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001063 Cursor c = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001064 try {
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001065 c = Browser.getAllBookmarks(mResolver);
1066 if (c.moveToFirst()) {
1067 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1068 do {
1069 String url = c.getString(urlIndex);
1070 db.retainIconForPageUrl(url);
1071 } while (c.moveToNext());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001072 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001073 } catch (IllegalStateException e) {
1074 Log.e(LOGTAG, "retainIconsOnStartup", e);
Leon Scroggins2c0f6112010-03-12 18:09:39 -05001075 } finally {
1076 if (c!= null) c.close();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001077 }
1078 }
1079
1080 // Helper method for getting the top window.
1081 WebView getTopWindow() {
1082 return mTabControl.getCurrentTopWebView();
1083 }
1084
Grace Kloba22ac16e2009-10-07 18:00:23 -07001085 TabControl getTabControl() {
1086 return mTabControl;
1087 }
1088
The Android Open Source Project0c908882009-03-03 19:32:16 -08001089 @Override
1090 public boolean onCreateOptionsMenu(Menu menu) {
1091 super.onCreateOptionsMenu(menu);
1092
1093 MenuInflater inflater = getMenuInflater();
1094 inflater.inflate(R.menu.browser, menu);
1095 mMenu = menu;
1096 updateInLoadMenuItems();
1097 return true;
1098 }
1099
1100 /**
1101 * As the menu can be open when loading state changes
1102 * we must manually update the state of the stop/reload menu
1103 * item
1104 */
1105 private void updateInLoadMenuItems() {
1106 if (mMenu == null) {
1107 return;
1108 }
1109 MenuItem src = mInLoad ?
1110 mMenu.findItem(R.id.stop_menu_id):
1111 mMenu.findItem(R.id.reload_menu_id);
1112 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1113 dest.setIcon(src.getIcon());
1114 dest.setTitle(src.getTitle());
1115 }
1116
1117 @Override
1118 public boolean onContextItemSelected(MenuItem item) {
1119 // chording is not an issue with context menus, but we use the same
1120 // options selector, so set mCanChord to true so we can access them.
1121 mCanChord = true;
1122 int id = item.getItemId();
Leon Scroggins96afcb12009-12-10 12:35:56 -05001123 boolean result = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001124 switch (id) {
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001125 // For the context menu from the title bar
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001126 case R.id.title_bar_copy_page_url:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001127 Tab currentTab = mTabControl.getCurrentTab();
1128 if (null == currentTab) {
1129 result = false;
1130 break;
1131 }
1132 WebView mainView = currentTab.getWebView();
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001133 if (null == mainView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001134 result = false;
1135 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001136 }
Leon Scroggins96afcb12009-12-10 12:35:56 -05001137 copy(mainView.getUrl());
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001138 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001139 // -- Browser context menu
1140 case R.id.open_context_menu_id:
1141 case R.id.open_newtab_context_menu_id:
1142 case R.id.bookmark_context_menu_id:
1143 case R.id.save_link_context_menu_id:
1144 case R.id.share_link_context_menu_id:
1145 case R.id.copy_link_context_menu_id:
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001146 final WebView webView = getTopWindow();
1147 if (null == webView) {
Leon Scroggins96afcb12009-12-10 12:35:56 -05001148 result = false;
1149 break;
Leon Scrogginsc6fa1102009-09-21 10:40:01 -04001150 }
1151 final HashMap hrefMap = new HashMap();
1152 hrefMap.put("webview", webView);
1153 final Message msg = mHandler.obtainMessage(
1154 FOCUS_NODE_HREF, id, 0, hrefMap);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001155 webView.requestFocusNodeHref(msg);
1156 break;
1157
1158 default:
1159 // For other context menus
Leon Scroggins96afcb12009-12-10 12:35:56 -05001160 result = onOptionsItemSelected(item);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001161 }
1162 mCanChord = false;
Leon Scroggins96afcb12009-12-10 12:35:56 -05001163 return result;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001164 }
1165
1166 private Bundle createGoogleSearchSourceBundle(String source) {
1167 Bundle bundle = new Bundle();
Bjorn Bringert10d1cca2010-02-10 14:22:12 +00001168 bundle.putString(Search.SOURCE, source);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001169 return bundle;
1170 }
1171
Leon Scroggins8ad29922010-02-16 12:33:55 -05001172 /* package */ void editUrl() {
Leon Scroggins68579392009-09-15 15:31:54 -04001173 if (mOptionsMenuOpen) closeOptionsMenu();
Leon Scroggins5bbe9802009-07-31 13:10:55 -04001174 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
Grace Kloba83f47342009-07-20 10:44:31 -07001175 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
Leon Scroggins8ad29922010-02-16 12:33:55 -05001176 null, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001177 }
1178
Leon Scroggins8ad29922010-02-16 12:33:55 -05001179 /**
1180 * Overriding this to insert a local information bundle
1181 */
The Android Open Source Project0c908882009-03-03 19:32:16 -08001182 @Override
1183 public void startSearch(String initialQuery, boolean selectInitialQuery,
1184 Bundle appSearchData, boolean globalSearch) {
1185 if (appSearchData == null) {
1186 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1187 }
Leon Scroggins III430057d2010-09-14 10:57:37 -04001188
1189 SearchEngine searchEngine = mSettings.getSearchEngine();
1190 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
1191 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
1192 }
1193
The Android Open Source Project0c908882009-03-03 19:32:16 -08001194 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1195 }
1196
Leon Scroggins1f005d32009-08-10 17:36:42 -04001197 /**
1198 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1199 * results in changing tabs.
Leon Scroggins160a7e72009-08-14 18:28:01 -04001200 * @param index Index of the tab to change to, as defined by
1201 * mTabControl.getTabIndex(Tab t).
1202 * @return boolean True if we successfully switched to a different tab. If
1203 * the indexth tab is null, or if that tab is the same as
1204 * the current one, return false.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001205 */
Leon Scroggins160a7e72009-08-14 18:28:01 -04001206 /* package */ boolean switchToTab(int index) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001207 Tab tab = mTabControl.getTab(index);
1208 Tab currentTab = mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001209 if (tab == null || tab == currentTab) {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001210 return false;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001211 }
1212 if (currentTab != null) {
1213 // currentTab may be null if it was just removed. In that case,
1214 // we do not need to remove it
1215 removeTabFromContentView(currentTab);
1216 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001217 mTabControl.setCurrentTab(tab);
1218 attachTabToContentView(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001219 resetTitleIconAndProgress();
1220 updateLockIconToLatest();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001221 return true;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001222 }
1223
Grace Kloba22ac16e2009-10-07 18:00:23 -07001224 /* package */ Tab openTabToHomePage() {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001225 return openTabAndShow(mSettings.getHomePage(), false, null);
1226 }
1227
Leon Scroggins1f005d32009-08-10 17:36:42 -04001228 /* package */ void closeCurrentWindow() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001229 final Tab current = mTabControl.getCurrentTab();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001230 if (mTabControl.getTabCount() == 1) {
Leon Scroggins30444232009-09-04 18:36:20 -04001231 // This is the last tab. Open a new one, with the home
1232 // page and close the current one.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001233 openTabToHomePage();
Leon Scroggins160a7e72009-08-14 18:28:01 -04001234 closeTab(current);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001235 return;
1236 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07001237 final Tab parent = current.getParentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04001238 int indexToShow = -1;
1239 if (parent != null) {
1240 indexToShow = mTabControl.getTabIndex(parent);
1241 } else {
Leon Scroggins160a7e72009-08-14 18:28:01 -04001242 final int currentIndex = mTabControl.getCurrentIndex();
1243 // Try to move to the tab to the right
1244 indexToShow = currentIndex + 1;
1245 if (indexToShow > mTabControl.getTabCount() - 1) {
1246 // Try to move to the tab to the left
1247 indexToShow = currentIndex - 1;
Leon Scroggins1f005d32009-08-10 17:36:42 -04001248 }
1249 }
Leon Scroggins160a7e72009-08-14 18:28:01 -04001250 if (switchToTab(indexToShow)) {
1251 // Close window
1252 closeTab(current);
1253 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001254 }
1255
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001256 private ActiveTabsPage mActiveTabsPage;
1257
1258 /**
1259 * Remove the active tabs page.
1260 * @param needToAttach If true, the active tabs page did not attach a tab
1261 * to the content view, so we need to do that here.
1262 */
1263 /* package */ void removeActiveTabPage(boolean needToAttach) {
1264 mContentView.removeView(mActiveTabsPage);
1265 mActiveTabsPage = null;
1266 mMenuState = R.id.MAIN_MENU;
1267 if (needToAttach) {
1268 attachTabToContentView(mTabControl.getCurrentTab());
1269 }
1270 getTopWindow().requestFocus();
1271 }
1272
The Android Open Source Project0c908882009-03-03 19:32:16 -08001273 @Override
1274 public boolean onOptionsItemSelected(MenuItem item) {
1275 if (!mCanChord) {
1276 // The user has already fired a shortcut with this hold down of the
1277 // menu key.
1278 return false;
1279 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001280 if (null == getTopWindow()) {
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001281 return false;
1282 }
Grace Kloba6ee9c492009-07-13 10:04:34 -07001283 if (mMenuIsDown) {
1284 // The shortcut action consumes the MENU. Even if it is still down,
1285 // it won't trigger the next shortcut action. In the case of the
1286 // shortcut action triggering a new activity, like Bookmarks, we
1287 // won't get onKeyUp for MENU. So it is important to reset it here.
1288 mMenuIsDown = false;
1289 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 switch (item.getItemId()) {
1291 // -- Main menu
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001292 case R.id.new_tab_menu_id:
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001293 openTabToHomePage();
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001294 break;
1295
Leon Scroggins64b80f32009-08-07 12:03:34 -04001296 case R.id.goto_menu_id:
Leon Scroggins8ad29922010-02-16 12:33:55 -05001297 editUrl();
Leon Scrogginsb3a5bed2009-09-28 11:21:56 -04001298 break;
1299
1300 case R.id.bookmarks_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001301 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001302 break;
1303
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001304 case R.id.active_tabs_menu_id:
1305 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1306 removeTabFromContentView(mTabControl.getCurrentTab());
Leon Scroggins43de6162009-09-14 19:59:58 -04001307 hideFakeTitleBar();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001308 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1309 mActiveTabsPage.requestFocus();
1310 mMenuState = EMPTY_MENU;
1311 break;
1312
Leon Scroggins1f005d32009-08-10 17:36:42 -04001313 case R.id.add_bookmark_menu_id:
1314 Intent i = new Intent(BrowserActivity.this,
1315 AddBookmarkPage.class);
1316 WebView w = getTopWindow();
1317 i.putExtra("url", w.getUrl());
1318 i.putExtra("title", w.getTitle());
Grace Kloba83cdb2c2009-09-16 00:48:57 -07001319 i.putExtra("touch_icon_url", w.getTouchIconUrl());
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01001320 i.putExtra("thumbnail", createScreenshot(w));
Leon Scroggins1f005d32009-08-10 17:36:42 -04001321 startActivity(i);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001322 break;
1323
1324 case R.id.stop_reload_menu_id:
1325 if (mInLoad) {
1326 stopLoading();
1327 } else {
1328 getTopWindow().reload();
1329 }
1330 break;
1331
1332 case R.id.back_menu_id:
1333 getTopWindow().goBack();
1334 break;
1335
1336 case R.id.forward_menu_id:
1337 getTopWindow().goForward();
1338 break;
1339
1340 case R.id.close_menu_id:
1341 // Close the subwindow if it exists.
1342 if (mTabControl.getCurrentSubWindow() != null) {
1343 dismissSubWindow(mTabControl.getCurrentTab());
1344 break;
1345 }
Leon Scroggins1f005d32009-08-10 17:36:42 -04001346 closeCurrentWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001347 break;
1348
1349 case R.id.homepage_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07001350 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001351 if (current != null) {
1352 dismissSubWindow(current);
Leon Scroggins92472e82010-02-17 16:32:28 -05001353 loadUrl(current.getWebView(), mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001354 }
1355 break;
1356
1357 case R.id.preferences_menu_id:
1358 Intent intent = new Intent(this,
1359 BrowserPreferencesPage.class);
Leon Scrogginsd5304942009-12-10 16:11:39 -05001360 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1361 getTopWindow().getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001362 startActivityForResult(intent, PREFERENCES_PAGE);
1363 break;
1364
1365 case R.id.find_menu_id:
1366 if (null == mFindDialog) {
1367 mFindDialog = new FindDialog(this);
1368 }
1369 mFindDialog.setWebView(getTopWindow());
1370 mFindDialog.show();
Cary Clark7d3ac792010-03-03 10:11:44 -05001371 getTopWindow().setFindIsUp(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001372 mMenuState = EMPTY_MENU;
1373 break;
1374
1375 case R.id.select_text_id:
1376 getTopWindow().emulateShiftHeld();
1377 break;
1378 case R.id.page_info_menu_id:
1379 showPageInfo(mTabControl.getCurrentTab(), false);
1380 break;
1381
1382 case R.id.classic_history_menu_id:
Leon Scroggins30444232009-09-04 18:36:20 -04001383 bookmarksOrHistoryPicker(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001384 break;
1385
Leon Scroggins96afcb12009-12-10 12:35:56 -05001386 case R.id.title_bar_share_page_url:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 case R.id.share_page_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05001388 Tab currentTab = mTabControl.getCurrentTab();
1389 if (null == currentTab) {
1390 mCanChord = false;
1391 return false;
1392 }
1393 currentTab.populatePickerData();
1394 sharePage(this, currentTab.getTitle(),
1395 currentTab.getUrl(), currentTab.getFavicon(),
1396 createScreenshot(currentTab.getWebView()));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001397 break;
1398
1399 case R.id.dump_nav_menu_id:
1400 getTopWindow().debugDump();
1401 break;
1402
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001403 case R.id.dump_counters_menu_id:
1404 getTopWindow().dumpV8Counters();
1405 break;
1406
The Android Open Source Project0c908882009-03-03 19:32:16 -08001407 case R.id.zoom_in_menu_id:
1408 getTopWindow().zoomIn();
1409 break;
1410
1411 case R.id.zoom_out_menu_id:
1412 getTopWindow().zoomOut();
1413 break;
1414
1415 case R.id.view_downloads_menu_id:
1416 viewDownloads(null);
1417 break;
1418
The Android Open Source Project0c908882009-03-03 19:32:16 -08001419 case R.id.window_one_menu_id:
1420 case R.id.window_two_menu_id:
1421 case R.id.window_three_menu_id:
1422 case R.id.window_four_menu_id:
1423 case R.id.window_five_menu_id:
1424 case R.id.window_six_menu_id:
1425 case R.id.window_seven_menu_id:
1426 case R.id.window_eight_menu_id:
1427 {
1428 int menuid = item.getItemId();
1429 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1430 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001431 Tab desiredTab = mTabControl.getTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001432 if (desiredTab != null &&
1433 desiredTab != mTabControl.getCurrentTab()) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001434 switchToTab(id);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001435 }
1436 break;
1437 }
1438 }
1439 }
1440 break;
1441
1442 default:
1443 if (!super.onOptionsItemSelected(item)) {
1444 return false;
1445 }
1446 // Otherwise fall through.
1447 }
1448 mCanChord = false;
1449 return true;
1450 }
1451
1452 public void closeFind() {
1453 mMenuState = R.id.MAIN_MENU;
1454 }
1455
Grace Kloba22ac16e2009-10-07 18:00:23 -07001456 @Override
1457 public boolean onPrepareOptionsMenu(Menu menu) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001458 // This happens when the user begins to hold down the menu key, so
1459 // allow them to chord to get a shortcut.
1460 mCanChord = true;
1461 // Note: setVisible will decide whether an item is visible; while
1462 // setEnabled() will decide whether an item is enabled, which also means
1463 // whether the matching shortcut key will function.
1464 super.onPrepareOptionsMenu(menu);
1465 switch (mMenuState) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001466 case EMPTY_MENU:
1467 if (mCurrentMenuState != mMenuState) {
1468 menu.setGroupVisible(R.id.MAIN_MENU, false);
1469 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1470 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001471 }
1472 break;
1473 default:
1474 if (mCurrentMenuState != mMenuState) {
1475 menu.setGroupVisible(R.id.MAIN_MENU, true);
1476 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1477 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001478 }
1479 final WebView w = getTopWindow();
1480 boolean canGoBack = false;
1481 boolean canGoForward = false;
1482 boolean isHome = false;
1483 if (w != null) {
1484 canGoBack = w.canGoBack();
1485 canGoForward = w.canGoForward();
1486 isHome = mSettings.getHomePage().equals(w.getUrl());
1487 }
1488 final MenuItem back = menu.findItem(R.id.back_menu_id);
1489 back.setEnabled(canGoBack);
1490
1491 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1492 home.setEnabled(!isHome);
1493
1494 menu.findItem(R.id.forward_menu_id)
1495 .setEnabled(canGoForward);
1496
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001497 menu.findItem(R.id.new_tab_menu_id).setEnabled(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001498 mTabControl.canCreateNewTab());
Leon Scrogginsa81a7642009-08-31 17:05:41 -04001499
The Android Open Source Project0c908882009-03-03 19:32:16 -08001500 // decide whether to show the share link option
1501 PackageManager pm = getPackageManager();
1502 Intent send = new Intent(Intent.ACTION_SEND);
1503 send.setType("text/plain");
1504 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1505 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1506
The Android Open Source Project0c908882009-03-03 19:32:16 -08001507 boolean isNavDump = mSettings.isNavDump();
1508 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1509 nav.setVisible(isNavDump);
1510 nav.setEnabled(isNavDump);
Andrei Popescu7a8b88b2010-02-02 00:30:38 +00001511
1512 boolean showDebugSettings = mSettings.showDebugSettings();
1513 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1514 counter.setVisible(showDebugSettings);
1515 counter.setEnabled(showDebugSettings);
1516
The Android Open Source Project0c908882009-03-03 19:32:16 -08001517 break;
1518 }
1519 mCurrentMenuState = mMenuState;
1520 return true;
1521 }
1522
1523 @Override
1524 public void onCreateContextMenu(ContextMenu menu, View v,
1525 ContextMenuInfo menuInfo) {
Leon Scroggins4e9f89b2010-02-22 16:54:14 -05001526 if (v instanceof TitleBar) {
1527 return;
1528 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001529 WebView webview = (WebView) v;
1530 WebView.HitTestResult result = webview.getHitTestResult();
1531 if (result == null) {
1532 return;
1533 }
1534
1535 int type = result.getType();
1536 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1537 Log.w(LOGTAG,
1538 "We should not show context menu when nothing is touched");
1539 return;
1540 }
1541 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1542 // let TextView handles context menu
1543 return;
1544 }
1545
1546 // Note, http://b/issue?id=1106666 is requesting that
1547 // an inflated menu can be used again. This is not available
1548 // yet, so inflate each time (yuk!)
1549 MenuInflater inflater = getMenuInflater();
1550 inflater.inflate(R.menu.browsercontext, menu);
1551
1552 // Show the correct menu group
1553 String extra = result.getExtra();
1554 menu.setGroupVisible(R.id.PHONE_MENU,
1555 type == WebView.HitTestResult.PHONE_TYPE);
1556 menu.setGroupVisible(R.id.EMAIL_MENU,
1557 type == WebView.HitTestResult.EMAIL_TYPE);
1558 menu.setGroupVisible(R.id.GEO_MENU,
1559 type == WebView.HitTestResult.GEO_TYPE);
1560 menu.setGroupVisible(R.id.IMAGE_MENU,
1561 type == WebView.HitTestResult.IMAGE_TYPE
1562 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1563 menu.setGroupVisible(R.id.ANCHOR_MENU,
1564 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1565 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1566
1567 // Setup custom handling depending on the type
1568 switch (type) {
1569 case WebView.HitTestResult.PHONE_TYPE:
1570 menu.setHeaderTitle(Uri.decode(extra));
1571 menu.findItem(R.id.dial_context_menu_id).setIntent(
1572 new Intent(Intent.ACTION_VIEW, Uri
1573 .parse(WebView.SCHEME_TEL + extra)));
1574 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1575 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
Cary Clark5e335a32009-09-22 14:53:11 -04001576 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001577 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1578 addIntent);
1579 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1580 new Copy(extra));
1581 break;
1582
1583 case WebView.HitTestResult.EMAIL_TYPE:
1584 menu.setHeaderTitle(extra);
1585 menu.findItem(R.id.email_context_menu_id).setIntent(
1586 new Intent(Intent.ACTION_VIEW, Uri
1587 .parse(WebView.SCHEME_MAILTO + extra)));
1588 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1589 new Copy(extra));
1590 break;
1591
1592 case WebView.HitTestResult.GEO_TYPE:
1593 menu.setHeaderTitle(extra);
1594 menu.findItem(R.id.map_context_menu_id).setIntent(
1595 new Intent(Intent.ACTION_VIEW, Uri
1596 .parse(WebView.SCHEME_GEO
1597 + URLEncoder.encode(extra))));
1598 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1599 new Copy(extra));
1600 break;
1601
1602 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1603 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1604 TextView titleView = (TextView) LayoutInflater.from(this)
1605 .inflate(android.R.layout.browser_link_context_header,
1606 null);
1607 titleView.setText(extra);
1608 menu.setHeaderView(titleView);
1609 // decide whether to show the open link in new tab option
1610 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
Grace Kloba22ac16e2009-10-07 18:00:23 -07001611 mTabControl.canCreateNewTab());
Ben Murdochde353622009-10-12 10:29:00 +01001612 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1613 Bookmarks.urlHasAcceptableScheme(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001614 PackageManager pm = getPackageManager();
1615 Intent send = new Intent(Intent.ACTION_SEND);
1616 send.setType("text/plain");
1617 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1618 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1619 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1620 break;
1621 }
1622 // otherwise fall through to handle image part
1623 case WebView.HitTestResult.IMAGE_TYPE:
1624 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1625 menu.setHeaderTitle(extra);
1626 }
1627 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1628 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1629 menu.findItem(R.id.download_context_menu_id).
1630 setOnMenuItemClickListener(new Download(extra));
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001631 menu.findItem(R.id.set_wallpaper_context_menu_id).
1632 setOnMenuItemClickListener(new SetAsWallpaper(extra));
The Android Open Source Project0c908882009-03-03 19:32:16 -08001633 break;
1634
1635 default:
1636 Log.w(LOGTAG, "We should not get here.");
1637 break;
1638 }
Leon Scrogginsb2b19f52009-10-09 16:10:00 -04001639 hideFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001640 }
1641
The Android Open Source Project0c908882009-03-03 19:32:16 -08001642 // Attach the given tab to the content view.
Grace Klobac928c302009-09-17 11:51:21 -07001643 // this should only be called for the current tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001644 private void attachTabToContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001645 // Attach the container that contains the main WebView and any other UI
1646 // associated with the tab.
Patrick Scottd0119532009-09-17 08:00:31 -04001647 t.attachTabToContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001648
1649 if (mShouldShowErrorConsole) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001650 ErrorConsoleView errorConsole = t.getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01001651 if (errorConsole.numberOfErrors() == 0) {
1652 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1653 } else {
1654 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1655 }
1656
1657 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08001658 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01001659 ViewGroup.LayoutParams.WRAP_CONTENT));
1660 }
1661
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001662 WebView view = t.getWebView();
Leon Scroggins55a5bc22009-09-04 17:00:08 -04001663 view.setEmbeddedTitleBar(mTitleBar);
Leon Scroggins58d56c62010-01-28 15:12:40 -05001664 if (t.isInVoiceSearchMode()) {
1665 showVoiceTitleBar(t.getVoiceDisplayTitle());
1666 } else {
1667 revertVoiceTitleBar();
1668 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001669 // Request focus on the top window.
1670 t.getTopWindow().requestFocus();
1671 }
1672
1673 // Attach a sub window to the main WebView of the given tab.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001674 void attachSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001675 t.attachSubWindow(mContentView);
1676 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001677 }
1678
1679 // Remove the given tab from the content view.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001680 private void removeTabFromContentView(Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001681 // Remove the container that contains the main WebView.
Patrick Scottd0119532009-09-17 08:00:31 -04001682 t.removeTabFromContentView(mContentView);
Ben Murdochbff2d602009-07-01 20:19:05 +01001683
Grace Kloba22ac16e2009-10-07 18:00:23 -07001684 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1685 if (errorConsole != null) {
1686 mErrorConsoleContainer.removeView(errorConsole);
Ben Murdochbff2d602009-07-01 20:19:05 +01001687 }
1688
Leon Scroggins39ab28e2009-09-02 21:20:30 -04001689 WebView view = t.getWebView();
Leon Scrogginsbb85b902009-09-14 19:27:20 -04001690 if (view != null) {
1691 view.setEmbeddedTitleBar(null);
1692 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001693 }
1694
1695 // Remove the sub window if it exists. Also called by TabControl when the
1696 // user clicks the 'X' to dismiss a sub window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001697 /* package */ void dismissSubWindow(Tab t) {
Patrick Scottd0119532009-09-17 08:00:31 -04001698 t.removeSubWindow(mContentView);
Grace Kloba22ac16e2009-10-07 18:00:23 -07001699 // dismiss the subwindow. This will destroy the WebView.
1700 t.dismissSubWindow();
Patrick Scottd0119532009-09-17 08:00:31 -04001701 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001702 }
1703
Leon Scroggins1f005d32009-08-10 17:36:42 -04001704 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001705 // that accepts url as string.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001706 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001707 return openTabAndShow(new UrlData(url), closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001708 }
1709
1710 // This method does a ton of stuff. It will attempt to create a new tab
1711 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
Leon Scroggins1f005d32009-08-10 17:36:42 -04001712 // url isn't null, it will load the given url.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001713 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1714 String appId) {
1715 final Tab currentTab = mTabControl.getCurrentTab();
1716 if (mTabControl.canCreateNewTab()) {
1717 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1718 urlData.mUrl);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001719 WebView webview = tab.getWebView();
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001720 // If the last tab was removed from the active tabs page, currentTab
1721 // will be null.
1722 if (currentTab != null) {
1723 removeTabFromContentView(currentTab);
1724 }
Patrick Scott8bbd69f2009-08-14 13:35:53 -04001725 // We must set the new tab as the current tab to reflect the old
1726 // animation behavior.
1727 mTabControl.setCurrentTab(tab);
Grace Klobaeb6eef42009-09-15 17:56:32 -07001728 attachTabToContentView(tab);
Leon Scroggins160a7e72009-08-14 18:28:01 -04001729 if (!urlData.isEmpty()) {
Patrick Scott9d53da02010-02-19 10:19:01 -05001730 loadUrlDataIn(tab, urlData);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001731 }
1732 return tab;
1733 } else {
1734 // Get rid of the subwindow if it exists
1735 dismissSubWindow(currentTab);
1736 if (!urlData.isEmpty()) {
1737 // Load the given url.
Patrick Scott9d53da02010-02-19 10:19:01 -05001738 loadUrlDataIn(currentTab, urlData);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001739 }
Leon Scroggins58d56c62010-01-28 15:12:40 -05001740 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001741 }
1742 }
1743
Grace Kloba22ac16e2009-10-07 18:00:23 -07001744 private Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001745 if (mSettings.openInBackground()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001746 Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001747 if (t != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001748 WebView view = t.getWebView();
Leon Scroggins92472e82010-02-17 16:32:28 -05001749 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001750 }
Grace Klobac9181842009-04-14 08:53:22 -07001751 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001752 } else {
Leon Scroggins1f005d32009-08-10 17:36:42 -04001753 return openTabAndShow(url, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001754 }
1755 }
1756
1757 private class Copy implements OnMenuItemClickListener {
1758 private CharSequence mText;
1759
1760 public boolean onMenuItemClick(MenuItem item) {
1761 copy(mText);
1762 return true;
1763 }
1764
1765 public Copy(CharSequence toCopy) {
1766 mText = toCopy;
1767 }
1768 }
1769
1770 private class Download implements OnMenuItemClickListener {
1771 private String mText;
1772
1773 public boolean onMenuItemClick(MenuItem item) {
1774 onDownloadStartNoStream(mText, null, null, null, -1);
1775 return true;
1776 }
1777
1778 public Download(String toDownload) {
1779 mText = toDownload;
1780 }
1781 }
1782
Ben Murdoch4f75ba22009-10-27 11:48:28 +00001783 private class SetAsWallpaper extends Thread implements
1784 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1785 private URL mUrl;
1786 private ProgressDialog mWallpaperProgress;
1787 private boolean mCanceled = false;
1788
1789 public SetAsWallpaper(String url) {
1790 try {
1791 mUrl = new URL(url);
1792 } catch (MalformedURLException e) {
1793 mUrl = null;
1794 }
1795 }
1796
1797 public void onCancel(DialogInterface dialog) {
1798 mCanceled = true;
1799 }
1800
1801 public boolean onMenuItemClick(MenuItem item) {
1802 if (mUrl != null) {
1803 // The user may have tried to set a image with a large file size as their
1804 // background so it may take a few moments to perform the operation. Display
1805 // a progress spinner while it is working.
1806 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1807 mWallpaperProgress.setIndeterminate(true);
1808 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1809 mWallpaperProgress.setCancelable(true);
1810 mWallpaperProgress.setOnCancelListener(this);
1811 mWallpaperProgress.show();
1812 start();
1813 }
1814 return true;
1815 }
1816
1817 public void run() {
1818 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1819 try {
1820 // TODO: This will cause the resource to be downloaded again, when we
1821 // should in most cases be able to grab it from the cache. To fix this
1822 // we should query WebCore to see if we can access a cached version and
1823 // instead open an input stream on that. This pattern could also be used
1824 // in the download manager where the same problem exists.
1825 InputStream inputstream = mUrl.openStream();
1826 if (inputstream != null) {
1827 setWallpaper(inputstream);
1828 }
1829 } catch (IOException e) {
1830 Log.e(LOGTAG, "Unable to set new wallpaper");
1831 // Act as though the user canceled the operation so we try to
1832 // restore the old wallpaper.
1833 mCanceled = true;
1834 }
1835
1836 if (mCanceled) {
1837 // Restore the old wallpaper if the user cancelled whilst we were setting
1838 // the new wallpaper.
1839 int width = oldWallpaper.getIntrinsicWidth();
1840 int height = oldWallpaper.getIntrinsicHeight();
1841 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1842 Canvas canvas = new Canvas(bm);
1843 oldWallpaper.setBounds(0, 0, width, height);
1844 oldWallpaper.draw(canvas);
1845 try {
1846 setWallpaper(bm);
1847 } catch (IOException e) {
1848 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1849 }
1850 mCanceled = false;
1851 }
1852
1853 if (mWallpaperProgress.isShowing()) {
1854 mWallpaperProgress.dismiss();
1855 }
1856 }
1857 }
1858
The Android Open Source Project0c908882009-03-03 19:32:16 -08001859 private void copy(CharSequence text) {
1860 try {
1861 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1862 if (clip != null) {
1863 clip.setClipboardText(text);
1864 }
1865 } catch (android.os.RemoteException e) {
1866 Log.e(LOGTAG, "Copy failed", e);
1867 }
1868 }
1869
1870 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001871 * Resets the browser title-view to whatever it must be
1872 * (for example, if we had a loading error)
1873 * When we have a new page, we call resetTitle, when we
1874 * have to reset the titlebar to whatever it used to be
1875 * (for example, if the user chose to stop loading), we
1876 * call resetTitleAndRevertLockIcon.
1877 */
1878 /* package */ void resetTitleAndRevertLockIcon() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001879 mTabControl.getCurrentTab().revertLockIcon();
1880 updateLockIconToLatest();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001881 resetTitleIconAndProgress();
1882 }
1883
1884 /**
1885 * Reset the title, favicon, and progress.
1886 */
1887 private void resetTitleIconAndProgress() {
1888 WebView current = mTabControl.getCurrentWebView();
1889 if (current == null) {
1890 return;
1891 }
1892 resetTitleAndIcon(current);
1893 int progress = current.getProgress();
Grace Kloba22ac16e2009-10-07 18:00:23 -07001894 current.getWebChromeClient().onProgressChanged(current, progress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001895 }
1896
1897 // Reset the title and the icon based on the given item.
1898 private void resetTitleAndIcon(WebView view) {
1899 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1900 if (item != null) {
Leon Scroggins68579392009-09-15 15:31:54 -04001901 setUrlTitle(item.getUrl(), item.getTitle());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001902 setFavicon(item.getFavicon());
1903 } else {
Leon Scroggins68579392009-09-15 15:31:54 -04001904 setUrlTitle(null, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001905 setFavicon(null);
1906 }
1907 }
1908
1909 /**
1910 * Sets a title composed of the URL and the title string.
1911 * @param url The URL of the site being loaded.
1912 * @param title The title of the site being loaded.
1913 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001914 void setUrlTitle(String url, String title) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001915 mUrl = url;
1916 mTitle = title;
1917
Leon Scroggins58d56c62010-01-28 15:12:40 -05001918 // If we are in voice search mode, the title has already been set.
1919 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1920 mTitleBar.setDisplayTitle(url);
1921 mFakeTitleBar.setDisplayTitle(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001922 }
1923
1924 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08001925 * @param url The URL to build a title version of the URL from.
1926 * @return The title version of the URL or null if fails.
1927 * The title version of the URL can be either the URL hostname,
1928 * or the hostname with an "https://" prefix (for secure URLs),
1929 * or an empty string if, for example, the URL in question is a
1930 * file:// URL with no hostname.
1931 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04001932 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001933 String titleUrl = null;
1934
1935 if (url != null) {
1936 try {
1937 // parse the url string
1938 URL urlObj = new URL(url);
1939 if (urlObj != null) {
1940 titleUrl = "";
1941
1942 String protocol = urlObj.getProtocol();
1943 String host = urlObj.getHost();
1944
1945 if (host != null && 0 < host.length()) {
1946 titleUrl = host;
1947 if (protocol != null) {
1948 // if a secure site, add an "https://" prefix!
1949 if (protocol.equalsIgnoreCase("https")) {
1950 titleUrl = protocol + "://" + host;
1951 }
1952 }
1953 }
1954 }
1955 } catch (MalformedURLException e) {}
1956 }
1957
1958 return titleUrl;
1959 }
1960
1961 // Set the favicon in the title bar.
Grace Kloba22ac16e2009-10-07 18:00:23 -07001962 void setFavicon(Bitmap icon) {
Leon Scroggins68579392009-09-15 15:31:54 -04001963 mTitleBar.setFavicon(icon);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04001964 mFakeTitleBar.setFavicon(icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001965 }
1966
1967 /**
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001968 * Close the tab, remove its associated title bar, and adjust mTabControl's
1969 * current tab to a valid value.
Leon Scroggins1f005d32009-08-10 17:36:42 -04001970 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07001971 /* package */ void closeTab(Tab t) {
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001972 int currentIndex = mTabControl.getCurrentIndex();
1973 int removeIndex = mTabControl.getTabIndex(t);
Leon Scroggins1f005d32009-08-10 17:36:42 -04001974 mTabControl.removeTab(t);
Leon Scroggins0a64ba52009-09-08 15:35:33 -04001975 if (currentIndex >= removeIndex && currentIndex != 0) {
1976 currentIndex--;
1977 }
1978 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
Andrei Popescua5bf1de2009-09-23 16:39:23 +01001979 resetTitleIconAndProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001980 }
1981
Leon Scrogginsdcc5eeb2010-02-23 17:26:37 -05001982 /* package */ void goBackOnePageOrQuit() {
Grace Kloba22ac16e2009-10-07 18:00:23 -07001983 Tab current = mTabControl.getCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001984 if (current == null) {
1985 /*
1986 * Instead of finishing the activity, simply push this to the back
1987 * of the stack and let ActivityManager to choose the foreground
1988 * activity. As BrowserActivity is singleTask, it will be always the
1989 * root of the task. So we can use either true or false for
1990 * moveTaskToBack().
1991 */
1992 moveTaskToBack(true);
Grace Kloba00d85e72009-09-23 18:50:05 -07001993 return;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001994 }
1995 WebView w = current.getWebView();
1996 if (w.canGoBack()) {
1997 w.goBack();
1998 } else {
1999 // Check to see if we are closing a window that was created by
2000 // another window. If so, we switch back to that window.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002001 Tab parent = current.getParentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 if (parent != null) {
Leon Scroggins1f005d32009-08-10 17:36:42 -04002003 switchToTab(mTabControl.getTabIndex(parent));
2004 // Now we close the other tab
2005 closeTab(current);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002006 } else {
2007 if (current.closeOnExit()) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002008 // force the tab's inLoad() to be false as we are going to
2009 // either finish the activity or remove the tab. This will
2010 // ensure pauseWebViewTimers() taking action.
2011 mTabControl.getCurrentTab().clearInLoad();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002012 if (mTabControl.getTabCount() == 1) {
2013 finish();
2014 return;
2015 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002016 // call pauseWebViewTimers() now, we won't be able to call
2017 // it in onPause() as the WebView won't be valid.
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002018 // Temporarily change mActivityInPause to be true as
2019 // pauseWebViewTimers() will do nothing if mActivityInPause
2020 // is false.
Grace Kloba918e1d72009-08-13 14:55:06 -07002021 boolean savedState = mActivityInPause;
2022 if (savedState) {
Grace Klobaec1b5ad2009-08-18 08:42:32 -07002023 Log.e(LOGTAG, "BrowserActivity is already paused "
2024 + "while handing goBackOnePageOrQuit.");
Grace Kloba918e1d72009-08-13 14:55:06 -07002025 }
2026 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002027 pauseWebViewTimers();
Grace Kloba918e1d72009-08-13 14:55:06 -07002028 mActivityInPause = savedState;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 removeTabFromContentView(current);
2030 mTabControl.removeTab(current);
2031 }
2032 /*
2033 * Instead of finishing the activity, simply push this to the back
2034 * of the stack and let ActivityManager to choose the foreground
2035 * activity. As BrowserActivity is singleTask, it will be always the
2036 * root of the task. So we can use either true or false for
2037 * moveTaskToBack().
2038 */
2039 moveTaskToBack(true);
2040 }
2041 }
2042 }
2043
Grace Kloba22ac16e2009-10-07 18:00:23 -07002044 boolean isMenuDown() {
2045 return mMenuIsDown;
2046 }
2047
Grace Kloba5942df02009-09-18 11:48:29 -07002048 @Override
2049 public boolean onKeyDown(int keyCode, KeyEvent event) {
Leon Scrogginsf65b50d2009-12-08 10:44:28 -05002050 // Even if MENU is already held down, we need to call to super to open
2051 // the IME on long press.
2052 if (KeyEvent.KEYCODE_MENU == keyCode) {
2053 mMenuIsDown = true;
2054 return super.onKeyDown(keyCode, event);
2055 }
Grace Kloba5942df02009-09-18 11:48:29 -07002056 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2057 // still down, we don't want to trigger the search. Pretend to consume
2058 // the key and do nothing.
2059 if (mMenuIsDown) return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002060
Grace Kloba5942df02009-09-18 11:48:29 -07002061 switch(keyCode) {
Grace Kloba5942df02009-09-18 11:48:29 -07002062 case KeyEvent.KEYCODE_SPACE:
Grace Klobada0fe552009-09-22 18:17:24 -07002063 // WebView/WebTextView handle the keys in the KeyDown. As
2064 // the Activity's shortcut keys are only handled when WebView
2065 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2066 if (event.isShiftPressed()) {
2067 getTopWindow().pageUp(false);
2068 } else {
2069 getTopWindow().pageDown(false);
2070 }
Grace Kloba5942df02009-09-18 11:48:29 -07002071 return true;
2072 case KeyEvent.KEYCODE_BACK:
2073 if (event.getRepeatCount() == 0) {
2074 event.startTracking();
2075 return true;
2076 } else if (mCustomView == null && mActiveTabsPage == null
2077 && event.isLongPress()) {
2078 bookmarksOrHistoryPicker(true);
2079 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002080 }
Grace Kloba5942df02009-09-18 11:48:29 -07002081 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082 }
Grace Kloba5942df02009-09-18 11:48:29 -07002083 return super.onKeyDown(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002084 }
2085
Grace Kloba5942df02009-09-18 11:48:29 -07002086 @Override
2087 public boolean onKeyUp(int keyCode, KeyEvent event) {
2088 switch(keyCode) {
2089 case KeyEvent.KEYCODE_MENU:
2090 mMenuIsDown = false;
2091 break;
Grace Kloba5942df02009-09-18 11:48:29 -07002092 case KeyEvent.KEYCODE_BACK:
2093 if (event.isTracking() && !event.isCanceled()) {
2094 if (mCustomView != null) {
2095 // if a custom view is showing, hide it
Grace Kloba22ac16e2009-10-07 18:00:23 -07002096 mTabControl.getCurrentWebView().getWebChromeClient()
2097 .onHideCustomView();
Grace Kloba5942df02009-09-18 11:48:29 -07002098 } else if (mActiveTabsPage != null) {
2099 // if tab page is showing, hide it
2100 removeActiveTabPage(true);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002101 } else {
Grace Kloba5942df02009-09-18 11:48:29 -07002102 WebView subwindow = mTabControl.getCurrentSubWindow();
2103 if (subwindow != null) {
2104 if (subwindow.canGoBack()) {
2105 subwindow.goBack();
2106 } else {
2107 dismissSubWindow(mTabControl.getCurrentTab());
2108 }
2109 } else {
2110 goBackOnePageOrQuit();
2111 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002112 }
Grace Kloba5942df02009-09-18 11:48:29 -07002113 return true;
2114 }
2115 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002116 }
Grace Kloba5942df02009-09-18 11:48:29 -07002117 return super.onKeyUp(keyCode, event);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002118 }
2119
Leon Scroggins68579392009-09-15 15:31:54 -04002120 /* package */ void stopLoading() {
Ben Murdochb7cc8b42009-09-28 10:59:09 +01002121 mDidStopLoad = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 resetTitleAndRevertLockIcon();
2123 WebView w = getTopWindow();
2124 w.stopLoading();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002125 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2126 // same logic here. But for subwindow case, should we call into the main
2127 // WebView's onPageFinished as we never call its onPageStarted and if
2128 // the page finishes itself, we don't call onPageFinished.
2129 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2130 w.getUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131
2132 cancelStopToast();
2133 mStopToast = Toast
2134 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2135 mStopToast.show();
2136 }
2137
Grace Kloba22ac16e2009-10-07 18:00:23 -07002138 boolean didUserStopLoading() {
2139 return mDidStopLoad;
2140 }
2141
The Android Open Source Project0c908882009-03-03 19:32:16 -08002142 private void cancelStopToast() {
2143 if (mStopToast != null) {
2144 mStopToast.cancel();
2145 mStopToast = null;
2146 }
2147 }
2148
Grace Kloba22ac16e2009-10-07 18:00:23 -07002149 // called by a UI or non-UI thread to post the message
2150 public void postMessage(int what, int arg1, int arg2, Object obj,
2151 long delayMillis) {
2152 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2153 obj), delayMillis);
2154 }
2155
2156 // called by a UI or non-UI thread to remove the message
2157 void removeMessages(int what, Object object) {
2158 mHandler.removeMessages(what, object);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002159 }
2160
2161 // public message ids
2162 public final static int LOAD_URL = 1001;
2163 public final static int STOP_LOAD = 1002;
2164
2165 // Message Ids
2166 private static final int FOCUS_NODE_HREF = 102;
Grace Kloba92c18a52009-07-31 23:48:32 -07002167 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002168
Grace Kloba22ac16e2009-10-07 18:00:23 -07002169 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
Ben Murdoch2694e232009-09-29 09:41:11 +01002170
The Android Open Source Project0c908882009-03-03 19:32:16 -08002171 // Private handler for handling javascript and saving passwords
2172 private Handler mHandler = new Handler() {
2173
2174 public void handleMessage(Message msg) {
2175 switch (msg.what) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002176 case FOCUS_NODE_HREF:
Ben Murdoch2694e232009-09-29 09:41:11 +01002177 {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002178 String url = (String) msg.getData().get("url");
Ben Murdoch90d088c2009-11-17 18:14:04 +00002179 String title = (String) msg.getData().get("title");
The Android Open Source Project0c908882009-03-03 19:32:16 -08002180 if (url == null || url.length() == 0) {
2181 break;
2182 }
2183 HashMap focusNodeMap = (HashMap) msg.obj;
2184 WebView view = (WebView) focusNodeMap.get("webview");
2185 // Only apply the action if the top window did not change.
2186 if (getTopWindow() != view) {
2187 break;
2188 }
2189 switch (msg.arg1) {
2190 case R.id.open_context_menu_id:
2191 case R.id.view_image_context_menu_id:
Leon Scroggins92472e82010-02-17 16:32:28 -05002192 loadUrlFromContext(getTopWindow(), url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002193 break;
2194 case R.id.open_newtab_context_menu_id:
Grace Kloba22ac16e2009-10-07 18:00:23 -07002195 final Tab parent = mTabControl.getCurrentTab();
2196 final Tab newTab = openTab(url);
Grace Klobac9181842009-04-14 08:53:22 -07002197 if (newTab != parent) {
2198 parent.addChildTab(newTab);
2199 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002200 break;
2201 case R.id.bookmark_context_menu_id:
2202 Intent intent = new Intent(BrowserActivity.this,
2203 AddBookmarkPage.class);
2204 intent.putExtra("url", url);
Ben Murdoch90d088c2009-11-17 18:14:04 +00002205 intent.putExtra("title", title);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002206 startActivity(intent);
2207 break;
2208 case R.id.share_link_context_menu_id:
Leon Scroggins96afcb12009-12-10 12:35:56 -05002209 // See if this site has been visited before
2210 StringBuilder sb = new StringBuilder(
2211 Browser.BookmarkColumns.URL + " = ");
2212 DatabaseUtils.appendEscapedSQLString(sb, url);
2213 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2214 Browser.HISTORY_PROJECTION,
2215 sb.toString(),
2216 null,
2217 null);
2218 if (c.moveToFirst()) {
2219 // The site has been visited before, so grab the
2220 // info from the database.
2221 Bitmap favicon = null;
2222 Bitmap thumbnail = null;
2223 String linkTitle = c.getString(Browser.
2224 HISTORY_PROJECTION_TITLE_INDEX);
2225 byte[] data = c.getBlob(Browser.
2226 HISTORY_PROJECTION_FAVICON_INDEX);
2227 if (data != null) {
2228 favicon = BitmapFactory.decodeByteArray(
2229 data, 0, data.length);
2230 }
2231 data = c.getBlob(Browser.
2232 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2233 if (data != null) {
2234 thumbnail = BitmapFactory.decodeByteArray(
2235 data, 0, data.length);
2236 }
2237 sharePage(BrowserActivity.this,
2238 linkTitle, url, favicon, thumbnail);
2239 } else {
2240 Browser.sendString(BrowserActivity.this, url,
2241 getString(
2242 R.string.choosertitle_sharevia));
2243 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002244 break;
2245 case R.id.copy_link_context_menu_id:
2246 copy(url);
2247 break;
2248 case R.id.save_link_context_menu_id:
2249 case R.id.download_context_menu_id:
2250 onDownloadStartNoStream(url, null, null, null, -1);
2251 break;
2252 }
2253 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002254 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002255
2256 case LOAD_URL:
Leon Scroggins92472e82010-02-17 16:32:28 -05002257 loadUrlFromContext(getTopWindow(), (String) msg.obj);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002258 break;
2259
2260 case STOP_LOAD:
2261 stopLoading();
2262 break;
2263
The Android Open Source Project0c908882009-03-03 19:32:16 -08002264 case RELEASE_WAKELOCK:
2265 if (mWakeLock.isHeld()) {
2266 mWakeLock.release();
Grace Kloba5d0e02e2009-10-05 15:15:36 -07002267 // if we reach here, Browser should be still in the
2268 // background loading after WAKELOCK_TIMEOUT (5-min).
2269 // To avoid burning the battery, stop loading.
2270 mTabControl.stopAllLoading();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 }
2272 break;
Ben Murdoch2694e232009-09-29 09:41:11 +01002273
2274 case UPDATE_BOOKMARK_THUMBNAIL:
2275 WebView view = (WebView) msg.obj;
2276 if (view != null) {
2277 updateScreenshot(view);
2278 }
2279 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002280 }
2281 }
2282 };
2283
Leon Scroggins96afcb12009-12-10 12:35:56 -05002284 /**
2285 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2286 * an {@link Intent} to launch the Activity chooser.
2287 * @param c Context used to launch a new Activity.
2288 * @param title Title of the page. Stored in the Intent with
Paul Westbrook03e6d392010-02-12 10:33:29 -08002289 * {@link Intent#EXTRA_SUBJECT}
Leon Scroggins96afcb12009-12-10 12:35:56 -05002290 * @param url URL of the page. Stored in the Intent with
2291 * {@link Intent#EXTRA_TEXT}
2292 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2293 * with {@link Browser#EXTRA_SHARE_FAVICON}
2294 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2295 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2296 */
2297 public static final void sharePage(Context c, String title, String url,
2298 Bitmap favicon, Bitmap screenshot) {
2299 Intent send = new Intent(Intent.ACTION_SEND);
2300 send.setType("text/plain");
2301 send.putExtra(Intent.EXTRA_TEXT, url);
Paul Westbrook03e6d392010-02-12 10:33:29 -08002302 send.putExtra(Intent.EXTRA_SUBJECT, title);
Leon Scroggins96afcb12009-12-10 12:35:56 -05002303 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2304 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2305 try {
2306 c.startActivity(Intent.createChooser(send, c.getString(
2307 R.string.choosertitle_sharevia)));
2308 } catch(android.content.ActivityNotFoundException ex) {
2309 // if no app handles it, do nothing
2310 }
2311 }
2312
Leon Scroggins89c6d362009-07-15 16:54:37 -04002313 private void updateScreenshot(WebView view) {
2314 // If this is a bookmarked site, add a screenshot to the database.
2315 // FIXME: When should we update? Every time?
2316 // FIXME: Would like to make sure there is actually something to
2317 // draw, but the API for that (WebViewCore.pictureReady()) is not
2318 // currently accessible here.
Ben Murdochaac7aa62009-09-17 16:57:40 +01002319
Patrick Scottcb192b52010-04-14 14:38:55 -04002320 final Bitmap bm = createScreenshot(view);
2321 if (bm == null) {
2322 return;
Leon Scroggins89c6d362009-07-15 16:54:37 -04002323 }
Patrick Scottcb192b52010-04-14 14:38:55 -04002324
2325 final ContentResolver cr = getContentResolver();
2326 final String url = view.getUrl();
2327 final String originalUrl = view.getOriginalUrl();
2328
2329 new AsyncTask<Void, Void, Void>() {
2330 @Override
2331 protected Void doInBackground(Void... unused) {
2332 Cursor c = null;
2333 try {
2334 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2335 cr, originalUrl, url, true);
2336 if (c != null) {
2337 if (c.moveToFirst()) {
2338 ContentValues values = new ContentValues();
2339 final ByteArrayOutputStream os
2340 = new ByteArrayOutputStream();
2341 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2342 values.put(Browser.BookmarkColumns.THUMBNAIL,
2343 os.toByteArray());
2344 do {
2345 cr.update(ContentUris.withAppendedId(
2346 Browser.BOOKMARKS_URI, c.getInt(0)),
2347 values, null, null);
2348 } while (c.moveToNext());
2349 }
2350 }
2351 } catch (IllegalStateException e) {
2352 // Ignore
2353 } finally {
2354 if (c != null) c.close();
2355 }
2356 return null;
2357 }
2358 }.execute();
Leon Scroggins89c6d362009-07-15 16:54:37 -04002359 }
2360
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002361 /**
Leon Scrogginsf8551612009-09-24 16:06:02 -04002362 * Values for the size of the thumbnail created when taking a screenshot.
2363 * Lazily initialized. Instead of using these directly, use
2364 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002365 */
Leon Scrogginsf8551612009-09-24 16:06:02 -04002366 private static int THUMBNAIL_WIDTH = 0;
2367 private static int THUMBNAIL_HEIGHT = 0;
2368
2369 /**
2370 * Return the desired width for thumbnail screenshots, which are stored in
2371 * the database, and used on the bookmarks screen.
2372 * @param context Context for finding out the density of the screen.
2373 * @return int desired width for thumbnail screenshot.
2374 */
2375 /* package */ static int getDesiredThumbnailWidth(Context context) {
2376 if (THUMBNAIL_WIDTH == 0) {
2377 float density = context.getResources().getDisplayMetrics().density;
2378 THUMBNAIL_WIDTH = (int) (90 * density);
2379 THUMBNAIL_HEIGHT = (int) (80 * density);
2380 }
2381 return THUMBNAIL_WIDTH;
2382 }
2383
2384 /**
2385 * Return the desired height for thumbnail screenshots, which are stored in
2386 * the database, and used on the bookmarks screen.
2387 * @param context Context for finding out the density of the screen.
2388 * @return int desired height for thumbnail screenshot.
2389 */
2390 /* package */ static int getDesiredThumbnailHeight(Context context) {
2391 // To ensure that they are both initialized.
2392 getDesiredThumbnailWidth(context);
2393 return THUMBNAIL_HEIGHT;
2394 }
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002395
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002396 private Bitmap createScreenshot(WebView view) {
2397 Picture thumbnail = view.capturePicture();
Leon Scroggins45800572009-09-29 16:38:47 -04002398 if (thumbnail == null) {
2399 return null;
2400 }
Leon Scrogginsf8551612009-09-24 16:06:02 -04002401 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
Cary Clarkab168ba2010-04-08 09:11:28 -04002402 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002403 Canvas canvas = new Canvas(bm);
2404 // May need to tweak these values to determine what is the
2405 // best scale factor
Ben Murdoch2694e232009-09-29 09:41:11 +01002406 int thumbnailWidth = thumbnail.getWidth();
Ben Murdochae59c3f2009-10-20 18:30:28 +01002407 int thumbnailHeight = thumbnail.getHeight();
2408 float scaleFactorX = 1.0f;
2409 float scaleFactorY = 1.0f;
Ben Murdoch2694e232009-09-29 09:41:11 +01002410 if (thumbnailWidth > 0) {
Ben Murdochae59c3f2009-10-20 18:30:28 +01002411 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
Ben Murdoch2694e232009-09-29 09:41:11 +01002412 (float)thumbnailWidth;
Ben Murdochae59c3f2009-10-20 18:30:28 +01002413 } else {
2414 return null;
Leon Scroggins06ec5f22009-09-17 12:46:04 -04002415 }
Ben Murdochae59c3f2009-10-20 18:30:28 +01002416
2417 if (view.getWidth() > view.getHeight() &&
2418 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2419 // If the device is in landscape and the page is shorter
2420 // than the height of the view, stretch the thumbnail to fill the
2421 // space.
2422 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2423 (float)thumbnailHeight;
2424 } else {
2425 // In the portrait case, this looks nice.
2426 scaleFactorY = scaleFactorX;
2427 }
2428
2429 canvas.scale(scaleFactorX, scaleFactorY);
2430
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01002431 thumbnail.draw(canvas);
2432 return bm;
2433 }
2434
The Android Open Source Project0c908882009-03-03 19:32:16 -08002435 // -------------------------------------------------------------------------
Grace Kloba22ac16e2009-10-07 18:00:23 -07002436 // Helper function for WebViewClient.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002437 //-------------------------------------------------------------------------
2438
2439 // Use in overrideUrlLoading
2440 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2441 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2442 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2443 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2444
Leon Scroggins92472e82010-02-17 16:32:28 -05002445 // Keep this initial progress in sync with initialProgressValue (* 100)
2446 // in ProgressTracker.cpp
2447 private final static int INITIAL_PROGRESS = 10;
2448
Grace Kloba22ac16e2009-10-07 18:00:23 -07002449 void onPageStarted(WebView view, String url, Bitmap favicon) {
2450 // when BrowserActivity just starts, onPageStarted may be called before
2451 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2452 // to start the timer. As we won't switch tabs while an activity is in
2453 // pause state, we can ensure calling resume and pause in pair.
2454 if (mActivityInPause) resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002455
Grace Kloba22ac16e2009-10-07 18:00:23 -07002456 resetLockIcon(url);
2457 setUrlTitle(url, null);
2458 setFavicon(favicon);
Leon Scroggins8cf8f682009-11-04 11:13:50 -08002459 // Show some progress so that the user knows the page is beginning to
2460 // load
Leon Scroggins92472e82010-02-17 16:32:28 -05002461 onProgressChanged(view, INITIAL_PROGRESS);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002462 mDidStopLoad = false;
Grace Kloba22ac16e2009-10-07 18:00:23 -07002463 if (!mIsNetworkUp) createAndShowNetworkDialog();
Patrick Scott15525d42009-09-21 13:39:37 -04002464
Grace Kloba22ac16e2009-10-07 18:00:23 -07002465 if (mSettings.isTracing()) {
2466 String host;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002467 try {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002468 WebAddress uri = new WebAddress(url);
2469 host = uri.mHost;
2470 } catch (android.net.ParseException ex) {
2471 host = "browser";
The Android Open Source Project0c908882009-03-03 19:32:16 -08002472 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002473 host = host.replace('.', '_');
2474 host += ".trace";
2475 mInTrace = true;
2476 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2477 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478
Grace Kloba22ac16e2009-10-07 18:00:23 -07002479 // Performance probe
2480 if (false) {
2481 mStart = SystemClock.uptimeMillis();
2482 mProcessStart = Process.getElapsedCpuTime();
2483 long[] sysCpu = new long[7];
2484 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2485 sysCpu, null)) {
2486 mUserStart = sysCpu[0] + sysCpu[1];
2487 mSystemStart = sysCpu[2];
2488 mIdleStart = sysCpu[3];
2489 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2490 }
2491 mUiStart = SystemClock.currentThreadTimeMillis();
2492 }
2493 }
2494
2495 void onPageFinished(WebView view, String url) {
2496 // Reset the title and icon in case we stopped a provisional load.
2497 resetTitleAndIcon(view);
2498 // Update the lock icon image only once we are done loading
2499 updateLockIconToLatest();
2500 // pause the WebView timer and release the wake lock if it is finished
2501 // while BrowserActivity is in pause state.
2502 if (mActivityInPause && pauseWebViewTimers()) {
2503 if (mWakeLock.isHeld()) {
2504 mHandler.removeMessages(RELEASE_WAKELOCK);
2505 mWakeLock.release();
2506 }
2507 }
2508
2509 // Performance probe
2510 if (false) {
2511 long[] sysCpu = new long[7];
2512 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2513 sysCpu, null)) {
2514 String uiInfo = "UI thread used "
2515 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2516 + " ms";
2517 if (LOGD_ENABLED) {
2518 Log.d(LOGTAG, uiInfo);
2519 }
2520 //The string that gets written to the log
2521 String performanceString = "It took total "
2522 + (SystemClock.uptimeMillis() - mStart)
2523 + " ms clock time to load the page."
2524 + "\nbrowser process used "
2525 + (Process.getElapsedCpuTime() - mProcessStart)
2526 + " ms, user processes used "
2527 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2528 + " ms, kernel used "
2529 + (sysCpu[2] - mSystemStart) * 10
2530 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2531 + " ms and irq took "
2532 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2533 * 10 + " ms, " + uiInfo;
2534 if (LOGD_ENABLED) {
2535 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2536 }
2537 if (url != null) {
2538 // strip the url to maintain consistency
2539 String newUrl = new String(url);
2540 if (newUrl.startsWith("http://www.")) {
2541 newUrl = newUrl.substring(11);
2542 } else if (newUrl.startsWith("http://")) {
2543 newUrl = newUrl.substring(7);
2544 } else if (newUrl.startsWith("https://www.")) {
2545 newUrl = newUrl.substring(12);
2546 } else if (newUrl.startsWith("https://")) {
2547 newUrl = newUrl.substring(8);
2548 }
2549 if (LOGD_ENABLED) {
2550 Log.d(LOGTAG, newUrl + " loaded");
2551 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002552 }
2553 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002554 }
Grace Kloba5b078b52009-06-24 20:23:41 -07002555
Grace Kloba22ac16e2009-10-07 18:00:23 -07002556 if (mInTrace) {
2557 mInTrace = false;
2558 Debug.stopMethodTracing();
2559 }
2560 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561
Grace Kloba22ac16e2009-10-07 18:00:23 -07002562 boolean shouldOverrideUrlLoading(WebView view, String url) {
2563 if (url.startsWith(SCHEME_WTAI)) {
2564 // wtai://wp/mc;number
2565 // number=string(phone-number)
2566 if (url.startsWith(SCHEME_WTAI_MC)) {
2567 Intent intent = new Intent(Intent.ACTION_VIEW,
2568 Uri.parse(WebView.SCHEME_TEL +
2569 url.substring(SCHEME_WTAI_MC.length())));
2570 startActivity(intent);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002571 return true;
2572 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002573 // wtai://wp/sd;dtmf
2574 // dtmf=string(dialstring)
2575 if (url.startsWith(SCHEME_WTAI_SD)) {
2576 // TODO: only send when there is active voice connection
2577 return false;
2578 }
2579 // wtai://wp/ap;number;name
2580 // number=string(phone-number)
2581 // name=string
2582 if (url.startsWith(SCHEME_WTAI_AP)) {
2583 // TODO
2584 return false;
2585 }
2586 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002587
Grace Kloba22ac16e2009-10-07 18:00:23 -07002588 // The "about:" schemes are internal to the browser; don't want these to
2589 // be dispatched to other apps.
2590 if (url.startsWith("about:")) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002591 return false;
2592 }
2593
Grace Kloba22ac16e2009-10-07 18:00:23 -07002594 Intent intent;
2595 // perform generic parsing of the URI to turn it into an Intent.
2596 try {
2597 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2598 } catch (URISyntaxException ex) {
2599 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2600 return false;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002601 }
2602
Grace Kloba22ac16e2009-10-07 18:00:23 -07002603 // check whether the intent can be resolved. If not, we will see
2604 // whether we can download it from the Market.
2605 if (getPackageManager().resolveActivity(intent, 0) == null) {
2606 String packagename = intent.getPackage();
2607 if (packagename != null) {
2608 intent = new Intent(Intent.ACTION_VIEW, Uri
2609 .parse("market://search?q=pname:" + packagename));
2610 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2611 startActivity(intent);
2612 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002613 } else {
2614 return false;
2615 }
2616 }
2617
Grace Kloba22ac16e2009-10-07 18:00:23 -07002618 // sanitize the Intent, ensuring web pages can not bypass browser
2619 // security (only access to BROWSABLE activities).
2620 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2621 intent.setComponent(null);
2622 try {
2623 if (startActivityIfNeeded(intent, -1)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624 return true;
2625 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002626 } catch (ActivityNotFoundException ex) {
2627 // ignore the error. If no application can handle the URL,
2628 // eg about:blank, assume the browser can handle it.
2629 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002630
Grace Kloba22ac16e2009-10-07 18:00:23 -07002631 if (mMenuIsDown) {
2632 openTab(url);
2633 closeOptionsMenu();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002634 return true;
2635 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002636 return false;
2637 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002638
Grace Kloba22ac16e2009-10-07 18:00:23 -07002639 // -------------------------------------------------------------------------
2640 // Helper function for WebChromeClient
2641 // -------------------------------------------------------------------------
The Android Open Source Project0c908882009-03-03 19:32:16 -08002642
Grace Kloba22ac16e2009-10-07 18:00:23 -07002643 void onProgressChanged(WebView view, int newProgress) {
Grace Kloba22ac16e2009-10-07 18:00:23 -07002644 mFakeTitleBar.setProgress(newProgress);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002645
Grace Kloba22ac16e2009-10-07 18:00:23 -07002646 if (newProgress == 100) {
2647 // onProgressChanged() may continue to be called after the main
2648 // frame has finished loading, as any remaining sub frames continue
2649 // to load. We'll only get called once though with newProgress as
2650 // 100 when everything is loaded. (onPageFinished is called once
2651 // when the main frame completes loading regardless of the state of
2652 // any sub frames so calls to onProgressChanges may continue after
2653 // onPageFinished has executed)
2654 if (mInLoad) {
2655 mInLoad = false;
Leon Scrogginsa27ff192009-09-14 12:58:04 -04002656 updateInLoadMenuItems();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002657 // If the options menu is open, leave the title bar
2658 if (!mOptionsMenuOpen || !mIconView) {
2659 hideFakeTitleBar();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002660 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002661 }
Leon Scrogginsaa37e7f2010-03-05 11:51:20 -05002662 } else {
2663 if (!mInLoad) {
2664 // onPageFinished may have already been called but a subframe is
2665 // still loading and updating the progress. Reset mInLoad and
2666 // update the menu items.
2667 mInLoad = true;
2668 updateInLoadMenuItems();
2669 }
2670 // When the page first begins to load, the Activity may still be
2671 // paused, in which case showFakeTitleBar will do nothing. Call
2672 // again as the page continues to load so that it will be shown.
2673 // (Calling it will the fake title bar is already showing will also
2674 // do nothing.
Grace Kloba22ac16e2009-10-07 18:00:23 -07002675 if (!mOptionsMenuOpen || mIconView) {
2676 // This page has begun to load, so show the title bar
2677 showFakeTitleBar();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002678 }
2679 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002680 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002681
Grace Kloba22ac16e2009-10-07 18:00:23 -07002682 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002683 // if a view already exists then immediately terminate the new one
2684 if (mCustomView != null) {
2685 callback.onCustomViewHidden();
Grace Kloba22ac16e2009-10-07 18:00:23 -07002686 return;
Derek Sollenberger8ff57db2009-12-08 15:39:55 -05002687 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002688
2689 // Add the custom view to its container.
2690 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2691 mCustomView = view;
2692 mCustomViewCallback = callback;
2693 // Save the menu state and set it to empty while the custom
2694 // view is showing.
2695 mOldMenuState = mMenuState;
2696 mMenuState = EMPTY_MENU;
2697 // Hide the content view.
2698 mContentView.setVisibility(View.GONE);
2699 // Finally show the custom view container.
Andrei Popescu163ab742009-10-20 17:58:23 +01002700 setStatusBarVisibility(false);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002701 mCustomViewContainer.setVisibility(View.VISIBLE);
2702 mCustomViewContainer.bringToFront();
2703 }
2704
2705 void onHideCustomView() {
2706 if (mCustomView == null)
2707 return;
2708
2709 // Hide the custom view.
2710 mCustomView.setVisibility(View.GONE);
2711 // Remove the custom view from its container.
2712 mCustomViewContainer.removeView(mCustomView);
2713 mCustomView = null;
2714 // Reset the old menu state.
2715 mMenuState = mOldMenuState;
2716 mOldMenuState = EMPTY_MENU;
2717 mCustomViewContainer.setVisibility(View.GONE);
2718 mCustomViewCallback.onCustomViewHidden();
2719 // Show the content view.
Andrei Popescu163ab742009-10-20 17:58:23 +01002720 setStatusBarVisibility(true);
Grace Kloba22ac16e2009-10-07 18:00:23 -07002721 mContentView.setVisibility(View.VISIBLE);
2722 }
2723
2724 Bitmap getDefaultVideoPoster() {
2725 if (mDefaultVideoPoster == null) {
2726 mDefaultVideoPoster = BitmapFactory.decodeResource(
2727 getResources(), R.drawable.default_video_poster);
Patrick Scott3918d442009-08-04 13:22:29 -04002728 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002729 return mDefaultVideoPoster;
2730 }
Patrick Scott3918d442009-08-04 13:22:29 -04002731
Grace Kloba22ac16e2009-10-07 18:00:23 -07002732 View getVideoLoadingProgressView() {
2733 if (mVideoProgressView == null) {
2734 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2735 mVideoProgressView = inflater.inflate(
2736 R.layout.video_loading_progress, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002737 }
Grace Kloba22ac16e2009-10-07 18:00:23 -07002738 return mVideoProgressView;
2739 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002740
Leon Scroggins8d5fa432009-10-02 15:55:59 -04002741 /*
2742 * The Object used to inform the WebView of the file to upload.
2743 */
2744 private ValueCallback<Uri> mUploadMessage;
2745
Grace Kloba22ac16e2009-10-07 18:00:23 -07002746 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2747 if (mUploadMessage != null) return;
2748 mUploadMessage = uploadMsg;
2749 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2750 i.addCategory(Intent.CATEGORY_OPENABLE);
2751 i.setType("*/*");
2752 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2753 getString(R.string.choose_upload)), FILE_SELECTED);
2754 }
2755
2756 // -------------------------------------------------------------------------
2757 // Implement functions for DownloadListener
2758 // -------------------------------------------------------------------------
2759
The Android Open Source Project0c908882009-03-03 19:32:16 -08002760 /**
2761 * Notify the host application a download should be done, or that
2762 * the data should be streamed if a streaming viewer is available.
2763 * @param url The full url to the content that should be downloaded
2764 * @param contentDisposition Content-disposition http header, if
2765 * present.
2766 * @param mimetype The mimetype of the content reported by the server
2767 * @param contentLength The file size reported by the server
2768 */
2769 public void onDownloadStart(String url, String userAgent,
2770 String contentDisposition, String mimetype, long contentLength) {
2771 // if we're dealing wih A/V content that's not explicitly marked
2772 // for download, check if it's streamable.
2773 if (contentDisposition == null
Patrick Scotte1fb9662009-08-31 14:31:52 -04002774 || !contentDisposition.regionMatches(
2775 true, 0, "attachment", 0, 10)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002776 // query the package manager to see if there's a registered handler
2777 // that matches.
2778 Intent intent = new Intent(Intent.ACTION_VIEW);
2779 intent.setDataAndType(Uri.parse(url), mimetype);
Patrick Scotte1fb9662009-08-31 14:31:52 -04002780 ResolveInfo info = getPackageManager().resolveActivity(intent,
2781 PackageManager.MATCH_DEFAULT_ONLY);
2782 if (info != null) {
2783 ComponentName myName = getComponentName();
2784 // If we resolved to ourselves, we don't want to attempt to
2785 // load the url only to try and download it again.
2786 if (!myName.getPackageName().equals(
2787 info.activityInfo.packageName)
2788 || !myName.getClassName().equals(
2789 info.activityInfo.name)) {
2790 // someone (other than us) knows how to handle this mime
2791 // type with this scheme, don't download.
2792 try {
2793 startActivity(intent);
2794 return;
2795 } catch (ActivityNotFoundException ex) {
2796 if (LOGD_ENABLED) {
2797 Log.d(LOGTAG, "activity not found for " + mimetype
2798 + " over " + Uri.parse(url).getScheme(),
2799 ex);
2800 }
2801 // Best behavior is to fall back to a download in this
2802 // case
The Android Open Source Project0c908882009-03-03 19:32:16 -08002803 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002804 }
2805 }
2806 }
2807 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2808 }
2809
Kristian Monsenfa52d172010-03-25 18:29:21 +00002810 // This is to work around the fact that java.net.URI throws Exceptions
2811 // instead of just encoding URL's properly
2812 // Helper method for onDownloadStartNoStream
2813 private static String encodePath(String path) {
2814 char[] chars = path.toCharArray();
2815
2816 boolean needed = false;
2817 for (char c : chars) {
2818 if (c == '[' || c == ']') {
2819 needed = true;
2820 break;
2821 }
2822 }
2823 if (needed == false) {
2824 return path;
2825 }
2826
2827 StringBuilder sb = new StringBuilder("");
2828 for (char c : chars) {
2829 if (c == '[' || c == ']') {
2830 sb.append('%');
2831 sb.append(Integer.toHexString(c));
2832 } else {
2833 sb.append(c);
2834 }
2835 }
2836
2837 return sb.toString();
2838 }
2839
The Android Open Source Project0c908882009-03-03 19:32:16 -08002840 /**
2841 * Notify the host application a download should be done, even if there
2842 * is a streaming viewer available for thise type.
2843 * @param url The full url to the content that should be downloaded
2844 * @param contentDisposition Content-disposition http header, if
2845 * present.
2846 * @param mimetype The mimetype of the content reported by the server
2847 * @param contentLength The file size reported by the server
2848 */
2849 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2850 String contentDisposition, String mimetype, long contentLength) {
2851
2852 String filename = URLUtil.guessFileName(url,
2853 contentDisposition, mimetype);
2854
2855 // Check to see if we have an SDCard
2856 String status = Environment.getExternalStorageState();
2857 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2858 int title;
2859 String msg;
2860
2861 // Check to see if the SDCard is busy, same as the music app
2862 if (status.equals(Environment.MEDIA_SHARED)) {
2863 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2864 title = R.string.download_sdcard_busy_dlg_title;
2865 } else {
2866 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2867 title = R.string.download_no_sdcard_dlg_title;
2868 }
2869
2870 new AlertDialog.Builder(this)
2871 .setTitle(title)
2872 .setIcon(android.R.drawable.ic_dialog_alert)
2873 .setMessage(msg)
2874 .setPositiveButton(R.string.ok, null)
2875 .show();
2876 return;
2877 }
2878
Kristian Monsenfa52d172010-03-25 18:29:21 +00002879 // java.net.URI is a lot stricter than KURL so we have to encode some
2880 // extra characters. Fix for b 2538060 and b 1634719
2881 WebAddress webAddress;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002882 try {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002883 webAddress = new WebAddress(url);
2884 webAddress.mPath = encodePath(webAddress.mPath);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002885 } catch (Exception e) {
Kristian Monsenfa52d172010-03-25 18:29:21 +00002886 // This only happens for very bad urls, we want to chatch the
2887 // exception here
2888 Log.e(LOGTAG, "Exception trying to parse url:" + url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002889 return;
2890 }
2891
2892 // XXX: Have to use the old url since the cookies were stored using the
2893 // old percent-encoded url.
2894 String cookies = CookieManager.getInstance().getCookie(url);
2895
2896 ContentValues values = new ContentValues();
Kristian Monsenfa52d172010-03-25 18:29:21 +00002897 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002898 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2899 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2900 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 getPackageName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002902 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Leon Scrogginsa563d092010-04-19 16:53:49 -04002903 OpenDownloadReceiver.class.getCanonicalName());
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002904 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2905 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2906 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2907 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
Kristian Monsenfa52d172010-03-25 18:29:21 +00002908 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002909 if (contentLength > 0) {
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002910 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002911 }
2912 if (mimetype == null) {
2913 // We must have long pressed on a link or image to download it. We
2914 // are not sure of the mimetype in this case, so do a head request
2915 new FetchUrlMimeType(this).execute(values);
2916 } else {
2917 final Uri contentUri =
Jean-Baptiste Queru1e5bad92010-01-14 16:09:03 -08002918 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002919 }
Leon Scroggins9191a7f2010-03-18 14:44:44 -04002920 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2921 .show();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002922 }
2923
Grace Kloba22ac16e2009-10-07 18:00:23 -07002924 // -------------------------------------------------------------------------
2925
The Android Open Source Project0c908882009-03-03 19:32:16 -08002926 /**
2927 * Resets the lock icon. This method is called when we start a new load and
2928 * know the url to be loaded.
2929 */
2930 private void resetLockIcon(String url) {
2931 // Save the lock-icon state (we revert to it if the load gets cancelled)
Grace Kloba22ac16e2009-10-07 18:00:23 -07002932 mTabControl.getCurrentTab().resetLockIcon(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 updateLockIconImage(LOCK_ICON_UNSECURE);
2934 }
2935
The Android Open Source Project0c908882009-03-03 19:32:16 -08002936 /**
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002937 * Update the lock icon to correspond to our latest state.
2938 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002939 private void updateLockIconToLatest() {
2940 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
Leon Scroggins3bbb6ca2009-09-09 12:51:10 -04002941 }
2942
2943 /**
The Android Open Source Project0c908882009-03-03 19:32:16 -08002944 * Updates the lock-icon image in the title-bar.
2945 */
2946 private void updateLockIconImage(int lockIconType) {
2947 Drawable d = null;
2948 if (lockIconType == LOCK_ICON_SECURE) {
2949 d = mSecLockIcon;
2950 } else if (lockIconType == LOCK_ICON_MIXED) {
2951 d = mMixLockIcon;
2952 }
Leon Scroggins68579392009-09-15 15:31:54 -04002953 mTitleBar.setLock(d);
Leon Scrogginsfe87bd32009-10-06 10:10:00 -04002954 mFakeTitleBar.setLock(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002955 }
2956
2957 /**
2958 * Displays a page-info dialog.
2959 * @param tab The tab to show info about
2960 * @param fromShowSSLCertificateOnError The flag that indicates whether
2961 * this dialog was opened from the SSL-certificate-on-error dialog or
2962 * not. This is important, since we need to know whether to return to
2963 * the parent dialog or simply dismiss.
2964 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07002965 private void showPageInfo(final Tab tab,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002966 final boolean fromShowSSLCertificateOnError) {
2967 final LayoutInflater factory = LayoutInflater
2968 .from(this);
2969
2970 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2971
2972 final WebView view = tab.getWebView();
2973
2974 String url = null;
2975 String title = null;
2976
2977 if (view == null) {
2978 url = tab.getUrl();
2979 title = tab.getTitle();
2980 } else if (view == mTabControl.getCurrentWebView()) {
2981 // Use the cached title and url if this is the current WebView
2982 url = mUrl;
2983 title = mTitle;
2984 } else {
2985 url = view.getUrl();
2986 title = view.getTitle();
2987 }
2988
2989 if (url == null) {
2990 url = "";
2991 }
2992 if (title == null) {
2993 title = "";
2994 }
2995
2996 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2997 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2998
2999 mPageInfoView = tab;
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003000 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003001
3002 AlertDialog.Builder alertDialogBuilder =
3003 new AlertDialog.Builder(this)
3004 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3005 .setView(pageInfoView)
3006 .setPositiveButton(
3007 R.string.ok,
3008 new DialogInterface.OnClickListener() {
3009 public void onClick(DialogInterface dialog,
3010 int whichButton) {
3011 mPageInfoDialog = null;
3012 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003013
3014 // if we came here from the SSL error dialog
3015 if (fromShowSSLCertificateOnError) {
3016 // go back to the SSL error dialog
3017 showSSLCertificateOnError(
3018 mSSLCertificateOnErrorView,
3019 mSSLCertificateOnErrorHandler,
3020 mSSLCertificateOnErrorError);
3021 }
3022 }
3023 })
3024 .setOnCancelListener(
3025 new DialogInterface.OnCancelListener() {
3026 public void onCancel(DialogInterface dialog) {
3027 mPageInfoDialog = null;
3028 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003029
3030 // if we came here from the SSL error dialog
3031 if (fromShowSSLCertificateOnError) {
3032 // go back to the SSL error dialog
3033 showSSLCertificateOnError(
3034 mSSLCertificateOnErrorView,
3035 mSSLCertificateOnErrorHandler,
3036 mSSLCertificateOnErrorError);
3037 }
3038 }
3039 });
3040
3041 // if we have a main top-level page SSL certificate set or a certificate
3042 // error
3043 if (fromShowSSLCertificateOnError ||
3044 (view != null && view.getCertificate() != null)) {
3045 // add a 'View Certificate' button
3046 alertDialogBuilder.setNeutralButton(
3047 R.string.view_certificate,
3048 new DialogInterface.OnClickListener() {
3049 public void onClick(DialogInterface dialog,
3050 int whichButton) {
3051 mPageInfoDialog = null;
3052 mPageInfoView = null;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003053
3054 // if we came here from the SSL error dialog
3055 if (fromShowSSLCertificateOnError) {
3056 // go back to the SSL error dialog
3057 showSSLCertificateOnError(
3058 mSSLCertificateOnErrorView,
3059 mSSLCertificateOnErrorHandler,
3060 mSSLCertificateOnErrorError);
3061 } else {
3062 // otherwise, display the top-most certificate from
3063 // the chain
3064 if (view.getCertificate() != null) {
3065 showSSLCertificate(tab);
3066 }
3067 }
3068 }
3069 });
3070 }
3071
3072 mPageInfoDialog = alertDialogBuilder.show();
3073 }
3074
3075 /**
3076 * Displays the main top-level page SSL certificate dialog
3077 * (accessible from the Page-Info dialog).
3078 * @param tab The tab to show certificate for.
3079 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003080 private void showSSLCertificate(final Tab tab) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003081 final View certificateView =
3082 inflateCertificateView(tab.getWebView().getCertificate());
3083 if (certificateView == null) {
3084 return;
3085 }
3086
3087 LayoutInflater factory = LayoutInflater.from(this);
3088
3089 final LinearLayout placeholder =
3090 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3091
3092 LinearLayout ll = (LinearLayout) factory.inflate(
3093 R.layout.ssl_success, placeholder);
3094 ((TextView)ll.findViewById(R.id.success))
3095 .setText(R.string.ssl_certificate_is_valid);
3096
3097 mSSLCertificateView = tab;
3098 mSSLCertificateDialog =
3099 new AlertDialog.Builder(this)
3100 .setTitle(R.string.ssl_certificate).setIcon(
3101 R.drawable.ic_dialog_browser_certificate_secure)
3102 .setView(certificateView)
3103 .setPositiveButton(R.string.ok,
3104 new DialogInterface.OnClickListener() {
3105 public void onClick(DialogInterface dialog,
3106 int whichButton) {
3107 mSSLCertificateDialog = null;
3108 mSSLCertificateView = null;
3109
3110 showPageInfo(tab, false);
3111 }
3112 })
3113 .setOnCancelListener(
3114 new DialogInterface.OnCancelListener() {
3115 public void onCancel(DialogInterface dialog) {
3116 mSSLCertificateDialog = null;
3117 mSSLCertificateView = null;
3118
3119 showPageInfo(tab, false);
3120 }
3121 })
3122 .show();
3123 }
3124
3125 /**
3126 * Displays the SSL error certificate dialog.
3127 * @param view The target web-view.
3128 * @param handler The SSL error handler responsible for cancelling the
3129 * connection that resulted in an SSL error or proceeding per user request.
3130 * @param error The SSL error object.
3131 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003132 void showSSLCertificateOnError(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003133 final WebView view, final SslErrorHandler handler, final SslError error) {
3134
3135 final View certificateView =
3136 inflateCertificateView(error.getCertificate());
3137 if (certificateView == null) {
3138 return;
3139 }
3140
3141 LayoutInflater factory = LayoutInflater.from(this);
3142
3143 final LinearLayout placeholder =
3144 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3145
3146 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3147 LinearLayout ll = (LinearLayout)factory
3148 .inflate(R.layout.ssl_warning, placeholder);
3149 ((TextView)ll.findViewById(R.id.warning))
3150 .setText(R.string.ssl_untrusted);
3151 }
3152
3153 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3154 LinearLayout ll = (LinearLayout)factory
3155 .inflate(R.layout.ssl_warning, placeholder);
3156 ((TextView)ll.findViewById(R.id.warning))
3157 .setText(R.string.ssl_mismatch);
3158 }
3159
3160 if (error.hasError(SslError.SSL_EXPIRED)) {
3161 LinearLayout ll = (LinearLayout)factory
3162 .inflate(R.layout.ssl_warning, placeholder);
3163 ((TextView)ll.findViewById(R.id.warning))
3164 .setText(R.string.ssl_expired);
3165 }
3166
3167 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3168 LinearLayout ll = (LinearLayout)factory
3169 .inflate(R.layout.ssl_warning, placeholder);
3170 ((TextView)ll.findViewById(R.id.warning))
3171 .setText(R.string.ssl_not_yet_valid);
3172 }
3173
3174 mSSLCertificateOnErrorHandler = handler;
3175 mSSLCertificateOnErrorView = view;
3176 mSSLCertificateOnErrorError = error;
3177 mSSLCertificateOnErrorDialog =
3178 new AlertDialog.Builder(this)
3179 .setTitle(R.string.ssl_certificate).setIcon(
3180 R.drawable.ic_dialog_browser_certificate_partially_secure)
3181 .setView(certificateView)
3182 .setPositiveButton(R.string.ok,
3183 new DialogInterface.OnClickListener() {
3184 public void onClick(DialogInterface dialog,
3185 int whichButton) {
3186 mSSLCertificateOnErrorDialog = null;
3187 mSSLCertificateOnErrorView = null;
3188 mSSLCertificateOnErrorHandler = null;
3189 mSSLCertificateOnErrorError = null;
3190
Grace Kloba22ac16e2009-10-07 18:00:23 -07003191 view.getWebViewClient().onReceivedSslError(
3192 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003193 }
3194 })
3195 .setNeutralButton(R.string.page_info_view,
3196 new DialogInterface.OnClickListener() {
3197 public void onClick(DialogInterface dialog,
3198 int whichButton) {
3199 mSSLCertificateOnErrorDialog = null;
3200
3201 // do not clear the dialog state: we will
3202 // need to show the dialog again once the
3203 // user is done exploring the page-info details
3204
3205 showPageInfo(mTabControl.getTabFromView(view),
3206 true);
3207 }
3208 })
3209 .setOnCancelListener(
3210 new DialogInterface.OnCancelListener() {
3211 public void onCancel(DialogInterface dialog) {
3212 mSSLCertificateOnErrorDialog = null;
3213 mSSLCertificateOnErrorView = null;
3214 mSSLCertificateOnErrorHandler = null;
3215 mSSLCertificateOnErrorError = null;
3216
Grace Kloba22ac16e2009-10-07 18:00:23 -07003217 view.getWebViewClient().onReceivedSslError(
3218 view, handler, error);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003219 }
3220 })
3221 .show();
3222 }
3223
3224 /**
3225 * Inflates the SSL certificate view (helper method).
3226 * @param certificate The SSL certificate.
3227 * @return The resultant certificate view with issued-to, issued-by,
3228 * issued-on, expires-on, and possibly other fields set.
3229 * If the input certificate is null, returns null.
3230 */
3231 private View inflateCertificateView(SslCertificate certificate) {
3232 if (certificate == null) {
3233 return null;
3234 }
3235
3236 LayoutInflater factory = LayoutInflater.from(this);
3237
3238 View certificateView = factory.inflate(
3239 R.layout.ssl_certificate, null);
3240
3241 // issued to:
3242 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3243 if (issuedTo != null) {
3244 ((TextView) certificateView.findViewById(R.id.to_common))
3245 .setText(issuedTo.getCName());
3246 ((TextView) certificateView.findViewById(R.id.to_org))
3247 .setText(issuedTo.getOName());
3248 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3249 .setText(issuedTo.getUName());
3250 }
3251
3252 // issued by:
3253 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3254 if (issuedBy != null) {
3255 ((TextView) certificateView.findViewById(R.id.by_common))
3256 .setText(issuedBy.getCName());
3257 ((TextView) certificateView.findViewById(R.id.by_org))
3258 .setText(issuedBy.getOName());
3259 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3260 .setText(issuedBy.getUName());
3261 }
3262
3263 // issued on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003264 String issuedOn = formatCertificateDate(
3265 certificate.getValidNotBeforeDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003266 ((TextView) certificateView.findViewById(R.id.issued_on))
3267 .setText(issuedOn);
3268
3269 // expires on:
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003270 String expiresOn = formatCertificateDate(
3271 certificate.getValidNotAfterDate());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003272 ((TextView) certificateView.findViewById(R.id.expires_on))
3273 .setText(expiresOn);
3274
3275 return certificateView;
3276 }
3277
3278 /**
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003279 * Formats the certificate date to a properly localized date string.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003280 * @return Properly localized version of the certificate date string and
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003281 * the "" if it fails to localize.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003282 */
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003283 private String formatCertificateDate(Date certificateDate) {
3284 if (certificateDate == null) {
3285 return "";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003286 }
Brian Carlstrom95a2e4a2010-03-02 10:02:34 -08003287 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3288 if (formattedDate == null) {
3289 return "";
3290 }
3291 return formattedDate;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003292 }
3293
3294 /**
3295 * Displays an http-authentication dialog.
3296 */
Grace Kloba22ac16e2009-10-07 18:00:23 -07003297 void showHttpAuthentication(final HttpAuthHandler handler,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003298 final String host, final String realm, final String title,
3299 final String name, final String password, int focusId) {
3300 LayoutInflater factory = LayoutInflater.from(this);
3301 final View v = factory
3302 .inflate(R.layout.http_authentication, null);
3303 if (name != null) {
3304 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3305 }
3306 if (password != null) {
3307 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3308 }
3309
3310 String titleText = title;
3311 if (titleText == null) {
3312 titleText = getText(R.string.sign_in_to).toString().replace(
3313 "%s1", host).replace("%s2", realm);
3314 }
3315
3316 mHttpAuthHandler = handler;
3317 AlertDialog dialog = new AlertDialog.Builder(this)
3318 .setTitle(titleText)
3319 .setIcon(android.R.drawable.ic_dialog_alert)
3320 .setView(v)
3321 .setPositiveButton(R.string.action,
3322 new DialogInterface.OnClickListener() {
3323 public void onClick(DialogInterface dialog,
3324 int whichButton) {
3325 String nm = ((EditText) v
3326 .findViewById(R.id.username_edit))
3327 .getText().toString();
3328 String pw = ((EditText) v
3329 .findViewById(R.id.password_edit))
3330 .getText().toString();
3331 BrowserActivity.this.setHttpAuthUsernamePassword
3332 (host, realm, nm, pw);
3333 handler.proceed(nm, pw);
3334 mHttpAuthenticationDialog = null;
3335 mHttpAuthHandler = null;
3336 }})
3337 .setNegativeButton(R.string.cancel,
3338 new DialogInterface.OnClickListener() {
3339 public void onClick(DialogInterface dialog,
3340 int whichButton) {
3341 handler.cancel();
3342 BrowserActivity.this.resetTitleAndRevertLockIcon();
3343 mHttpAuthenticationDialog = null;
3344 mHttpAuthHandler = null;
3345 }})
3346 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3347 public void onCancel(DialogInterface dialog) {
3348 handler.cancel();
3349 BrowserActivity.this.resetTitleAndRevertLockIcon();
3350 mHttpAuthenticationDialog = null;
3351 mHttpAuthHandler = null;
3352 }})
3353 .create();
3354 // Make the IME appear when the dialog is displayed if applicable.
3355 dialog.getWindow().setSoftInputMode(
3356 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3357 dialog.show();
3358 if (focusId != 0) {
3359 dialog.findViewById(focusId).requestFocus();
3360 } else {
3361 v.findViewById(R.id.username_edit).requestFocus();
3362 }
3363 mHttpAuthenticationDialog = dialog;
3364 }
3365
3366 public int getProgress() {
3367 WebView w = mTabControl.getCurrentWebView();
3368 if (w != null) {
3369 return w.getProgress();
3370 } else {
3371 return 100;
3372 }
3373 }
3374
3375 /**
3376 * Set HTTP authentication password.
3377 *
3378 * @param host The host for the password
3379 * @param realm The realm for the password
3380 * @param username The username for the password. If it is null, it means
3381 * password can't be saved.
3382 * @param password The password
3383 */
3384 public void setHttpAuthUsernamePassword(String host, String realm,
3385 String username,
3386 String password) {
Steve Block95a53b22010-03-25 17:24:58 +00003387 WebView w = getTopWindow();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003388 if (w != null) {
3389 w.setHttpAuthUsernamePassword(host, realm, username, password);
3390 }
3391 }
3392
3393 /**
3394 * connectivity manager says net has come or gone... inform the user
3395 * @param up true if net has come up, false if net has gone down
3396 */
3397 public void onNetworkToggle(boolean up) {
3398 if (up == mIsNetworkUp) {
3399 return;
3400 } else if (up) {
3401 mIsNetworkUp = true;
3402 if (mAlertDialog != null) {
3403 mAlertDialog.cancel();
3404 mAlertDialog = null;
3405 }
3406 } else {
3407 mIsNetworkUp = false;
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003408 if (mInLoad) {
3409 createAndShowNetworkDialog();
3410 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003411 }
3412 WebView w = mTabControl.getCurrentWebView();
3413 if (w != null) {
3414 w.setNetworkAvailable(up);
3415 }
3416 }
3417
Grace Kloba22ac16e2009-10-07 18:00:23 -07003418 boolean isNetworkUp() {
3419 return mIsNetworkUp;
3420 }
3421
Patrick Scotteb6ab2a2009-09-16 10:00:17 -04003422 // This method shows the network dialog alerting the user that the net is
3423 // down. It will only show the dialog if mAlertDialog is null.
3424 private void createAndShowNetworkDialog() {
3425 if (mAlertDialog == null) {
3426 mAlertDialog = new AlertDialog.Builder(this)
3427 .setTitle(R.string.loadSuspendedTitle)
3428 .setMessage(R.string.loadSuspended)
3429 .setPositiveButton(R.string.ok, null)
3430 .show();
3431 }
3432 }
3433
The Android Open Source Project0c908882009-03-03 19:32:16 -08003434 @Override
3435 protected void onActivityResult(int requestCode, int resultCode,
3436 Intent intent) {
Grace Klobabb394f32009-11-19 10:26:37 -08003437 if (getTopWindow() == null) return;
3438
The Android Open Source Project0c908882009-03-03 19:32:16 -08003439 switch (requestCode) {
3440 case COMBO_PAGE:
3441 if (resultCode == RESULT_OK && intent != null) {
3442 String data = intent.getAction();
3443 Bundle extras = intent.getExtras();
3444 if (extras != null && extras.getBoolean("new_window", false)) {
Leon Scroggins25d35472009-09-15 11:37:27 -04003445 openTab(data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003446 } else {
Grace Kloba22ac16e2009-10-07 18:00:23 -07003447 final Tab currentTab =
The Android Open Source Project0c908882009-03-03 19:32:16 -08003448 mTabControl.getCurrentTab();
Leon Scroggins1f005d32009-08-10 17:36:42 -04003449 dismissSubWindow(currentTab);
3450 if (data != null && data.length() != 0) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003451 loadUrl(getTopWindow(), data);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003452 }
3453 }
3454 }
Leon Scrogginsfde97462010-01-11 13:06:21 -05003455 // Deliberately fall through to PREFERENCES_PAGE, since the
3456 // same extra may be attached to the COMBO_PAGE
3457 case PREFERENCES_PAGE:
3458 if (resultCode == RESULT_OK && intent != null) {
3459 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3460 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3461 mTabControl.removeParentChildRelationShips();
3462 }
3463 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003464 break;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003465 // Choose a file from the file picker.
3466 case FILE_SELECTED:
3467 if (null == mUploadMessage) break;
3468 Uri result = intent == null || resultCode != RESULT_OK ? null
3469 : intent.getData();
3470 mUploadMessage.onReceiveValue(result);
3471 mUploadMessage = null;
3472 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003473 default:
3474 break;
3475 }
Leon Scroggins30444232009-09-04 18:36:20 -04003476 getTopWindow().requestFocus();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003477 }
3478
3479 /*
3480 * This method is called as a result of the user selecting the options
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003481 * menu to see the download window. It shows the download window on top of
3482 * the current window.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003483 */
Leon Scrogginsf08809b2010-01-21 09:27:46 -05003484 private void viewDownloads(Uri downloadRecord) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003485 Intent intent = new Intent(this,
3486 BrowserDownloadPage.class);
3487 intent.setData(downloadRecord);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003488 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003489
3490 }
3491
Leon Scroggins160a7e72009-08-14 18:28:01 -04003492 /**
3493 * Open the Go page.
3494 * @param startWithHistory If true, open starting on the history tab.
3495 * Otherwise, start with the bookmarks tab.
Leon Scroggins160a7e72009-08-14 18:28:01 -04003496 */
Leon Scroggins30444232009-09-04 18:36:20 -04003497 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003498 WebView current = mTabControl.getCurrentWebView();
3499 if (current == null) {
3500 return;
3501 }
3502 Intent intent = new Intent(this,
3503 CombinedBookmarkHistoryActivity.class);
3504 String title = current.getTitle();
3505 String url = current.getUrl();
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003506 Bitmap thumbnail = createScreenshot(current);
3507
The Android Open Source Project0c908882009-03-03 19:32:16 -08003508 // Just in case the user opens bookmarks before a page finishes loading
3509 // so the current history item, and therefore the page, is null.
3510 if (null == url) {
3511 url = mLastEnteredUrl;
3512 // This can happen.
3513 if (null == url) {
3514 url = mSettings.getHomePage();
3515 }
3516 }
3517 // In case the web page has not yet received its associated title.
3518 if (title == null) {
3519 title = url;
3520 }
3521 intent.putExtra("title", title);
3522 intent.putExtra("url", url);
Ben Murdochdcc2b6f2009-09-21 14:29:20 +01003523 intent.putExtra("thumbnail", thumbnail);
Leon Scroggins30444232009-09-04 18:36:20 -04003524 // Disable opening in a new window if we have maxed out the windows
Grace Kloba22ac16e2009-10-07 18:00:23 -07003525 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
Patrick Scott3918d442009-08-04 13:22:29 -04003526 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003527 if (startWithHistory) {
3528 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3529 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3530 }
3531 startActivityForResult(intent, COMBO_PAGE);
3532 }
3533
3534 // Called when loading from context menu or LOAD_URL message
Leon Scroggins92472e82010-02-17 16:32:28 -05003535 private void loadUrlFromContext(WebView view, String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003536 // In case the user enters nothing.
3537 if (url != null && url.length() != 0 && view != null) {
3538 url = smartUrlFilter(url);
Grace Kloba22ac16e2009-10-07 18:00:23 -07003539 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
Leon Scroggins92472e82010-02-17 16:32:28 -05003540 loadUrl(view, url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541 }
3542 }
3543 }
3544
Leon Scroggins92472e82010-02-17 16:32:28 -05003545 /**
3546 * Load the URL into the given WebView and update the title bar
3547 * to reflect the new load. Call this instead of WebView.loadUrl
3548 * directly.
3549 * @param view The WebView used to load url.
3550 * @param url The URL to load.
3551 */
3552 private void loadUrl(WebView view, String url) {
3553 updateTitleBarForNewLoad(view, url);
3554 view.loadUrl(url);
3555 }
3556
3557 /**
3558 * Load UrlData into a Tab and update the title bar to reflect the new
3559 * load. Call this instead of UrlData.loadIn directly.
3560 * @param t The Tab used to load.
3561 * @param data The UrlData being loaded.
3562 */
3563 private void loadUrlDataIn(Tab t, UrlData data) {
3564 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3565 data.loadIn(t);
3566 }
3567
3568 /**
3569 * If the WebView is the top window, update the title bar to reflect
3570 * loading the new URL. i.e. set its text, clear the favicon (which
3571 * will be set once the page begins loading), and set the progress to
3572 * INITIAL_PROGRESS to show that the page has begun to load. Called
3573 * by loadUrl and loadUrlDataIn.
3574 * @param view The WebView that is starting a load.
3575 * @param url The URL that is being loaded.
3576 */
3577 private void updateTitleBarForNewLoad(WebView view, String url) {
3578 if (view == getTopWindow()) {
3579 setUrlTitle(url, null);
3580 setFavicon(null);
3581 onProgressChanged(view, INITIAL_PROGRESS);
3582 }
3583 }
3584
The Android Open Source Project0c908882009-03-03 19:32:16 -08003585 private String smartUrlFilter(Uri inUri) {
3586 if (inUri != null) {
3587 return smartUrlFilter(inUri.toString());
3588 }
3589 return null;
3590 }
3591
Feng Qianb34f87a2009-03-24 21:27:26 -07003592 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08003593 "(?i)" + // switch on case insensitive matching
3594 "(" + // begin group for schema
3595 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003596 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08003597 ")" +
3598 "(.*)" );
3599
3600 /**
3601 * Attempts to determine whether user input is a URL or search
3602 * terms. Anything with a space is passed to search.
3603 *
3604 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3605 * "Http://" converts to "http://"
3606 *
3607 * @return Original or modified URL
3608 *
3609 */
3610 String smartUrlFilter(String url) {
3611
3612 String inUrl = url.trim();
3613 boolean hasSpace = inUrl.indexOf(' ') != -1;
3614
3615 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3616 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003617 // force scheme to lowercase
3618 String scheme = matcher.group(1);
3619 String lcScheme = scheme.toLowerCase();
3620 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07003621 inUrl = lcScheme + matcher.group(2);
3622 }
3623 if (hasSpace) {
3624 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08003625 }
3626 return inUrl;
3627 }
3628 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01003629 // FIXME: Is this the correct place to add to searches?
3630 // what if someone else calls this function?
3631 int shortcut = parseUrlShortcut(inUrl);
3632 if (shortcut != SHORTCUT_INVALID) {
3633 Browser.addSearchUrl(mResolver, inUrl);
3634 String query = inUrl.substring(2);
3635 switch (shortcut) {
3636 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003637 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01003638 case SHORTCUT_WIKIPEDIA_SEARCH:
3639 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3640 case SHORTCUT_DICTIONARY_SEARCH:
3641 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3642 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08003643 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01003644 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003645 }
3646 }
3647 } else {
Dan Egnor5ee906c2009-11-18 12:11:49 -08003648 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003649 return URLUtil.guessUrl(inUrl);
3650 }
3651 }
3652
3653 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003654 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003655 }
3656
Ben Murdochbff2d602009-07-01 20:19:05 +01003657 /* package */ void setShouldShowErrorConsole(boolean flag) {
3658 if (flag == mShouldShowErrorConsole) {
3659 // Nothing to do.
3660 return;
3661 }
3662
3663 mShouldShowErrorConsole = flag;
3664
Grace Kloba22ac16e2009-10-07 18:00:23 -07003665 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3666 .getErrorConsole(true);
Ben Murdochbff2d602009-07-01 20:19:05 +01003667
3668 if (flag) {
3669 // Setting the show state of the console will cause it's the layout to be inflated.
3670 if (errorConsole.numberOfErrors() > 0) {
3671 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3672 } else {
3673 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3674 }
3675
3676 // Now we can add it to the main view.
3677 mErrorConsoleContainer.addView(errorConsole,
Romain Guy15b8ec62010-01-08 15:06:43 -08003678 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
Ben Murdochbff2d602009-07-01 20:19:05 +01003679 ViewGroup.LayoutParams.WRAP_CONTENT));
3680 } else {
3681 mErrorConsoleContainer.removeView(errorConsole);
3682 }
3683
3684 }
3685
Grace Kloba22ac16e2009-10-07 18:00:23 -07003686 boolean shouldShowErrorConsole() {
3687 return mShouldShowErrorConsole;
3688 }
3689
Andrei Popescu163ab742009-10-20 17:58:23 +01003690 private void setStatusBarVisibility(boolean visible) {
3691 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3692 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3693 }
3694
Andrei Popescu56199cc2010-01-12 22:39:16 +00003695
3696 private void sendNetworkType(String type, String subtype) {
3697 WebView w = mTabControl.getCurrentWebView();
3698 if (w != null) {
3699 w.setNetworkType(type, subtype);
3700 }
3701 }
3702
Andrei Popescu30995e72010-02-09 16:59:58 +00003703 private void packageChanged(String packageName, boolean wasAdded) {
3704 WebView w = mTabControl.getCurrentWebView();
3705 if (w == null) {
3706 return;
3707 }
3708
3709 if (wasAdded) {
3710 w.addPackageName(packageName);
3711 } else {
3712 w.removePackageName(packageName);
3713 }
3714 }
3715
3716 private void addPackageNames(Set<String> packageNames) {
3717 WebView w = mTabControl.getCurrentWebView();
3718 if (w == null) {
3719 return;
3720 }
3721
3722 w.addPackageNames(packageNames);
3723 }
3724
3725 private void getInstalledPackages() {
3726 AsyncTask<Void, Void, Set<String> > task =
3727 new AsyncTask<Void, Void, Set<String> >() {
3728 protected Set<String> doInBackground(Void... unused) {
3729 Set<String> installedPackages = new HashSet<String>();
3730 PackageManager pm = BrowserActivity.this.getPackageManager();
3731 if (pm != null) {
3732 List<PackageInfo> packages = pm.getInstalledPackages(0);
3733 for (PackageInfo p : packages) {
3734 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3735 installedPackages.add(p.packageName);
3736 }
3737 }
3738 }
3739
3740 return installedPackages;
3741 }
3742
3743 // Executes on the UI thread
3744 protected void onPostExecute(Set<String> installedPackages) {
3745 addPackageNames(installedPackages);
3746 }
3747 };
3748 task.execute();
3749 }
3750
Grace Klobaeb6eef42009-09-15 17:56:32 -07003751 final static int LOCK_ICON_UNSECURE = 0;
3752 final static int LOCK_ICON_SECURE = 1;
3753 final static int LOCK_ICON_MIXED = 2;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003754
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755 private BrowserSettings mSettings;
3756 private TabControl mTabControl;
3757 private ContentResolver mResolver;
3758 private FrameLayout mContentView;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003759 private View mCustomView;
3760 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003761 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003762
3763 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3764 // view, we should rewrite this.
3765 private int mCurrentMenuState = 0;
3766 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003767 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003768 private static final int EMPTY_MENU = -1;
3769 private Menu mMenu;
3770
3771 private FindDialog mFindDialog;
3772 // Used to prevent chording to result in firing two shortcuts immediately
3773 // one after another. Fixes bug 1211714.
3774 boolean mCanChord;
3775
3776 private boolean mInLoad;
3777 private boolean mIsNetworkUp;
Ben Murdochb7cc8b42009-09-28 10:59:09 +01003778 private boolean mDidStopLoad;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003779
Cary Clark1f10cbf2010-03-22 11:45:23 -04003780 /* package */ boolean mActivityInPause = true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003781
3782 private boolean mMenuIsDown;
3783
The Android Open Source Project0c908882009-03-03 19:32:16 -08003784 private static boolean mInTrace;
3785
3786 // Performance probe
3787 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3788 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3789 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3790 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3791 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3792 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3793 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3794 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3795 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3796 };
3797
3798 private long mStart;
3799 private long mProcessStart;
3800 private long mUserStart;
3801 private long mSystemStart;
3802 private long mIdleStart;
3803 private long mIrqStart;
3804
3805 private long mUiStart;
3806
3807 private Drawable mMixLockIcon;
3808 private Drawable mSecLockIcon;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003809
3810 /* hold a ref so we can auto-cancel if necessary */
3811 private AlertDialog mAlertDialog;
3812
The Android Open Source Project0c908882009-03-03 19:32:16 -08003813 // The up-to-date URL and title (these can be different from those stored
3814 // in WebView, since it takes some time for the information in WebView to
3815 // get updated)
3816 private String mUrl;
3817 private String mTitle;
3818
3819 // As PageInfo has different style for landscape / portrait, we have
3820 // to re-open it when configuration changed
3821 private AlertDialog mPageInfoDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003822 private Tab mPageInfoView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003823 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3824 // dialog, we should not just dismiss it, but should get back to the
3825 // SSL-certificate-on-error dialog. This flag is used to store this state
Leon Scrogginsc7b92f82010-01-11 18:17:31 -05003826 private boolean mPageInfoFromShowSSLCertificateOnError;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003827
3828 // as SSLCertificateOnError has different style for landscape / portrait,
3829 // we have to re-open it when configuration changed
3830 private AlertDialog mSSLCertificateOnErrorDialog;
3831 private WebView mSSLCertificateOnErrorView;
3832 private SslErrorHandler mSSLCertificateOnErrorHandler;
3833 private SslError mSSLCertificateOnErrorError;
3834
3835 // as SSLCertificate has different style for landscape / portrait, we
3836 // have to re-open it when configuration changed
3837 private AlertDialog mSSLCertificateDialog;
Grace Kloba22ac16e2009-10-07 18:00:23 -07003838 private Tab mSSLCertificateView;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003839
3840 // as HttpAuthentication has different style for landscape / portrait, we
3841 // have to re-open it when configuration changed
3842 private AlertDialog mHttpAuthenticationDialog;
3843 private HttpAuthHandler mHttpAuthHandler;
3844
3845 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3846 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003847 ViewGroup.LayoutParams.MATCH_PARENT,
3848 ViewGroup.LayoutParams.MATCH_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003849 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3850 new FrameLayout.LayoutParams(
Romain Guy15b8ec62010-01-08 15:06:43 -08003851 ViewGroup.LayoutParams.MATCH_PARENT,
3852 ViewGroup.LayoutParams.MATCH_PARENT,
Andrei Popescuadc008d2009-06-26 14:11:30 +01003853 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07003854 // Google search
3855 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08003856 // Wikipedia search
3857 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3858 // Dictionary search
3859 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3860 // Google Mobile Local search
3861 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3862
3863 final static String QUERY_PLACE_HOLDER = "%s";
3864
3865 // "source" parameter for Google search through search key
3866 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3867 // "source" parameter for Google search through goto menu
3868 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3869 // "source" parameter for Google search through simplily type
3870 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3871 // "source" parameter for Google search suggested by the browser
3872 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3873 // "source" parameter for Google search from unknown source
3874 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3875
3876 private final static String LOGTAG = "browser";
3877
The Android Open Source Project0c908882009-03-03 19:32:16 -08003878 private String mLastEnteredUrl;
3879
3880 private PowerManager.WakeLock mWakeLock;
3881 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3882
3883 private Toast mStopToast;
3884
Leon Scroggins68579392009-09-15 15:31:54 -04003885 private TitleBar mTitleBar;
Leon Scroggins81db3662009-06-04 17:45:11 -04003886
Ben Murdochbff2d602009-07-01 20:19:05 +01003887 private LinearLayout mErrorConsoleContainer = null;
3888 private boolean mShouldShowErrorConsole = false;
3889
The Android Open Source Project0c908882009-03-03 19:32:16 -08003890 // As the ids are dynamically created, we can't guarantee that they will
3891 // be in sequence, so this static array maps ids to a window number.
3892 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3893 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3894 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3895 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3896
3897 // monitor platform changes
3898 private IntentFilter mNetworkStateChangedFilter;
3899 private BroadcastReceiver mNetworkStateIntentReceiver;
3900
Grace Klobab4da0ad2009-05-14 14:45:40 -07003901 private BroadcastReceiver mPackageInstallationReceiver;
3902
Bjorn Bringerta7611812010-03-24 11:12:02 +00003903 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3904
The Android Open Source Project0c908882009-03-03 19:32:16 -08003905 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01003906 final static int COMBO_PAGE = 1;
3907 final static int DOWNLOAD_PAGE = 2;
3908 final static int PREFERENCES_PAGE = 3;
Leon Scroggins8d5fa432009-10-02 15:55:59 -04003909 final static int FILE_SELECTED = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08003910
Andrei Popescu540035d2009-09-18 18:59:20 +01003911 // the default <video> poster
3912 private Bitmap mDefaultVideoPoster;
3913 // the video progress view
3914 private View mVideoProgressView;
3915
Andrei Popescu30995e72010-02-09 16:59:58 +00003916 // The Google packages we monitor for the navigator.isApplicationInstalled()
3917 // API. Add as needed.
3918 private static Set<String> sGoogleApps;
3919 static {
3920 sGoogleApps = new HashSet<String>();
3921 sGoogleApps.add("com.google.android.youtube");
3922 }
3923
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003924 /**
3925 * A UrlData class to abstract how the content will be set to WebView.
3926 * This base class uses loadUrl to show the content.
3927 */
Leon Scroggins6eac63e2010-03-15 18:19:14 -04003928 /* package */ static class UrlData {
Grace Kloba068e48b2010-01-26 18:11:27 -08003929 final String mUrl;
3930 final Map<String, String> mHeaders;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003931 final Intent mVoiceIntent;
Grace Kloba60e095c2009-06-16 11:50:55 -07003932
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003933 UrlData(String url) {
3934 this.mUrl = url;
Grace Kloba068e48b2010-01-26 18:11:27 -08003935 this.mHeaders = null;
Leon Scroggins58d56c62010-01-28 15:12:40 -05003936 this.mVoiceIntent = null;
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003937 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003938
Leon Scroggins58d56c62010-01-28 15:12:40 -05003939 UrlData(String url, Map<String, String> headers, Intent intent) {
Grace Kloba068e48b2010-01-26 18:11:27 -08003940 this.mUrl = url;
3941 this.mHeaders = headers;
Leon Scrogginsa1cc3fd2010-02-01 16:14:11 -05003942 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3943 .equals(intent.getAction())) {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003944 this.mVoiceIntent = intent;
3945 } else {
3946 this.mVoiceIntent = null;
3947 }
Grace Kloba60e095c2009-06-16 11:50:55 -07003948 }
3949
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003950 boolean isEmpty() {
Leon Scroggins58d56c62010-01-28 15:12:40 -05003951 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003952 }
3953
Leon Scroggins92472e82010-02-17 16:32:28 -05003954 /**
3955 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3956 * the title bar as well.
3957 */
Leon Scroggins58d56c62010-01-28 15:12:40 -05003958 public void loadIn(Tab t) {
3959 if (mVoiceIntent != null) {
3960 t.activateVoiceSearchMode(mVoiceIntent);
3961 } else {
3962 t.getWebView().loadUrl(mUrl, mHeaders);
3963 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07003964 }
3965 };
3966
Leon Scroggins1f005d32009-08-10 17:36:42 -04003967 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003968}